babylon.max.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", [], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. /**
  31. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  32. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  33. */
  34. var EffectFallbacks = /** @class */ (function () {
  35. function EffectFallbacks() {
  36. this._defines = {};
  37. this._currentRank = 32;
  38. this._maxRank = -1;
  39. }
  40. /**
  41. * Removes the fallback from the bound mesh.
  42. */
  43. EffectFallbacks.prototype.unBindMesh = function () {
  44. this._mesh = null;
  45. };
  46. /**
  47. * Adds a fallback on the specified property.
  48. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  49. * @param define The name of the define in the shader
  50. */
  51. EffectFallbacks.prototype.addFallback = function (rank, define) {
  52. if (!this._defines[rank]) {
  53. if (rank < this._currentRank) {
  54. this._currentRank = rank;
  55. }
  56. if (rank > this._maxRank) {
  57. this._maxRank = rank;
  58. }
  59. this._defines[rank] = new Array();
  60. }
  61. this._defines[rank].push(define);
  62. };
  63. /**
  64. * Sets the mesh to use CPU skinning when needing to fallback.
  65. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  66. * @param mesh The mesh to use the fallbacks.
  67. */
  68. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  69. this._mesh = mesh;
  70. if (rank < this._currentRank) {
  71. this._currentRank = rank;
  72. }
  73. if (rank > this._maxRank) {
  74. this._maxRank = rank;
  75. }
  76. };
  77. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  78. /**
  79. * Checks to see if more fallbacks are still availible.
  80. */
  81. get: function () {
  82. return this._currentRank <= this._maxRank;
  83. },
  84. enumerable: true,
  85. configurable: true
  86. });
  87. /**
  88. * Removes the defines that shoould be removed when falling back.
  89. * @param currentDefines defines the current define statements for the shader.
  90. * @param effect defines the current effect we try to compile
  91. * @returns The resulting defines with defines of the current rank removed.
  92. */
  93. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  94. // First we try to switch to CPU skinning
  95. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  96. this._mesh.computeBonesUsingShaders = false;
  97. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  98. var scene = this._mesh.getScene();
  99. for (var index = 0; index < scene.meshes.length; index++) {
  100. var otherMesh = scene.meshes[index];
  101. if (!otherMesh.material) {
  102. continue;
  103. }
  104. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  105. continue;
  106. }
  107. if (otherMesh.material.getEffect() === effect) {
  108. otherMesh.computeBonesUsingShaders = false;
  109. }
  110. else {
  111. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  112. var subMesh = _a[_i];
  113. var subMeshEffect = subMesh.effect;
  114. if (subMeshEffect === effect) {
  115. otherMesh.computeBonesUsingShaders = false;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. var currentFallbacks = this._defines[this._currentRank];
  124. if (currentFallbacks) {
  125. for (var index = 0; index < currentFallbacks.length; index++) {
  126. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  127. }
  128. }
  129. this._currentRank++;
  130. }
  131. return currentDefines;
  132. };
  133. return EffectFallbacks;
  134. }());
  135. BABYLON.EffectFallbacks = EffectFallbacks;
  136. /**
  137. * Options to be used when creating an effect.
  138. */
  139. var EffectCreationOptions = /** @class */ (function () {
  140. function EffectCreationOptions() {
  141. }
  142. return EffectCreationOptions;
  143. }());
  144. BABYLON.EffectCreationOptions = EffectCreationOptions;
  145. /**
  146. * Effect containing vertex and fragment shader that can be executed on an object.
  147. */
  148. var Effect = /** @class */ (function () {
  149. /**
  150. * Instantiates an effect.
  151. * An effect can be used to create/manage/execute vertex and fragment shaders.
  152. * @param baseName Name of the effect.
  153. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  154. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  155. * @param samplers List of sampler variables that will be passed to the shader.
  156. * @param engine Engine to be used to render the effect
  157. * @param defines Define statements to be added to the shader.
  158. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  159. * @param onCompiled Callback that will be called when the shader is compiled.
  160. * @param onError Callback that will be called if an error occurs during shader compilation.
  161. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  162. */
  163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  164. if (samplers === void 0) { samplers = null; }
  165. if (defines === void 0) { defines = null; }
  166. if (fallbacks === void 0) { fallbacks = null; }
  167. if (onCompiled === void 0) { onCompiled = null; }
  168. if (onError === void 0) { onError = null; }
  169. var _this = this;
  170. /**
  171. * Unique ID of the effect.
  172. */
  173. this.uniqueId = 0;
  174. /**
  175. * Observable that will be called when the shader is compiled.
  176. */
  177. this.onCompileObservable = new BABYLON.Observable();
  178. /**
  179. * Observable that will be called if an error occurs during shader compilation.
  180. */
  181. this.onErrorObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called when effect is bound.
  184. */
  185. this.onBindObservable = new BABYLON.Observable();
  186. this._uniformBuffersNames = {};
  187. this._isReady = false;
  188. this._compilationError = "";
  189. this.name = baseName;
  190. if (attributesNamesOrOptions.attributes) {
  191. var options = attributesNamesOrOptions;
  192. this._engine = uniformsNamesOrEngine;
  193. this._attributesNames = options.attributes;
  194. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  195. this._samplers = options.samplers;
  196. this.defines = options.defines;
  197. this.onError = options.onError;
  198. this.onCompiled = options.onCompiled;
  199. this._fallbacks = options.fallbacks;
  200. this._indexParameters = options.indexParameters;
  201. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  202. if (options.uniformBuffersNames) {
  203. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  204. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  205. }
  206. }
  207. }
  208. else {
  209. this._engine = engine;
  210. this.defines = defines;
  211. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  212. this._samplers = samplers;
  213. this._attributesNames = attributesNamesOrOptions;
  214. this.onError = onError;
  215. this.onCompiled = onCompiled;
  216. this._indexParameters = indexParameters;
  217. this._fallbacks = fallbacks;
  218. }
  219. this.uniqueId = Effect._uniqueIdSeed++;
  220. if (this._getFromCache(baseName)) {
  221. this._prepareEffect();
  222. return;
  223. }
  224. var vertexSource;
  225. var fragmentSource;
  226. if (baseName.vertexElement) {
  227. vertexSource = document.getElementById(baseName.vertexElement);
  228. if (!vertexSource) {
  229. vertexSource = baseName.vertexElement;
  230. }
  231. }
  232. else {
  233. vertexSource = baseName.vertex || baseName;
  234. }
  235. if (baseName.fragmentElement) {
  236. fragmentSource = document.getElementById(baseName.fragmentElement);
  237. if (!fragmentSource) {
  238. fragmentSource = baseName.fragmentElement;
  239. }
  240. }
  241. else {
  242. fragmentSource = baseName.fragment || baseName;
  243. }
  244. var finalVertexCode;
  245. this._loadVertexShaderAsync(vertexSource)
  246. .then(function (vertexCode) {
  247. return _this._processIncludesAsync(vertexCode);
  248. })
  249. .then(function (vertexCodeWithIncludes) {
  250. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  251. return _this._loadFragmentShaderAsync(fragmentSource);
  252. })
  253. .then(function (fragmentCode) {
  254. return _this._processIncludesAsync(fragmentCode);
  255. })
  256. .then(function (fragmentCodeWithIncludes) {
  257. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  258. if (baseName) {
  259. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  260. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  261. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  262. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  263. }
  264. else {
  265. _this._vertexSourceCode = finalVertexCode;
  266. _this._fragmentSourceCode = migratedFragmentCode;
  267. }
  268. _this._setInCache(baseName);
  269. _this._prepareEffect();
  270. });
  271. }
  272. Effect.prototype._getSourceCacheKey = function (baseName) {
  273. var cacheKey = baseName;
  274. if (this._indexParameters) {
  275. for (var key in this._indexParameters) {
  276. if (this._indexParameters.hasOwnProperty(key)) {
  277. cacheKey += "|";
  278. cacheKey += key;
  279. cacheKey += "_";
  280. cacheKey += this._indexParameters[key];
  281. }
  282. }
  283. }
  284. return cacheKey;
  285. };
  286. Effect.prototype._getFromCache = function (baseName) {
  287. if (typeof baseName !== "string") {
  288. return false;
  289. }
  290. var cacheKey = this._getSourceCacheKey(baseName);
  291. var sources = Effect._sourceCache[cacheKey];
  292. if (!sources) {
  293. return false;
  294. }
  295. this._vertexSourceCode = sources.vertex;
  296. this._fragmentSourceCode = sources.fragment;
  297. return true;
  298. };
  299. Effect.prototype._setInCache = function (baseName) {
  300. if (typeof baseName !== "string") {
  301. return;
  302. }
  303. var cacheKey = this._getSourceCacheKey(baseName);
  304. Effect._sourceCache[cacheKey] = {
  305. vertex: this._vertexSourceCode,
  306. fragment: this._fragmentSourceCode
  307. };
  308. };
  309. Object.defineProperty(Effect.prototype, "key", {
  310. /**
  311. * Unique key for this effect
  312. */
  313. get: function () {
  314. return this._key;
  315. },
  316. enumerable: true,
  317. configurable: true
  318. });
  319. /**
  320. * If the effect has been compiled and prepared.
  321. * @returns if the effect is compiled and prepared.
  322. */
  323. Effect.prototype.isReady = function () {
  324. return this._isReady;
  325. };
  326. /**
  327. * The engine the effect was initialized with.
  328. * @returns the engine.
  329. */
  330. Effect.prototype.getEngine = function () {
  331. return this._engine;
  332. };
  333. /**
  334. * The compiled webGL program for the effect
  335. * @returns the webGL program.
  336. */
  337. Effect.prototype.getProgram = function () {
  338. return this._program;
  339. };
  340. /**
  341. * The set of names of attribute variables for the shader.
  342. * @returns An array of attribute names.
  343. */
  344. Effect.prototype.getAttributesNames = function () {
  345. return this._attributesNames;
  346. };
  347. /**
  348. * Returns the attribute at the given index.
  349. * @param index The index of the attribute.
  350. * @returns The location of the attribute.
  351. */
  352. Effect.prototype.getAttributeLocation = function (index) {
  353. return this._attributes[index];
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param name of the attribute to look up.
  358. * @returns the attribute location.
  359. */
  360. Effect.prototype.getAttributeLocationByName = function (name) {
  361. var index = this._attributesNames.indexOf(name);
  362. return this._attributes[index];
  363. };
  364. /**
  365. * The number of attributes.
  366. * @returns the numnber of attributes.
  367. */
  368. Effect.prototype.getAttributesCount = function () {
  369. return this._attributes.length;
  370. };
  371. /**
  372. * Gets the index of a uniform variable.
  373. * @param uniformName of the uniform to look up.
  374. * @returns the index.
  375. */
  376. Effect.prototype.getUniformIndex = function (uniformName) {
  377. return this._uniformsNames.indexOf(uniformName);
  378. };
  379. /**
  380. * Returns the attribute based on the name of the variable.
  381. * @param uniformName of the uniform to look up.
  382. * @returns the location of the uniform.
  383. */
  384. Effect.prototype.getUniform = function (uniformName) {
  385. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  386. };
  387. /**
  388. * Returns an array of sampler variable names
  389. * @returns The array of sampler variable neames.
  390. */
  391. Effect.prototype.getSamplers = function () {
  392. return this._samplers;
  393. };
  394. /**
  395. * The error from the last compilation.
  396. * @returns the error string.
  397. */
  398. Effect.prototype.getCompilationError = function () {
  399. return this._compilationError;
  400. };
  401. /**
  402. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  403. * @param func The callback to be used.
  404. */
  405. Effect.prototype.executeWhenCompiled = function (func) {
  406. if (this.isReady()) {
  407. func(this);
  408. return;
  409. }
  410. this.onCompileObservable.add(function (effect) {
  411. func(effect);
  412. });
  413. };
  414. /** @ignore */
  415. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (vertex instanceof HTMLElement) {
  419. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  420. return Promise.resolve(vertexCode);
  421. }
  422. }
  423. // Base64 encoded ?
  424. if (vertex.substr(0, 7) === "base64:") {
  425. var vertexBinary = window.atob(vertex.substr(7));
  426. return Promise.resolve(vertexBinary);
  427. }
  428. // Is in local store ?
  429. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  430. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  431. }
  432. var vertexShaderUrl;
  433. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  434. vertexShaderUrl = vertex;
  435. }
  436. else {
  437. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  438. }
  439. // Vertex shader
  440. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  441. };
  442. /** @ignore */
  443. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  444. if (BABYLON.Tools.IsWindowObjectExist()) {
  445. // DOM element ?
  446. if (fragment instanceof HTMLElement) {
  447. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  448. return Promise.resolve(fragmentCode);
  449. }
  450. }
  451. // Base64 encoded ?
  452. if (fragment.substr(0, 7) === "base64:") {
  453. var fragmentBinary = window.atob(fragment.substr(7));
  454. return Promise.resolve(fragmentBinary);
  455. }
  456. // Is in local store ?
  457. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  458. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  459. }
  460. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  461. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  462. }
  463. var fragmentShaderUrl;
  464. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  465. fragmentShaderUrl = fragment;
  466. }
  467. else {
  468. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  469. }
  470. // Fragment shader
  471. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  472. };
  473. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  474. // Rebuild shaders source code
  475. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  476. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  477. vertexCode = prefix + vertexCode;
  478. fragmentCode = prefix + fragmentCode;
  479. // Number lines of shaders source code
  480. var i = 2;
  481. var regex = /\n/gm;
  482. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  483. i = 2;
  484. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  485. // Dump shaders name and formatted source code
  486. if (this.name.vertexElement) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  489. }
  490. else if (this.name.vertex) {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  493. }
  494. else {
  495. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  496. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  497. }
  498. };
  499. ;
  500. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  501. var preparedSourceCode = this._processPrecision(sourceCode);
  502. if (this._engine.webGLVersion == 1) {
  503. return preparedSourceCode;
  504. }
  505. // Already converted
  506. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  507. return preparedSourceCode.replace("#version 300 es", "");
  508. }
  509. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  510. // Remove extensions
  511. // #extension GL_OES_standard_derivatives : enable
  512. // #extension GL_EXT_shader_texture_lod : enable
  513. // #extension GL_EXT_frag_depth : enable
  514. // #extension GL_EXT_draw_buffers : require
  515. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  516. var result = preparedSourceCode.replace(regex, "");
  517. // Migrate to GLSL v300
  518. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  519. result = result.replace(/attribute[ \t]/g, "in ");
  520. result = result.replace(/[ \t]attribute/g, " in");
  521. if (isFragment) {
  522. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  523. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/texture2D\s*\(/g, "texture(");
  525. result = result.replace(/textureCube\s*\(/g, "texture(");
  526. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  527. result = result.replace(/gl_FragColor/g, "glFragColor");
  528. result = result.replace(/gl_FragData/g, "glFragData");
  529. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  530. }
  531. return result;
  532. };
  533. Effect.prototype._processIncludesAsync = function (sourceCode) {
  534. var _this = this;
  535. return new Promise(function (resolve, reject) {
  536. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  537. var match = regex.exec(sourceCode);
  538. var returnValue = sourceCode;
  539. while (match != null) {
  540. var includeFile = match[1];
  541. // Uniform declaration
  542. if (includeFile.indexOf("__decl__") !== -1) {
  543. includeFile = includeFile.replace(/__decl__/, "");
  544. if (_this._engine.supportsUniformBuffers) {
  545. includeFile = includeFile.replace(/Vertex/, "Ubo");
  546. includeFile = includeFile.replace(/Fragment/, "Ubo");
  547. }
  548. includeFile = includeFile + "Declaration";
  549. }
  550. if (Effect.IncludesShadersStore[includeFile]) {
  551. // Substitution
  552. var includeContent = Effect.IncludesShadersStore[includeFile];
  553. if (match[2]) {
  554. var splits = match[3].split(",");
  555. for (var index = 0; index < splits.length; index += 2) {
  556. var source = new RegExp(splits[index], "g");
  557. var dest = splits[index + 1];
  558. includeContent = includeContent.replace(source, dest);
  559. }
  560. }
  561. if (match[4]) {
  562. var indexString = match[5];
  563. if (indexString.indexOf("..") !== -1) {
  564. var indexSplits = indexString.split("..");
  565. var minIndex = parseInt(indexSplits[0]);
  566. var maxIndex = parseInt(indexSplits[1]);
  567. var sourceIncludeContent = includeContent.slice(0);
  568. includeContent = "";
  569. if (isNaN(maxIndex)) {
  570. maxIndex = _this._indexParameters[indexSplits[1]];
  571. }
  572. for (var i = minIndex; i < maxIndex; i++) {
  573. if (!_this._engine.supportsUniformBuffers) {
  574. // Ubo replacement
  575. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  576. return p1 + "{X}";
  577. });
  578. }
  579. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  580. }
  581. }
  582. else {
  583. if (!_this._engine.supportsUniformBuffers) {
  584. // Ubo replacement
  585. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  586. return p1 + "{X}";
  587. });
  588. }
  589. includeContent = includeContent.replace(/\{X\}/g, indexString);
  590. }
  591. }
  592. // Replace
  593. returnValue = returnValue.replace(match[0], includeContent);
  594. }
  595. else {
  596. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  597. _this._engine._loadFileAsync(includeShaderUrl)
  598. .then(function (fileContent) {
  599. Effect.IncludesShadersStore[includeFile] = fileContent;
  600. return _this._processIncludesAsync(returnValue);
  601. })
  602. .then(function (returnValue) {
  603. resolve(returnValue);
  604. });
  605. return;
  606. }
  607. match = regex.exec(sourceCode);
  608. }
  609. resolve(returnValue);
  610. });
  611. };
  612. Effect.prototype._processPrecision = function (source) {
  613. if (source.indexOf("precision highp float") === -1) {
  614. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  615. source = "precision mediump float;\n" + source;
  616. }
  617. else {
  618. source = "precision highp float;\n" + source;
  619. }
  620. }
  621. else {
  622. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  623. source = source.replace("precision highp float", "precision mediump float");
  624. }
  625. }
  626. return source;
  627. };
  628. /**
  629. * Recompiles the webGL program
  630. * @param vertexSourceCode The source code for the vertex shader.
  631. * @param fragmentSourceCode The source code for the fragment shader.
  632. * @param onCompiled Callback called when completed.
  633. * @param onError Callback called on error.
  634. */
  635. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  636. var _this = this;
  637. this._isReady = false;
  638. this._vertexSourceCodeOverride = vertexSourceCode;
  639. this._fragmentSourceCodeOverride = fragmentSourceCode;
  640. this.onError = function (effect, error) {
  641. if (onError) {
  642. onError(error);
  643. }
  644. };
  645. this.onCompiled = function () {
  646. var scenes = _this.getEngine().scenes;
  647. for (var i = 0; i < scenes.length; i++) {
  648. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  649. }
  650. if (onCompiled) {
  651. onCompiled(_this._program);
  652. }
  653. };
  654. this._fallbacks = null;
  655. this._prepareEffect();
  656. };
  657. /**
  658. * Gets the uniform locations of the the specified variable names
  659. * @param names THe names of the variables to lookup.
  660. * @returns Array of locations in the same order as variable names.
  661. */
  662. Effect.prototype.getSpecificUniformLocations = function (names) {
  663. var engine = this._engine;
  664. return engine.getUniforms(this._program, names);
  665. };
  666. /**
  667. * Prepares the effect
  668. */
  669. Effect.prototype._prepareEffect = function () {
  670. var attributesNames = this._attributesNames;
  671. var defines = this.defines;
  672. var fallbacks = this._fallbacks;
  673. this._valueCache = {};
  674. var previousProgram = this._program;
  675. try {
  676. var engine = this._engine;
  677. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  678. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  679. }
  680. else {
  681. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  682. }
  683. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  684. if (engine.supportsUniformBuffers) {
  685. for (var name in this._uniformBuffersNames) {
  686. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  687. }
  688. }
  689. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  690. this._attributes = engine.getAttributes(this._program, attributesNames);
  691. var index;
  692. for (index = 0; index < this._samplers.length; index++) {
  693. var sampler = this.getUniform(this._samplers[index]);
  694. if (sampler == null) {
  695. this._samplers.splice(index, 1);
  696. index--;
  697. }
  698. }
  699. engine.bindSamplers(this);
  700. this._compilationError = "";
  701. this._isReady = true;
  702. if (this.onCompiled) {
  703. this.onCompiled(this);
  704. }
  705. this.onCompileObservable.notifyObservers(this);
  706. this.onCompileObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. if (previousProgram) {
  712. this.getEngine()._deleteProgram(previousProgram);
  713. }
  714. }
  715. catch (e) {
  716. this._compilationError = e.message;
  717. // Let's go through fallbacks then
  718. BABYLON.Tools.Error("Unable to compile effect:");
  719. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  720. return " " + uniform;
  721. }));
  722. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  723. return " " + attribute;
  724. }));
  725. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  726. BABYLON.Tools.Error("Error: " + this._compilationError);
  727. if (previousProgram) {
  728. this._program = previousProgram;
  729. this._isReady = true;
  730. if (this.onError) {
  731. this.onError(this, this._compilationError);
  732. }
  733. this.onErrorObservable.notifyObservers(this);
  734. }
  735. if (fallbacks && fallbacks.isMoreFallbacks) {
  736. BABYLON.Tools.Error("Trying next fallback.");
  737. this.defines = fallbacks.reduce(this.defines, this);
  738. this._prepareEffect();
  739. }
  740. else {
  741. if (this.onError) {
  742. this.onError(this, this._compilationError);
  743. }
  744. this.onErrorObservable.notifyObservers(this);
  745. this.onErrorObservable.clear();
  746. // Unbind mesh reference in fallbacks
  747. if (this._fallbacks) {
  748. this._fallbacks.unBindMesh();
  749. }
  750. }
  751. }
  752. };
  753. Object.defineProperty(Effect.prototype, "isSupported", {
  754. /**
  755. * Checks if the effect is supported. (Must be called after compilation)
  756. */
  757. get: function () {
  758. return this._compilationError === "";
  759. },
  760. enumerable: true,
  761. configurable: true
  762. });
  763. /**
  764. * Binds a texture to the engine to be used as output of the shader.
  765. * @param channel Name of the output variable.
  766. * @param texture Texture to bind.
  767. */
  768. Effect.prototype._bindTexture = function (channel, texture) {
  769. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  770. };
  771. /**
  772. * Sets a texture on the engine to be used in the shader.
  773. * @param channel Name of the sampler variable.
  774. * @param texture Texture to set.
  775. */
  776. Effect.prototype.setTexture = function (channel, texture) {
  777. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  778. };
  779. /**
  780. * Sets an array of textures on the engine to be used in the shader.
  781. * @param channel Name of the variable.
  782. * @param textures Textures to set.
  783. */
  784. Effect.prototype.setTextureArray = function (channel, textures) {
  785. if (this._samplers.indexOf(channel + "Ex") === -1) {
  786. var initialPos = this._samplers.indexOf(channel);
  787. for (var index = 1; index < textures.length; index++) {
  788. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  789. }
  790. }
  791. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  792. };
  793. /**
  794. * 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)
  795. * @param channel Name of the sampler variable.
  796. * @param postProcess Post process to get the input texture from.
  797. */
  798. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  799. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  800. };
  801. /** @ignore */
  802. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  803. var cache = this._valueCache[uniformName];
  804. var flag = matrix.updateFlag;
  805. if (cache !== undefined && cache === flag) {
  806. return false;
  807. }
  808. this._valueCache[uniformName] = flag;
  809. return true;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y];
  816. this._valueCache[uniformName] = cache;
  817. return true;
  818. }
  819. var changed = false;
  820. if (cache[0] !== x) {
  821. cache[0] = x;
  822. changed = true;
  823. }
  824. if (cache[1] !== y) {
  825. cache[1] = y;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @ignore */
  831. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. return changed;
  852. };
  853. /** @ignore */
  854. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  855. var cache = this._valueCache[uniformName];
  856. if (!cache) {
  857. cache = [x, y, z, w];
  858. this._valueCache[uniformName] = cache;
  859. return true;
  860. }
  861. var changed = false;
  862. if (cache[0] !== x) {
  863. cache[0] = x;
  864. changed = true;
  865. }
  866. if (cache[1] !== y) {
  867. cache[1] = y;
  868. changed = true;
  869. }
  870. if (cache[2] !== z) {
  871. cache[2] = z;
  872. changed = true;
  873. }
  874. if (cache[3] !== w) {
  875. cache[3] = w;
  876. changed = true;
  877. }
  878. return changed;
  879. };
  880. /**
  881. * Binds a buffer to a uniform.
  882. * @param buffer Buffer to bind.
  883. * @param name Name of the uniform variable to bind to.
  884. */
  885. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  886. var bufferName = this._uniformBuffersNames[name];
  887. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  888. return;
  889. }
  890. Effect._baseCache[bufferName] = buffer;
  891. this._engine.bindUniformBufferBase(buffer, bufferName);
  892. };
  893. /**
  894. * Binds block to a uniform.
  895. * @param blockName Name of the block to bind.
  896. * @param index Index to bind.
  897. */
  898. Effect.prototype.bindUniformBlock = function (blockName, index) {
  899. this._engine.bindUniformBlock(this._program, blockName, index);
  900. };
  901. /**
  902. * Sets an interger value on a uniform variable.
  903. * @param uniformName Name of the variable.
  904. * @param value Value to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setInt = function (uniformName, value) {
  908. var cache = this._valueCache[uniformName];
  909. if (cache !== undefined && cache === value)
  910. return this;
  911. this._valueCache[uniformName] = value;
  912. this._engine.setInt(this.getUniform(uniformName), value);
  913. return this;
  914. };
  915. /**
  916. * Sets an int array on a uniform variable.
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray2 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray2(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * 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)
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setIntArray3 = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setIntArray3(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * 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)
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setIntArray4 = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setIntArray4(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * Sets an float array on a uniform variable.
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * 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)
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * 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)
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * Sets an array on a uniform variable.
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray2 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray2(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * 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)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setArray3 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setArray3(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * 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)
  1038. * @param uniformName Name of the variable.
  1039. * @param array array to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setArray4 = function (uniformName, array) {
  1043. this._valueCache[uniformName] = null;
  1044. this._engine.setArray4(this.getUniform(uniformName), array);
  1045. return this;
  1046. };
  1047. /**
  1048. * Sets matrices on a uniform variable.
  1049. * @param uniformName Name of the variable.
  1050. * @param matrices matrices to be set.
  1051. * @returns this effect.
  1052. */
  1053. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1054. if (!matrices) {
  1055. return this;
  1056. }
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets matrix on a uniform variable.
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1068. if (this._cacheMatrix(uniformName, matrix)) {
  1069. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1070. }
  1071. return this;
  1072. };
  1073. /**
  1074. * 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)
  1075. * @param uniformName Name of the variable.
  1076. * @param matrix matrix to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1086. * @param uniformName Name of the variable.
  1087. * @param matrix matrix to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a float on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param value value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat = function (uniformName, value) {
  1102. var cache = this._valueCache[uniformName];
  1103. if (cache !== undefined && cache === value)
  1104. return this;
  1105. this._valueCache[uniformName] = value;
  1106. this._engine.setFloat(this.getUniform(uniformName), value);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets a boolean on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param bool value to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setBool = function (uniformName, bool) {
  1116. var cache = this._valueCache[uniformName];
  1117. if (cache !== undefined && cache === bool)
  1118. return this;
  1119. this._valueCache[uniformName] = bool;
  1120. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector2 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector2 vector2 to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1130. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1131. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float2 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float2.
  1139. * @param y Second float in float2.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1143. if (this._cacheFloat2(uniformName, x, y)) {
  1144. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Vector3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param vector3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1155. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1156. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a float3 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param x First float in float3.
  1164. * @param y Second float in float3.
  1165. * @param z Third float in float3.
  1166. * @returns this effect.
  1167. */
  1168. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1169. if (this._cacheFloat3(uniformName, x, y, z)) {
  1170. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1171. }
  1172. return this;
  1173. };
  1174. /**
  1175. * Sets a Vector4 on a uniform variable.
  1176. * @param uniformName Name of the variable.
  1177. * @param vector4 Value to be set.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1181. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1182. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a float4 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param x First float in float4.
  1190. * @param y Second float in float4.
  1191. * @param z Third float in float4.
  1192. * @param w Fourth float in float4.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1196. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1197. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color3 on a uniform variable.
  1203. * @param uniformName Name of the variable.
  1204. * @param color3 Value to be set.
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setColor3 = function (uniformName, color3) {
  1208. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1209. this._engine.setColor3(this.getUniform(uniformName), color3);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Sets a Color4 on a uniform variable.
  1215. * @param uniformName Name of the variable.
  1216. * @param color3 Value to be set.
  1217. * @param alpha Alpha value to be set.
  1218. * @returns this effect.
  1219. */
  1220. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1221. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1222. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1223. }
  1224. return this;
  1225. };
  1226. /**
  1227. * Sets a Color4 on a uniform variable
  1228. * @param uniformName defines the name of the variable
  1229. * @param color4 defines the value to be set
  1230. * @returns this effect.
  1231. */
  1232. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1233. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1234. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1235. }
  1236. return this;
  1237. };
  1238. /**
  1239. * Resets the cache of effects.
  1240. */
  1241. Effect.ResetCache = function () {
  1242. Effect._baseCache = {};
  1243. };
  1244. Effect._uniqueIdSeed = 0;
  1245. Effect._baseCache = {};
  1246. Effect._sourceCache = {};
  1247. // Statics
  1248. /**
  1249. * Store of each shader (The can be looked up using effect.key)
  1250. */
  1251. Effect.ShadersStore = {};
  1252. /**
  1253. * Store of each included file for a shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.IncludesShadersStore = {};
  1256. return Effect;
  1257. }());
  1258. BABYLON.Effect = Effect;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.effect.js.map
  1261. //# sourceMappingURL=babylon.types.js.map
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var KeyboardEventTypes = /** @class */ (function () {
  1265. function KeyboardEventTypes() {
  1266. }
  1267. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1268. get: function () {
  1269. return KeyboardEventTypes._KEYDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1275. get: function () {
  1276. return KeyboardEventTypes._KEYUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. KeyboardEventTypes._KEYDOWN = 0x01;
  1282. KeyboardEventTypes._KEYUP = 0x02;
  1283. return KeyboardEventTypes;
  1284. }());
  1285. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1286. var KeyboardInfo = /** @class */ (function () {
  1287. function KeyboardInfo(type, event) {
  1288. this.type = type;
  1289. this.event = event;
  1290. }
  1291. return KeyboardInfo;
  1292. }());
  1293. BABYLON.KeyboardInfo = KeyboardInfo;
  1294. /**
  1295. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1296. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1297. */
  1298. var KeyboardInfoPre = /** @class */ (function (_super) {
  1299. __extends(KeyboardInfoPre, _super);
  1300. function KeyboardInfoPre(type, event) {
  1301. var _this = _super.call(this, type, event) || this;
  1302. _this.skipOnPointerObservable = false;
  1303. return _this;
  1304. }
  1305. return KeyboardInfoPre;
  1306. }(KeyboardInfo));
  1307. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1308. })(BABYLON || (BABYLON = {}));
  1309. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1310. var BABYLON;
  1311. (function (BABYLON) {
  1312. var PointerEventTypes = /** @class */ (function () {
  1313. function PointerEventTypes() {
  1314. }
  1315. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERDOWN;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERUP;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1330. get: function () {
  1331. return PointerEventTypes._POINTERMOVE;
  1332. },
  1333. enumerable: true,
  1334. configurable: true
  1335. });
  1336. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERWHEEL;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1344. get: function () {
  1345. return PointerEventTypes._POINTERPICK;
  1346. },
  1347. enumerable: true,
  1348. configurable: true
  1349. });
  1350. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1351. get: function () {
  1352. return PointerEventTypes._POINTERTAP;
  1353. },
  1354. enumerable: true,
  1355. configurable: true
  1356. });
  1357. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1358. get: function () {
  1359. return PointerEventTypes._POINTERDOUBLETAP;
  1360. },
  1361. enumerable: true,
  1362. configurable: true
  1363. });
  1364. PointerEventTypes._POINTERDOWN = 0x01;
  1365. PointerEventTypes._POINTERUP = 0x02;
  1366. PointerEventTypes._POINTERMOVE = 0x04;
  1367. PointerEventTypes._POINTERWHEEL = 0x08;
  1368. PointerEventTypes._POINTERPICK = 0x10;
  1369. PointerEventTypes._POINTERTAP = 0x20;
  1370. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1371. return PointerEventTypes;
  1372. }());
  1373. BABYLON.PointerEventTypes = PointerEventTypes;
  1374. var PointerInfoBase = /** @class */ (function () {
  1375. function PointerInfoBase(type, event) {
  1376. this.type = type;
  1377. this.event = event;
  1378. }
  1379. return PointerInfoBase;
  1380. }());
  1381. BABYLON.PointerInfoBase = PointerInfoBase;
  1382. /**
  1383. * This class is used to store pointer related info for the onPrePointerObservable event.
  1384. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1385. */
  1386. var PointerInfoPre = /** @class */ (function (_super) {
  1387. __extends(PointerInfoPre, _super);
  1388. function PointerInfoPre(type, event, localX, localY) {
  1389. var _this = _super.call(this, type, event) || this;
  1390. _this.skipOnPointerObservable = false;
  1391. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1392. return _this;
  1393. }
  1394. return PointerInfoPre;
  1395. }(PointerInfoBase));
  1396. BABYLON.PointerInfoPre = PointerInfoPre;
  1397. /**
  1398. * This type contains all the data related to a pointer event in Babylon.js.
  1399. * 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.
  1400. */
  1401. var PointerInfo = /** @class */ (function (_super) {
  1402. __extends(PointerInfo, _super);
  1403. function PointerInfo(type, event, pickInfo) {
  1404. var _this = _super.call(this, type, event) || this;
  1405. _this.pickInfo = pickInfo;
  1406. return _this;
  1407. }
  1408. return PointerInfo;
  1409. }(PointerInfoBase));
  1410. BABYLON.PointerInfo = PointerInfo;
  1411. })(BABYLON || (BABYLON = {}));
  1412. //# sourceMappingURL=babylon.pointerEvents.js.map
  1413. var BABYLON;
  1414. (function (BABYLON) {
  1415. BABYLON.ToGammaSpace = 1 / 2.2;
  1416. BABYLON.ToLinearSpace = 2.2;
  1417. BABYLON.Epsilon = 0.001;
  1418. /**
  1419. * Class used to hold a RBG color
  1420. */
  1421. var Color3 = /** @class */ (function () {
  1422. /**
  1423. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1424. * @param r defines the red component (between 0 and 1, default is 0)
  1425. * @param g defines the green component (between 0 and 1, default is 0)
  1426. * @param b defines the blue component (between 0 and 1, default is 0)
  1427. */
  1428. function Color3(
  1429. /**
  1430. * Defines the red component (between 0 and 1, default is 0)
  1431. */
  1432. r,
  1433. /**
  1434. * Defines the green component (between 0 and 1, default is 0)
  1435. */
  1436. g,
  1437. /**
  1438. * Defines the blue component (between 0 and 1, default is 0)
  1439. */
  1440. b) {
  1441. if (r === void 0) { r = 0; }
  1442. if (g === void 0) { g = 0; }
  1443. if (b === void 0) { b = 0; }
  1444. this.r = r;
  1445. this.g = g;
  1446. this.b = b;
  1447. }
  1448. /**
  1449. * Creates a string with the Color3 current values
  1450. * @returns the string representation of the Color3 object
  1451. */
  1452. Color3.prototype.toString = function () {
  1453. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1454. };
  1455. /**
  1456. * Returns the string "Color3"
  1457. * @returns "Color3"
  1458. */
  1459. Color3.prototype.getClassName = function () {
  1460. return "Color3";
  1461. };
  1462. /**
  1463. * Compute the Color3 hash code
  1464. * @returns an unique number that can be used to hash Color3 objects
  1465. */
  1466. Color3.prototype.getHashCode = function () {
  1467. var hash = this.r || 0;
  1468. hash = (hash * 397) ^ (this.g || 0);
  1469. hash = (hash * 397) ^ (this.b || 0);
  1470. return hash;
  1471. };
  1472. // Operators
  1473. /**
  1474. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1475. * @param array defines the array where to store the r,g,b components
  1476. * @param index defines an optional index in the target array to define where to start storing values
  1477. * @returns the current Color3 object
  1478. */
  1479. Color3.prototype.toArray = function (array, index) {
  1480. if (index === undefined) {
  1481. index = 0;
  1482. }
  1483. array[index] = this.r;
  1484. array[index + 1] = this.g;
  1485. array[index + 2] = this.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1490. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1491. * @returns a new {BABYLON.Color4} object
  1492. */
  1493. Color3.prototype.toColor4 = function (alpha) {
  1494. if (alpha === void 0) { alpha = 1; }
  1495. return new Color4(this.r, this.g, this.b, alpha);
  1496. };
  1497. /**
  1498. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1499. * @returns the new array
  1500. */
  1501. Color3.prototype.asArray = function () {
  1502. var result = new Array();
  1503. this.toArray(result, 0);
  1504. return result;
  1505. };
  1506. /**
  1507. * Returns the luminance value
  1508. * @returns a float value
  1509. */
  1510. Color3.prototype.toLuminance = function () {
  1511. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1512. };
  1513. /**
  1514. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1515. * @param otherColor defines the second operand
  1516. * @returns the new Color3 object
  1517. */
  1518. Color3.prototype.multiply = function (otherColor) {
  1519. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1520. };
  1521. /**
  1522. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1523. * @param otherColor defines the second operand
  1524. * @param result defines the Color3 object where to store the result
  1525. * @returns the current Color3
  1526. */
  1527. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1528. result.r = this.r * otherColor.r;
  1529. result.g = this.g * otherColor.g;
  1530. result.b = this.b * otherColor.b;
  1531. return this;
  1532. };
  1533. /**
  1534. * Determines equality between Color3 objects
  1535. * @param otherColor defines the second operand
  1536. * @returns true if the rgb values are equal to the passed ones
  1537. */
  1538. Color3.prototype.equals = function (otherColor) {
  1539. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1540. };
  1541. /**
  1542. * Determines equality between the current Color3 object and a set of r,b,g values
  1543. * @param r defines the red component to check
  1544. * @param g defines the green component to check
  1545. * @param b defines the blue component to check
  1546. * @returns true if the rgb values are equal to the passed ones
  1547. */
  1548. Color3.prototype.equalsFloats = function (r, g, b) {
  1549. return this.r === r && this.g === g && this.b === b;
  1550. };
  1551. /**
  1552. * Multiplies in place each rgb value by scale
  1553. * @param scale defines the scaling factor
  1554. * @returns the updated Color3.
  1555. */
  1556. Color3.prototype.scale = function (scale) {
  1557. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1558. };
  1559. /**
  1560. * Multiplies the rgb values by scale and stores the result into "result"
  1561. * @param scale defines the scaling factor
  1562. * @param result defines the Color3 object where to store the result
  1563. * @returns the unmodified current Color3.
  1564. */
  1565. Color3.prototype.scaleToRef = function (scale, result) {
  1566. result.r = this.r * scale;
  1567. result.g = this.g * scale;
  1568. result.b = this.b * scale;
  1569. return this;
  1570. };
  1571. /**
  1572. * Clamps the rgb values by the min and max values and stores the result into "result"
  1573. * @param min defines minimum clamping value (default is 0)
  1574. * @param max defines maximum clamping value (default is 1)
  1575. * @param result defines color to store the result into
  1576. * @returns the original Color3
  1577. */
  1578. Color3.prototype.clampToRef = function (min, max, result) {
  1579. if (min === void 0) { min = 0; }
  1580. if (max === void 0) { max = 1; }
  1581. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1582. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1583. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1584. return this;
  1585. };
  1586. /**
  1587. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1588. * @param otherColor defines the second operand
  1589. * @returns the new Color3
  1590. */
  1591. Color3.prototype.add = function (otherColor) {
  1592. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1593. };
  1594. /**
  1595. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1596. * @param otherColor defines the second operand
  1597. * @param result defines Color3 object to store the result into
  1598. * @returns the unmodified current Color3
  1599. */
  1600. Color3.prototype.addToRef = function (otherColor, result) {
  1601. result.r = this.r + otherColor.r;
  1602. result.g = this.g + otherColor.g;
  1603. result.b = this.b + otherColor.b;
  1604. return this;
  1605. };
  1606. /**
  1607. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.subtract = function (otherColor) {
  1612. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.subtractToRef = function (otherColor, result) {
  1621. result.r = this.r - otherColor.r;
  1622. result.g = this.g - otherColor.g;
  1623. result.b = this.b - otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Copy the current object
  1628. * @returns a new Color3 copied the current one
  1629. */
  1630. Color3.prototype.clone = function () {
  1631. return new Color3(this.r, this.g, this.b);
  1632. };
  1633. /**
  1634. * Copies the rgb values from the source in the current Color3
  1635. * @param source defines the source Color3 object
  1636. * @returns the updated Color3 object
  1637. */
  1638. Color3.prototype.copyFrom = function (source) {
  1639. this.r = source.r;
  1640. this.g = source.g;
  1641. this.b = source.b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the passed floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.copyFromFloats = function (r, g, b) {
  1652. this.r = r;
  1653. this.g = g;
  1654. this.b = b;
  1655. return this;
  1656. };
  1657. /**
  1658. * Updates the Color3 rgb values from the passed floats
  1659. * @param r defines the red component to read from
  1660. * @param g defines the green component to read from
  1661. * @param b defines the blue component to read from
  1662. * @returns the current Color3 object
  1663. */
  1664. Color3.prototype.set = function (r, g, b) {
  1665. return this.copyFromFloats(r, g, b);
  1666. };
  1667. /**
  1668. * Compute the Color3 hexadecimal code as a string
  1669. * @returns a string containing the hexadecimal representation of the Color3 object
  1670. */
  1671. Color3.prototype.toHexString = function () {
  1672. var intR = (this.r * 255) | 0;
  1673. var intG = (this.g * 255) | 0;
  1674. var intB = (this.b * 255) | 0;
  1675. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1676. };
  1677. /**
  1678. * Computes a new Color3 converted from the current one to linear space
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.prototype.toLinearSpace = function () {
  1682. var convertedColor = new Color3();
  1683. this.toLinearSpaceToRef(convertedColor);
  1684. return convertedColor;
  1685. };
  1686. /**
  1687. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1688. * @param convertedColor defines the Color3 object where to store the linear space version
  1689. * @returns the unmodified Color3
  1690. */
  1691. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1692. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1693. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1694. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1695. return this;
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to gamma space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toGammaSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toGammaSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the gamma space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1715. return this;
  1716. };
  1717. // Statics
  1718. /**
  1719. * Creates a new Color3 from the string containing valid hexadecimal values
  1720. * @param hex defines a string containing valid hexadecimal values
  1721. * @returns a new Color3 object
  1722. */
  1723. Color3.FromHexString = function (hex) {
  1724. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1725. return new Color3(0, 0, 0);
  1726. }
  1727. var r = parseInt(hex.substring(1, 3), 16);
  1728. var g = parseInt(hex.substring(3, 5), 16);
  1729. var b = parseInt(hex.substring(5, 7), 16);
  1730. return Color3.FromInts(r, g, b);
  1731. };
  1732. /**
  1733. * Creates a new Vector3 from the starting index of the passed array
  1734. * @param array defines the source array
  1735. * @param offset defines an offset in the source array
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.FromArray = function (array, offset) {
  1739. if (offset === void 0) { offset = 0; }
  1740. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1741. };
  1742. /**
  1743. * Creates a new Color3 from integer values (< 256)
  1744. * @param r defines the red component to read from (value between 0 and 255)
  1745. * @param g defines the green component to read from (value between 0 and 255)
  1746. * @param b defines the blue component to read from (value between 0 and 255)
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.FromInts = function (r, g, b) {
  1750. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1751. };
  1752. /**
  1753. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1754. * @param start defines the start Color3 value
  1755. * @param end defines the end Color3 value
  1756. * @param amount defines the gradient value between start and end
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Lerp = function (start, end, amount) {
  1760. var r = start.r + ((end.r - start.r) * amount);
  1761. var g = start.g + ((end.g - start.g) * amount);
  1762. var b = start.b + ((end.b - start.b) * amount);
  1763. return new Color3(r, g, b);
  1764. };
  1765. /**
  1766. * Returns a Color3 value containing a red color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Red = function () { return new Color3(1, 0, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a green color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Green = function () { return new Color3(0, 1, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a blue color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a black color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Black = function () { return new Color3(0, 0, 0); };
  1785. /**
  1786. * Returns a Color3 value containing a white color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.White = function () { return new Color3(1, 1, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a purple color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1795. /**
  1796. * Returns a Color3 value containing a magenta color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a yellow color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a gray color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1810. /**
  1811. * Returns a Color3 value containing a teal color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1815. /**
  1816. * Returns a Color3 value containing a random color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1820. return Color3;
  1821. }());
  1822. BABYLON.Color3 = Color3;
  1823. /**
  1824. * Class used to hold a RBGA color
  1825. */
  1826. var Color4 = /** @class */ (function () {
  1827. /**
  1828. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1829. * @param r defines the red component (between 0 and 1, default is 0)
  1830. * @param g defines the green component (between 0 and 1, default is 0)
  1831. * @param b defines the blue component (between 0 and 1, default is 0)
  1832. * @param a defines the alpha component (between 0 and 1, default is 1)
  1833. */
  1834. function Color4(
  1835. /**
  1836. * Defines the red component (between 0 and 1, default is 0)
  1837. */
  1838. r,
  1839. /**
  1840. * Defines the green component (between 0 and 1, default is 0)
  1841. */
  1842. g,
  1843. /**
  1844. * Defines the blue component (between 0 and 1, default is 0)
  1845. */
  1846. b,
  1847. /**
  1848. * Defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. a) {
  1851. if (r === void 0) { r = 0; }
  1852. if (g === void 0) { g = 0; }
  1853. if (b === void 0) { b = 0; }
  1854. if (a === void 0) { a = 1; }
  1855. this.r = r;
  1856. this.g = g;
  1857. this.b = b;
  1858. this.a = a;
  1859. }
  1860. // Operators
  1861. /**
  1862. * Adds in place the passed Color4 values to the current Color4 object
  1863. * @param right defines the second operand
  1864. * @returns the current updated Color4 object
  1865. */
  1866. Color4.prototype.addInPlace = function (right) {
  1867. this.r += right.r;
  1868. this.g += right.g;
  1869. this.b += right.b;
  1870. this.a += right.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1875. * @returns the new array
  1876. */
  1877. Color4.prototype.asArray = function () {
  1878. var result = new Array();
  1879. this.toArray(result, 0);
  1880. return result;
  1881. };
  1882. /**
  1883. * Stores from the starting index in the passed array the Color4 successive values
  1884. * @param array defines the array where to store the r,g,b components
  1885. * @param index defines an optional index in the target array to define where to start storing values
  1886. * @returns the current Color4 object
  1887. */
  1888. Color4.prototype.toArray = function (array, index) {
  1889. if (index === undefined) {
  1890. index = 0;
  1891. }
  1892. array[index] = this.r;
  1893. array[index + 1] = this.g;
  1894. array[index + 2] = this.b;
  1895. array[index + 3] = this.a;
  1896. return this;
  1897. };
  1898. /**
  1899. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1900. * @param right defines the second operand
  1901. * @returns a new Color4 object
  1902. */
  1903. Color4.prototype.add = function (right) {
  1904. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1905. };
  1906. /**
  1907. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1908. * @param right defines the second operand
  1909. * @returns a new Color4 object
  1910. */
  1911. Color4.prototype.subtract = function (right) {
  1912. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1913. };
  1914. /**
  1915. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1916. * @param right defines the second operand
  1917. * @param result defines the Color4 object where to store the result
  1918. * @returns the current Color4 object
  1919. */
  1920. Color4.prototype.subtractToRef = function (right, result) {
  1921. result.r = this.r - right.r;
  1922. result.g = this.g - right.g;
  1923. result.b = this.b - right.b;
  1924. result.a = this.a - right.a;
  1925. return this;
  1926. };
  1927. /**
  1928. * Creates a new Color4 with the current Color4 values multiplied by scale
  1929. * @param scale defines the scaling factor to apply
  1930. * @returns a new Color4 object
  1931. */
  1932. Color4.prototype.scale = function (scale) {
  1933. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1934. };
  1935. /**
  1936. * Multiplies the current Color4 values by scale and stores the result in "result"
  1937. * @param scale defines the scaling factor to apply
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the current Color4.
  1940. */
  1941. Color4.prototype.scaleToRef = function (scale, result) {
  1942. result.r = this.r * scale;
  1943. result.g = this.g * scale;
  1944. result.b = this.b * scale;
  1945. result.a = this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the passed Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the passed float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the passed array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. var Vector2 = /** @class */ (function () {
  2196. /**
  2197. * Creates a new Vector2 from the passed x and y coordinates.
  2198. */
  2199. function Vector2(x, y) {
  2200. this.x = x;
  2201. this.y = y;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector2 coordinates.
  2205. */
  2206. Vector2.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector2"
  2211. */
  2212. Vector2.prototype.getClassName = function () {
  2213. return "Vector2";
  2214. };
  2215. /**
  2216. * Returns the Vector2 hash code as a number.
  2217. */
  2218. Vector2.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. return hash;
  2222. };
  2223. // Operators
  2224. /**
  2225. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2226. * Returns the Vector2.
  2227. */
  2228. Vector2.prototype.toArray = function (array, index) {
  2229. if (index === void 0) { index = 0; }
  2230. array[index] = this.x;
  2231. array[index + 1] = this.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Returns a new array with 2 elements : the Vector2 coordinates.
  2236. */
  2237. Vector2.prototype.asArray = function () {
  2238. var result = new Array();
  2239. this.toArray(result, 0);
  2240. return result;
  2241. };
  2242. /**
  2243. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2244. * Returns the updated Vector2.
  2245. */
  2246. Vector2.prototype.copyFrom = function (source) {
  2247. this.x = source.x;
  2248. this.y = source.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the passed floats.
  2253. * Returns the updated Vector2.
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the passed floats.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2269. */
  2270. Vector2.prototype.add = function (otherVector) {
  2271. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2272. };
  2273. /**
  2274. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2275. * Returns the Vector2.
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.addInPlace = function (otherVector) {
  2287. this.x += otherVector.x;
  2288. this.y += otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2299. */
  2300. Vector2.prototype.subtract = function (otherVector) {
  2301. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2314. * Returns the updated Vector2.
  2315. */
  2316. Vector2.prototype.subtractInPlace = function (otherVector) {
  2317. this.x -= otherVector.x;
  2318. this.y -= otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2323. * Returns the updated Vector2.
  2324. */
  2325. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2326. this.x *= otherVector.x;
  2327. this.y *= otherVector.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2332. */
  2333. Vector2.prototype.multiply = function (otherVector) {
  2334. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2335. };
  2336. /**
  2337. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2341. result.x = this.x * otherVector.x;
  2342. result.y = this.y * otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2347. */
  2348. Vector2.prototype.multiplyByFloats = function (x, y) {
  2349. return new Vector2(this.x * x, this.y * y);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2353. */
  2354. Vector2.prototype.divide = function (otherVector) {
  2355. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2356. };
  2357. /**
  2358. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2359. * Returns the Vector2.
  2360. */
  2361. Vector2.prototype.divideToRef = function (otherVector, result) {
  2362. result.x = this.x / otherVector.x;
  2363. result.y = this.y / otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Divides the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector2.prototype.divideInPlace = function (otherVector) {
  2371. return this.divideToRef(otherVector, this);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 with current Vector2 negated coordinates.
  2375. */
  2376. Vector2.prototype.negate = function () {
  2377. return new Vector2(-this.x, -this.y);
  2378. };
  2379. /**
  2380. * Multiply the Vector2 coordinates by scale.
  2381. * Returns the updated Vector2.
  2382. */
  2383. Vector2.prototype.scaleInPlace = function (scale) {
  2384. this.x *= scale;
  2385. this.y *= scale;
  2386. return this;
  2387. };
  2388. /**
  2389. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2390. */
  2391. Vector2.prototype.scale = function (scale) {
  2392. return new Vector2(this.x * scale, this.y * scale);
  2393. };
  2394. /**
  2395. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2396. */
  2397. Vector2.prototype.equals = function (otherVector) {
  2398. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2399. };
  2400. /**
  2401. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2402. */
  2403. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2404. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2405. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2406. };
  2407. // Properties
  2408. /**
  2409. * Returns the vector length (float).
  2410. */
  2411. Vector2.prototype.length = function () {
  2412. return Math.sqrt(this.x * this.x + this.y * this.y);
  2413. };
  2414. /**
  2415. * Returns the vector squared length (float);
  2416. */
  2417. Vector2.prototype.lengthSquared = function () {
  2418. return (this.x * this.x + this.y * this.y);
  2419. };
  2420. // Methods
  2421. /**
  2422. * Normalize the vector.
  2423. * Returns the updated Vector2.
  2424. */
  2425. Vector2.prototype.normalize = function () {
  2426. var len = this.length();
  2427. if (len === 0)
  2428. return this;
  2429. var num = 1.0 / len;
  2430. this.x *= num;
  2431. this.y *= num;
  2432. return this;
  2433. };
  2434. /**
  2435. * Returns a new Vector2 copied from the Vector2.
  2436. */
  2437. Vector2.prototype.clone = function () {
  2438. return new Vector2(this.x, this.y);
  2439. };
  2440. // Statics
  2441. /**
  2442. * Returns a new Vector2(0, 0)
  2443. */
  2444. Vector2.Zero = function () {
  2445. return new Vector2(0, 0);
  2446. };
  2447. /**
  2448. * Returns a new Vector2(1, 1)
  2449. */
  2450. Vector2.One = function () {
  2451. return new Vector2(1, 1);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 set from the passed index element of the passed array.
  2455. */
  2456. Vector2.FromArray = function (array, offset) {
  2457. if (offset === void 0) { offset = 0; }
  2458. return new Vector2(array[offset], array[offset + 1]);
  2459. };
  2460. /**
  2461. * Sets "result" from the passed index element of the passed array.
  2462. */
  2463. Vector2.FromArrayToRef = function (array, offset, result) {
  2464. result.x = array[offset];
  2465. result.y = array[offset + 1];
  2466. };
  2467. /**
  2468. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2469. */
  2470. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2471. var squared = amount * amount;
  2472. var cubed = amount * squared;
  2473. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2474. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2475. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2476. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2477. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2478. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2479. return new Vector2(x, y);
  2480. };
  2481. /**
  2482. * 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".
  2483. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2484. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2485. */
  2486. Vector2.Clamp = function (value, min, max) {
  2487. var x = value.x;
  2488. x = (x > max.x) ? max.x : x;
  2489. x = (x < min.x) ? min.x : x;
  2490. var y = value.y;
  2491. y = (y > max.y) ? max.y : y;
  2492. y = (y < min.y) ? min.y : y;
  2493. return new Vector2(x, y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2497. */
  2498. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2499. var squared = amount * amount;
  2500. var cubed = amount * squared;
  2501. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2502. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2503. var part3 = (cubed - (2.0 * squared)) + amount;
  2504. var part4 = cubed - squared;
  2505. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2506. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2507. return new Vector2(x, y);
  2508. };
  2509. /**
  2510. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2511. */
  2512. Vector2.Lerp = function (start, end, amount) {
  2513. var x = start.x + ((end.x - start.x) * amount);
  2514. var y = start.y + ((end.y - start.y) * amount);
  2515. return new Vector2(x, y);
  2516. };
  2517. /**
  2518. * Returns the dot product (float) of the vector "left" and the vector "right".
  2519. */
  2520. Vector2.Dot = function (left, right) {
  2521. return left.x * right.x + left.y * right.y;
  2522. };
  2523. /**
  2524. * Returns a new Vector2 equal to the normalized passed vector.
  2525. */
  2526. Vector2.Normalize = function (vector) {
  2527. var newVector = vector.clone();
  2528. newVector.normalize();
  2529. return newVector;
  2530. };
  2531. /**
  2532. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2533. */
  2534. Vector2.Minimize = function (left, right) {
  2535. var x = (left.x < right.x) ? left.x : right.x;
  2536. var y = (left.y < right.y) ? left.y : right.y;
  2537. return new Vector2(x, y);
  2538. };
  2539. /**
  2540. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2541. */
  2542. Vector2.Maximize = function (left, right) {
  2543. var x = (left.x > right.x) ? left.x : right.x;
  2544. var y = (left.y > right.y) ? left.y : right.y;
  2545. return new Vector2(x, y);
  2546. };
  2547. /**
  2548. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2549. */
  2550. Vector2.Transform = function (vector, transformation) {
  2551. var r = Vector2.Zero();
  2552. Vector2.TransformToRef(vector, transformation, r);
  2553. return r;
  2554. };
  2555. /**
  2556. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2557. */
  2558. Vector2.TransformToRef = function (vector, transformation, result) {
  2559. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2560. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2561. result.x = x;
  2562. result.y = y;
  2563. };
  2564. /**
  2565. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2566. */
  2567. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2568. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2569. var sign = a < 0 ? -1 : 1;
  2570. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2571. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2572. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2573. };
  2574. /**
  2575. * Returns the distance (float) between the vectors "value1" and "value2".
  2576. */
  2577. Vector2.Distance = function (value1, value2) {
  2578. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2579. };
  2580. /**
  2581. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2582. */
  2583. Vector2.DistanceSquared = function (value1, value2) {
  2584. var x = value1.x - value2.x;
  2585. var y = value1.y - value2.y;
  2586. return (x * x) + (y * y);
  2587. };
  2588. /**
  2589. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2590. */
  2591. Vector2.Center = function (value1, value2) {
  2592. var center = value1.add(value2);
  2593. center.scaleInPlace(0.5);
  2594. return center;
  2595. };
  2596. /**
  2597. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2598. */
  2599. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2600. var l2 = Vector2.DistanceSquared(segA, segB);
  2601. if (l2 === 0.0) {
  2602. return Vector2.Distance(p, segA);
  2603. }
  2604. var v = segB.subtract(segA);
  2605. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2606. var proj = segA.add(v.multiplyByFloats(t, t));
  2607. return Vector2.Distance(p, proj);
  2608. };
  2609. return Vector2;
  2610. }());
  2611. BABYLON.Vector2 = Vector2;
  2612. /**
  2613. * Classed used to store (x,y,z) vector representation
  2614. * A Vector3 is the main object used in 3D geometry
  2615. * It can represent etiher the coordinates of a point the space, either a direction
  2616. * Reminder: Babylon.js uses a left handed forward facing system
  2617. */
  2618. var Vector3 = /** @class */ (function () {
  2619. /**
  2620. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2621. * @param x defines the first coordinates (on X axis)
  2622. * @param y defines the second coordinates (on Y axis)
  2623. * @param z defines the third coordinates (on Z axis)
  2624. */
  2625. function Vector3(
  2626. /**
  2627. * Defines the first coordinates (on X axis)
  2628. */
  2629. x,
  2630. /**
  2631. * Defines the second coordinates (on Y axis)
  2632. */
  2633. y,
  2634. /**
  2635. * Defines the third coordinates (on Z axis)
  2636. */
  2637. z) {
  2638. this.x = x;
  2639. this.y = y;
  2640. this.z = z;
  2641. }
  2642. /**
  2643. * Creates a string representation of the Vector3
  2644. * @returns a string with the Vector3 coordinates.
  2645. */
  2646. Vector3.prototype.toString = function () {
  2647. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2648. };
  2649. /**
  2650. * Gets the class name
  2651. * @returns the string "Vector3"
  2652. */
  2653. Vector3.prototype.getClassName = function () {
  2654. return "Vector3";
  2655. };
  2656. /**
  2657. * Creates the Vector3 hash code
  2658. * @returns a number which tends to be unique between Vector3 instances
  2659. */
  2660. Vector3.prototype.getHashCode = function () {
  2661. var hash = this.x || 0;
  2662. hash = (hash * 397) ^ (this.y || 0);
  2663. hash = (hash * 397) ^ (this.z || 0);
  2664. return hash;
  2665. };
  2666. // Operators
  2667. /**
  2668. * Creates an array containing three elements : the coordinates of the Vector3
  2669. * @returns a new array of numbers
  2670. */
  2671. Vector3.prototype.asArray = function () {
  2672. var result = [];
  2673. this.toArray(result, 0);
  2674. return result;
  2675. };
  2676. /**
  2677. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2678. * @param array defines the destination array
  2679. * @param index defines the offset in the destination array
  2680. * @returns the current Vector3
  2681. */
  2682. Vector3.prototype.toArray = function (array, index) {
  2683. if (index === void 0) { index = 0; }
  2684. array[index] = this.x;
  2685. array[index + 1] = this.y;
  2686. array[index + 2] = this.z;
  2687. return this;
  2688. };
  2689. /**
  2690. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2691. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2692. */
  2693. Vector3.prototype.toQuaternion = function () {
  2694. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2695. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2696. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2697. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2698. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2699. var cosy = Math.cos(this.y * 0.5);
  2700. var siny = Math.sin(this.y * 0.5);
  2701. result.x = coszMinusx * siny;
  2702. result.y = -sinzMinusx * siny;
  2703. result.z = sinxPlusz * cosy;
  2704. result.w = cosxPlusz * cosy;
  2705. return result;
  2706. };
  2707. /**
  2708. * Adds the passed vector to the current Vector3
  2709. * @param otherVector defines the second operand
  2710. * @returns the current updated Vector3
  2711. */
  2712. Vector3.prototype.addInPlace = function (otherVector) {
  2713. this.x += otherVector.x;
  2714. this.y += otherVector.y;
  2715. this.z += otherVector.z;
  2716. return this;
  2717. };
  2718. /**
  2719. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2720. * @param otherVector defines the second operand
  2721. * @returns the resulting Vector3
  2722. */
  2723. Vector3.prototype.add = function (otherVector) {
  2724. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2725. };
  2726. /**
  2727. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2728. * @param otherVector defines the second operand
  2729. * @param result defines the Vector3 object where to store the result
  2730. * @returns the current Vector3
  2731. */
  2732. Vector3.prototype.addToRef = function (otherVector, result) {
  2733. result.x = this.x + otherVector.x;
  2734. result.y = this.y + otherVector.y;
  2735. result.z = this.z + otherVector.z;
  2736. return this;
  2737. };
  2738. /**
  2739. * Subtract the passed vector from the current Vector3
  2740. * @param otherVector defines the second operand
  2741. * @returns the current updated Vector3
  2742. */
  2743. Vector3.prototype.subtractInPlace = function (otherVector) {
  2744. this.x -= otherVector.x;
  2745. this.y -= otherVector.y;
  2746. this.z -= otherVector.z;
  2747. return this;
  2748. };
  2749. /**
  2750. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2751. * @param otherVector defines the second operand
  2752. * @returns the resulting Vector3
  2753. */
  2754. Vector3.prototype.subtract = function (otherVector) {
  2755. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2756. };
  2757. /**
  2758. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2759. * @param otherVector defines the second operand
  2760. * @param result defines the Vector3 object where to store the result
  2761. * @returns the current Vector3
  2762. */
  2763. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2764. result.x = this.x - otherVector.x;
  2765. result.y = this.y - otherVector.y;
  2766. result.z = this.z - otherVector.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2771. * @param x defines the x coordinate of the operand
  2772. * @param y defines the y coordinate of the operand
  2773. * @param z defines the z coordinate of the operand
  2774. * @returns the resulting Vector3
  2775. */
  2776. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2777. return new Vector3(this.x - x, this.y - y, this.z - z);
  2778. };
  2779. /**
  2780. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2781. * @param x defines the x coordinate of the operand
  2782. * @param y defines the y coordinate of the operand
  2783. * @param z defines the z coordinate of the operand
  2784. * @param result defines the Vector3 object where to store the result
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2788. result.x = this.x - x;
  2789. result.y = this.y - y;
  2790. result.z = this.z - z;
  2791. return this;
  2792. };
  2793. /**
  2794. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2795. * @returns a new Vector3
  2796. */
  2797. Vector3.prototype.negate = function () {
  2798. return new Vector3(-this.x, -this.y, -this.z);
  2799. };
  2800. /**
  2801. * Multiplies the Vector3 coordinates by the float "scale"
  2802. * @param scale defines the multiplier factor
  2803. * @returns the current updated Vector3
  2804. */
  2805. Vector3.prototype.scaleInPlace = function (scale) {
  2806. this.x *= scale;
  2807. this.y *= scale;
  2808. this.z *= scale;
  2809. return this;
  2810. };
  2811. /**
  2812. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2813. * @param scale defines the multiplier factor
  2814. * @returns a new Vector3
  2815. */
  2816. Vector3.prototype.scale = function (scale) {
  2817. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2818. };
  2819. /**
  2820. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2821. * @param scale defines the multiplier factor
  2822. * @param result defines the Vector3 object where to store the result
  2823. * @returns the current Vector3
  2824. */
  2825. Vector3.prototype.scaleToRef = function (scale, result) {
  2826. result.x = this.x * scale;
  2827. result.y = this.y * scale;
  2828. result.z = this.z * scale;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2833. * @param otherVector defines the second operand
  2834. * @returns true if both vectors are equals
  2835. */
  2836. Vector3.prototype.equals = function (otherVector) {
  2837. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2838. };
  2839. /**
  2840. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2841. * @param otherVector defines the second operand
  2842. * @param epsilon defines the minimal distance to define values as equals
  2843. * @returns true if both vectors are distant less than epsilon
  2844. */
  2845. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2846. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2847. 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);
  2848. };
  2849. /**
  2850. * Returns true if the current Vector3 coordinates equals the passed floats
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns true if both vectors are equals
  2855. */
  2856. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2857. return this.x === x && this.y === y && this.z === z;
  2858. };
  2859. /**
  2860. * Multiplies the current Vector3 coordinates by the passed ones
  2861. * @param otherVector defines the second operand
  2862. * @returns the current updated Vector3
  2863. */
  2864. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2865. this.x *= otherVector.x;
  2866. this.y *= otherVector.y;
  2867. this.z *= otherVector.z;
  2868. return this;
  2869. };
  2870. /**
  2871. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2872. * @param otherVector defines the second operand
  2873. * @returns the new Vector3
  2874. */
  2875. Vector3.prototype.multiply = function (otherVector) {
  2876. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2877. };
  2878. /**
  2879. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2880. * @param otherVector defines the second operand
  2881. * @param result defines the Vector3 object where to store the result
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2885. result.x = this.x * otherVector.x;
  2886. result.y = this.y * otherVector.y;
  2887. result.z = this.z * otherVector.z;
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @returns the new Vector3
  2896. */
  2897. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2898. return new Vector3(this.x * x, this.y * y, this.z * z);
  2899. };
  2900. /**
  2901. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2902. * @param otherVector defines the second operand
  2903. * @returns the new Vector3
  2904. */
  2905. Vector3.prototype.divide = function (otherVector) {
  2906. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2907. };
  2908. /**
  2909. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.divideToRef = function (otherVector, result) {
  2915. result.x = this.x / otherVector.x;
  2916. result.y = this.y / otherVector.y;
  2917. result.z = this.z / otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Divides the current Vector3 coordinates by the passed ones.
  2922. * @param otherVector defines the second operand
  2923. * @returns the current updated Vector3
  2924. */
  2925. Vector3.prototype.divideInPlace = function (otherVector) {
  2926. return this.divideToRef(otherVector, this);
  2927. };
  2928. /**
  2929. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2930. * @param other defines the second operand
  2931. * @returns the current updated Vector3
  2932. */
  2933. Vector3.prototype.minimizeInPlace = function (other) {
  2934. if (other.x < this.x)
  2935. this.x = other.x;
  2936. if (other.y < this.y)
  2937. this.y = other.y;
  2938. if (other.z < this.z)
  2939. this.z = other.z;
  2940. return this;
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.maximizeInPlace = function (other) {
  2948. if (other.x > this.x)
  2949. this.x = other.x;
  2950. if (other.y > this.y)
  2951. this.y = other.y;
  2952. if (other.z > this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2957. /**
  2958. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2959. */
  2960. get: function () {
  2961. var absX = Math.abs(this.x);
  2962. var absY = Math.abs(this.y);
  2963. if (absX !== absY) {
  2964. return true;
  2965. }
  2966. var absZ = Math.abs(this.z);
  2967. if (absX !== absZ) {
  2968. return true;
  2969. }
  2970. if (absY !== absZ) {
  2971. return true;
  2972. }
  2973. return false;
  2974. },
  2975. enumerable: true,
  2976. configurable: true
  2977. });
  2978. // Properties
  2979. /**
  2980. * Gets the length of the Vector3
  2981. * @returns the length of the Vecto3
  2982. */
  2983. Vector3.prototype.length = function () {
  2984. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2985. };
  2986. /**
  2987. * Gets the squared length of the Vector3
  2988. * @returns squared length of the Vector3
  2989. */
  2990. Vector3.prototype.lengthSquared = function () {
  2991. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2992. };
  2993. /**
  2994. * Normalize the current Vector3.
  2995. * Please note that this is an in place operation.
  2996. * @returns the current updated Vector3
  2997. */
  2998. Vector3.prototype.normalize = function () {
  2999. var len = this.length();
  3000. if (len === 0 || len === 1.0)
  3001. return this;
  3002. var num = 1.0 / len;
  3003. this.x *= num;
  3004. this.y *= num;
  3005. this.z *= num;
  3006. return this;
  3007. };
  3008. /**
  3009. * Normalize the current Vector3 to a new vector
  3010. * @returns the new Vector3
  3011. */
  3012. Vector3.prototype.normalizeToNew = function () {
  3013. var normalized = new Vector3(0, 0, 0);
  3014. this.normalizeToRef(normalized);
  3015. return normalized;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to the reference
  3019. * @param reference define the Vector3 to update
  3020. * @returns the updated Vector3
  3021. */
  3022. Vector3.prototype.normalizeToRef = function (reference) {
  3023. var len = this.length();
  3024. if (len === 0 || len === 1.0) {
  3025. reference.set(this.x, this.y, this.z);
  3026. return reference;
  3027. }
  3028. var scale = 1.0 / len;
  3029. this.scaleToRef(scale, reference);
  3030. return reference;
  3031. };
  3032. /**
  3033. * Creates a new Vector3 copied from the current Vector3
  3034. * @returns the new Vector3
  3035. */
  3036. Vector3.prototype.clone = function () {
  3037. return new Vector3(this.x, this.y, this.z);
  3038. };
  3039. /**
  3040. * Copies the passed vector coordinates to the current Vector3 ones
  3041. * @param source defines the source Vector3
  3042. * @returns the current updated Vector3
  3043. */
  3044. Vector3.prototype.copyFrom = function (source) {
  3045. this.x = source.x;
  3046. this.y = source.y;
  3047. this.z = source.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Copies the passed floats to the current Vector3 coordinates
  3052. * @param x defines the x coordinate of the operand
  3053. * @param y defines the y coordinate of the operand
  3054. * @param z defines the z coordinate of the operand
  3055. * @returns the current updated Vector3
  3056. */
  3057. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3058. this.x = x;
  3059. this.y = y;
  3060. this.z = z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Copies the passed floats to the current Vector3 coordinates
  3065. * @param x defines the x coordinate of the operand
  3066. * @param y defines the y coordinate of the operand
  3067. * @param z defines the z coordinate of the operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.set = function (x, y, z) {
  3071. return this.copyFromFloats(x, y, z);
  3072. };
  3073. // Statics
  3074. /**
  3075. * Get the clip factor between two vectors
  3076. * @param vector0 defines the first operand
  3077. * @param vector1 defines the second operand
  3078. * @param axis defines the axis to use
  3079. * @param size defines the size along the axis
  3080. * @returns the clip factor
  3081. */
  3082. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3083. var d0 = Vector3.Dot(vector0, axis) - size;
  3084. var d1 = Vector3.Dot(vector1, axis) - size;
  3085. var s = d0 / (d0 - d1);
  3086. return s;
  3087. };
  3088. /**
  3089. * Get angle between two vectors
  3090. * @param vector0 angle between vector0 and vector1
  3091. * @param vector1 angle between vector0 and vector1
  3092. * @param normal direction of the normal
  3093. * @return the angle between vector0 and vector1
  3094. */
  3095. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3096. var v0 = vector0.clone().normalize();
  3097. var v1 = vector1.clone().normalize();
  3098. var dot = Vector3.Dot(v0, v1);
  3099. var n = Vector3.Cross(v0, v1);
  3100. if (Vector3.Dot(n, normal) > 0) {
  3101. return Math.acos(dot);
  3102. }
  3103. return -Math.acos(dot);
  3104. };
  3105. /**
  3106. * Returns a new Vector3 set from the index "offset" of the passed array
  3107. * @param array defines the source array
  3108. * @param offset defines the offset in the source array
  3109. * @returns the new Vector3
  3110. */
  3111. Vector3.FromArray = function (array, offset) {
  3112. if (!offset) {
  3113. offset = 0;
  3114. }
  3115. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3119. * This function is deprecated. Use FromArray instead
  3120. * @param array defines the source array
  3121. * @param offset defines the offset in the source array
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.FromFloatArray = function (array, offset) {
  3125. return Vector3.FromArray(array, offset);
  3126. };
  3127. /**
  3128. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @param result defines the Vector3 where to store the result
  3132. */
  3133. Vector3.FromArrayToRef = function (array, offset, result) {
  3134. result.x = array[offset];
  3135. result.y = array[offset + 1];
  3136. result.z = array[offset + 2];
  3137. };
  3138. /**
  3139. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3140. * This function is deprecated. Use FromArrayToRef instead.
  3141. * @param array defines the source array
  3142. * @param offset defines the offset in the source array
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3146. return Vector3.FromArrayToRef(array, offset, result);
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" with the passed floats.
  3150. * @param x defines the x coordinate of the source
  3151. * @param y defines the y coordinate of the source
  3152. * @param z defines the z coordinate of the source
  3153. * @param result defines the Vector3 where to store the result
  3154. */
  3155. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3156. result.x = x;
  3157. result.y = y;
  3158. result.z = z;
  3159. };
  3160. /**
  3161. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3162. * @returns a new empty Vector3
  3163. */
  3164. Vector3.Zero = function () {
  3165. return new Vector3(0.0, 0.0, 0.0);
  3166. };
  3167. /**
  3168. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3169. * @returns a new unit Vector3
  3170. */
  3171. Vector3.One = function () {
  3172. return new Vector3(1.0, 1.0, 1.0);
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3176. * @returns a new up Vector3
  3177. */
  3178. Vector3.Up = function () {
  3179. return new Vector3(0.0, 1.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3183. * @returns a new forward Vector3
  3184. */
  3185. Vector3.Forward = function () {
  3186. return new Vector3(0.0, 0.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3190. * @returns a new right Vector3
  3191. */
  3192. Vector3.Right = function () {
  3193. return new Vector3(1.0, 0.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3197. * @returns a new left Vector3
  3198. */
  3199. Vector3.Left = function () {
  3200. return new Vector3(-1.0, 0.0, 0.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3204. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3205. * @param vector defines the Vector3 to transform
  3206. * @param transformation defines the transformation matrix
  3207. * @returns the transformed Vector3
  3208. */
  3209. Vector3.TransformCoordinates = function (vector, transformation) {
  3210. var result = Vector3.Zero();
  3211. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3212. return result;
  3213. };
  3214. /**
  3215. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3216. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3217. * @param vector defines the Vector3 to transform
  3218. * @param transformation defines the transformation matrix
  3219. * @param result defines the Vector3 where to store the result
  3220. */
  3221. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3222. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3223. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3224. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3225. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3226. result.x = x / w;
  3227. result.y = y / w;
  3228. result.z = z / w;
  3229. };
  3230. /**
  3231. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3232. * This method computes tranformed coordinates only, not transformed direction vectors
  3233. * @param x define the x coordinate of the source vector
  3234. * @param y define the y coordinate of the source vector
  3235. * @param z define the z coordinate of the source vector
  3236. * @param transformation defines the transformation matrix
  3237. * @param result defines the Vector3 where to store the result
  3238. */
  3239. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3240. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3241. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3242. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3243. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3244. result.x = rx / rw;
  3245. result.y = ry / rw;
  3246. result.z = rz / rw;
  3247. };
  3248. /**
  3249. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3250. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3251. * @param vector defines the Vector3 to transform
  3252. * @param transformation defines the transformation matrix
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.TransformNormal = function (vector, transformation) {
  3256. var result = Vector3.Zero();
  3257. Vector3.TransformNormalToRef(vector, transformation, result);
  3258. return result;
  3259. };
  3260. /**
  3261. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3262. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3263. * @param vector defines the Vector3 to transform
  3264. * @param transformation defines the transformation matrix
  3265. * @param result defines the Vector3 where to store the result
  3266. */
  3267. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3268. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3269. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3270. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3271. result.x = x;
  3272. result.y = y;
  3273. result.z = z;
  3274. };
  3275. /**
  3276. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3277. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3278. * @param x define the x coordinate of the source vector
  3279. * @param y define the y coordinate of the source vector
  3280. * @param z define the z coordinate of the source vector
  3281. * @param transformation defines the transformation matrix
  3282. * @param result defines the Vector3 where to store the result
  3283. */
  3284. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3285. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3286. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3287. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3291. * @param value1 defines the first control point
  3292. * @param value2 defines the second control point
  3293. * @param value3 defines the third control point
  3294. * @param value4 defines the fourth control point
  3295. * @param amount defines the amount on the spline to use
  3296. * @returns the new Vector3
  3297. */
  3298. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3299. var squared = amount * amount;
  3300. var cubed = amount * squared;
  3301. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3302. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3303. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3304. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3305. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3306. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3307. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3308. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3309. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3310. return new Vector3(x, y, z);
  3311. };
  3312. /**
  3313. * 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"
  3314. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3315. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3316. * @param value defines the current value
  3317. * @param min defines the lower range value
  3318. * @param max defines the upper range value
  3319. * @returns the new Vector3
  3320. */
  3321. Vector3.Clamp = function (value, min, max) {
  3322. var x = value.x;
  3323. x = (x > max.x) ? max.x : x;
  3324. x = (x < min.x) ? min.x : x;
  3325. var y = value.y;
  3326. y = (y > max.y) ? max.y : y;
  3327. y = (y < min.y) ? min.y : y;
  3328. var z = value.z;
  3329. z = (z > max.z) ? max.z : z;
  3330. z = (z < min.z) ? min.z : z;
  3331. return new Vector3(x, y, z);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3335. * @param value1 defines the first control point
  3336. * @param tangent1 defines the first tangent vector
  3337. * @param value2 defines the second control point
  3338. * @param tangent2 defines the second tangent vector
  3339. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3340. * @returns the new Vector3
  3341. */
  3342. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3343. var squared = amount * amount;
  3344. var cubed = amount * squared;
  3345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3347. var part3 = (cubed - (2.0 * squared)) + amount;
  3348. var part4 = cubed - squared;
  3349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3351. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3352. return new Vector3(x, y, z);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3356. * @param start defines the start value
  3357. * @param end defines the end value
  3358. * @param amount max defines amount between both (between 0 and 1)
  3359. * @returns the new Vector3
  3360. */
  3361. Vector3.Lerp = function (start, end, amount) {
  3362. var result = new Vector3(0, 0, 0);
  3363. Vector3.LerpToRef(start, end, amount, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3368. * @param start defines the start value
  3369. * @param end defines the end value
  3370. * @param amount max defines amount between both (between 0 and 1)
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.LerpToRef = function (start, end, amount, result) {
  3374. result.x = start.x + ((end.x - start.x) * amount);
  3375. result.y = start.y + ((end.y - start.y) * amount);
  3376. result.z = start.z + ((end.z - start.z) * amount);
  3377. };
  3378. /**
  3379. * Returns the dot product (float) between the vectors "left" and "right"
  3380. * @param left defines the left operand
  3381. * @param right defines the right operand
  3382. * @returns the dot product
  3383. */
  3384. Vector3.Dot = function (left, right) {
  3385. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3389. * The cross product is then orthogonal to both "left" and "right"
  3390. * @param left defines the left operand
  3391. * @param right defines the right operand
  3392. * @returns the cross product
  3393. */
  3394. Vector3.Cross = function (left, right) {
  3395. var result = Vector3.Zero();
  3396. Vector3.CrossToRef(left, right, result);
  3397. return result;
  3398. };
  3399. /**
  3400. * Sets the passed vector "result" with the cross product of "left" and "right"
  3401. * The cross product is then orthogonal to both "left" and "right"
  3402. * @param left defines the left operand
  3403. * @param right defines the right operand
  3404. * @param result defines the Vector3 where to store the result
  3405. */
  3406. Vector3.CrossToRef = function (left, right, result) {
  3407. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3408. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3409. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3410. result.copyFrom(MathTmp.Vector3[0]);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 as the normalization of the passed vector
  3414. * @param vector defines the Vector3 to normalize
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.Normalize = function (vector) {
  3418. var result = Vector3.Zero();
  3419. Vector3.NormalizeToRef(vector, result);
  3420. return result;
  3421. };
  3422. /**
  3423. * Sets the passed vector "result" with the normalization of the passed first vector
  3424. * @param vector defines the Vector3 to normalize
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.NormalizeToRef = function (vector, result) {
  3428. result.copyFrom(vector);
  3429. result.normalize();
  3430. };
  3431. /**
  3432. * Project a Vector3 onto screen space
  3433. * @param vector defines the Vector3 to project
  3434. * @param world defines the world matrix to use
  3435. * @param transform defines the transform (view x projection) matrix to use
  3436. * @param viewport defines the screen viewport to use
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Project = function (vector, world, transform, viewport) {
  3440. var cw = viewport.width;
  3441. var ch = viewport.height;
  3442. var cx = viewport.x;
  3443. var cy = viewport.y;
  3444. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3445. 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);
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(transform, matrix);
  3448. matrix.multiplyToRef(viewportMatrix, matrix);
  3449. return Vector3.TransformCoordinates(vector, matrix);
  3450. };
  3451. /**
  3452. * Unproject from screen space to object space
  3453. * @param source defines the screen space Vector3 to use
  3454. * @param viewportWidth defines the current width of the viewport
  3455. * @param viewportHeight defines the current height of the viewport
  3456. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3457. * @param transform defines the transform (view x projection) matrix to use
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3461. var matrix = MathTmp.Matrix[0];
  3462. world.multiplyToRef(transform, matrix);
  3463. matrix.invert();
  3464. source.x = source.x / viewportWidth * 2 - 1;
  3465. source.y = -(source.y / viewportHeight * 2 - 1);
  3466. var vector = Vector3.TransformCoordinates(source, matrix);
  3467. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3468. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3469. vector = vector.scale(1.0 / num);
  3470. }
  3471. return vector;
  3472. };
  3473. /**
  3474. * Unproject from screen space to object space
  3475. * @param source defines the screen space Vector3 to use
  3476. * @param viewportWidth defines the current width of the viewport
  3477. * @param viewportHeight defines the current height of the viewport
  3478. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3479. * @param view defines the view matrix to use
  3480. * @param projection defines the projection matrix to use
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3484. var result = Vector3.Zero();
  3485. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3486. return result;
  3487. };
  3488. /**
  3489. * Unproject from screen space to object space
  3490. * @param source defines the screen space Vector3 to use
  3491. * @param viewportWidth defines the current width of the viewport
  3492. * @param viewportHeight defines the current height of the viewport
  3493. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3494. * @param view defines the view matrix to use
  3495. * @param projection defines the projection matrix to use
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3499. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3500. };
  3501. /**
  3502. * Unproject from screen space to object space
  3503. * @param sourceX defines the screen space x coordinate to use
  3504. * @param sourceY defines the screen space y coordinate to use
  3505. * @param sourceZ defines the screen space z coordinate to use
  3506. * @param viewportWidth defines the current width of the viewport
  3507. * @param viewportHeight defines the current height of the viewport
  3508. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3509. * @param view defines the view matrix to use
  3510. * @param projection defines the projection matrix to use
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3514. var matrix = MathTmp.Matrix[0];
  3515. world.multiplyToRef(view, matrix);
  3516. matrix.multiplyToRef(projection, matrix);
  3517. matrix.invert();
  3518. var screenSource = MathTmp.Vector3[0];
  3519. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3520. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3521. screenSource.z = 2 * sourceZ - 1.0;
  3522. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3523. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3524. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3525. result.scaleInPlace(1.0 / num);
  3526. }
  3527. };
  3528. /**
  3529. * Gets the minimal coordinate values between two Vector3
  3530. * @param left defines the first operand
  3531. * @param right defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Minimize = function (left, right) {
  3535. var min = left.clone();
  3536. min.minimizeInPlace(right);
  3537. return min;
  3538. };
  3539. /**
  3540. * Gets the maximal coordinate values between two Vector3
  3541. * @param left defines the first operand
  3542. * @param right defines the second operand
  3543. * @returns the new Vector3
  3544. */
  3545. Vector3.Maximize = function (left, right) {
  3546. var max = left.clone();
  3547. max.maximizeInPlace(right);
  3548. return max;
  3549. };
  3550. /**
  3551. * Returns the distance between the vectors "value1" and "value2"
  3552. * @param value1 defines the first operand
  3553. * @param value2 defines the second operand
  3554. * @returns the distance
  3555. */
  3556. Vector3.Distance = function (value1, value2) {
  3557. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3558. };
  3559. /**
  3560. * Returns the squared distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the squared distance
  3564. */
  3565. Vector3.DistanceSquared = function (value1, value2) {
  3566. var x = value1.x - value2.x;
  3567. var y = value1.y - value2.y;
  3568. var z = value1.z - value2.z;
  3569. return (x * x) + (y * y) + (z * z);
  3570. };
  3571. /**
  3572. * Returns a new Vector3 located at the center between "value1" and "value2"
  3573. * @param value1 defines the first operand
  3574. * @param value2 defines the second operand
  3575. * @returns the new Vector3
  3576. */
  3577. Vector3.Center = function (value1, value2) {
  3578. var center = value1.add(value2);
  3579. center.scaleInPlace(0.5);
  3580. return center;
  3581. };
  3582. /**
  3583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3585. * to something in order to rotate it from its local system to the given target system
  3586. * Note: axis1, axis2 and axis3 are normalized during this operation
  3587. * @param axis1 defines the first axis
  3588. * @param axis2 defines the second axis
  3589. * @param axis3 defines the third axis
  3590. * @returns a new Vector3
  3591. */
  3592. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3593. var rotation = Vector3.Zero();
  3594. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3595. return rotation;
  3596. };
  3597. /**
  3598. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3599. * @param axis1 defines the first axis
  3600. * @param axis2 defines the second axis
  3601. * @param axis3 defines the third axis
  3602. * @param ref defines the Vector3 where to store the result
  3603. */
  3604. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3605. var quat = MathTmp.Quaternion[0];
  3606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3607. quat.toEulerAnglesToRef(ref);
  3608. };
  3609. return Vector3;
  3610. }());
  3611. BABYLON.Vector3 = Vector3;
  3612. //Vector4 class created for EulerAngle class conversion to Quaternion
  3613. var Vector4 = /** @class */ (function () {
  3614. /**
  3615. * Creates a Vector4 object from the passed floats.
  3616. */
  3617. function Vector4(x, y, z, w) {
  3618. this.x = x;
  3619. this.y = y;
  3620. this.z = z;
  3621. this.w = w;
  3622. }
  3623. /**
  3624. * Returns the string with the Vector4 coordinates.
  3625. */
  3626. Vector4.prototype.toString = function () {
  3627. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3628. };
  3629. /**
  3630. * Returns the string "Vector4".
  3631. */
  3632. Vector4.prototype.getClassName = function () {
  3633. return "Vector4";
  3634. };
  3635. /**
  3636. * Returns the Vector4 hash code.
  3637. */
  3638. Vector4.prototype.getHashCode = function () {
  3639. var hash = this.x || 0;
  3640. hash = (hash * 397) ^ (this.y || 0);
  3641. hash = (hash * 397) ^ (this.z || 0);
  3642. hash = (hash * 397) ^ (this.w || 0);
  3643. return hash;
  3644. };
  3645. // Operators
  3646. /**
  3647. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3648. */
  3649. Vector4.prototype.asArray = function () {
  3650. var result = new Array();
  3651. this.toArray(result, 0);
  3652. return result;
  3653. };
  3654. /**
  3655. * Populates the passed array from the passed index with the Vector4 coordinates.
  3656. * Returns the Vector4.
  3657. */
  3658. Vector4.prototype.toArray = function (array, index) {
  3659. if (index === undefined) {
  3660. index = 0;
  3661. }
  3662. array[index] = this.x;
  3663. array[index + 1] = this.y;
  3664. array[index + 2] = this.z;
  3665. array[index + 3] = this.w;
  3666. return this;
  3667. };
  3668. /**
  3669. * Adds the passed vector to the current Vector4.
  3670. * Returns the updated Vector4.
  3671. */
  3672. Vector4.prototype.addInPlace = function (otherVector) {
  3673. this.x += otherVector.x;
  3674. this.y += otherVector.y;
  3675. this.z += otherVector.z;
  3676. this.w += otherVector.w;
  3677. return this;
  3678. };
  3679. /**
  3680. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3681. */
  3682. Vector4.prototype.add = function (otherVector) {
  3683. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3684. };
  3685. /**
  3686. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3687. * Returns the current Vector4.
  3688. */
  3689. Vector4.prototype.addToRef = function (otherVector, result) {
  3690. result.x = this.x + otherVector.x;
  3691. result.y = this.y + otherVector.y;
  3692. result.z = this.z + otherVector.z;
  3693. result.w = this.w + otherVector.w;
  3694. return this;
  3695. };
  3696. /**
  3697. * Subtract in place the passed vector from the current Vector4.
  3698. * Returns the updated Vector4.
  3699. */
  3700. Vector4.prototype.subtractInPlace = function (otherVector) {
  3701. this.x -= otherVector.x;
  3702. this.y -= otherVector.y;
  3703. this.z -= otherVector.z;
  3704. this.w -= otherVector.w;
  3705. return this;
  3706. };
  3707. /**
  3708. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3709. */
  3710. Vector4.prototype.subtract = function (otherVector) {
  3711. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3712. };
  3713. /**
  3714. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3715. * Returns the current Vector4.
  3716. */
  3717. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3718. result.x = this.x - otherVector.x;
  3719. result.y = this.y - otherVector.y;
  3720. result.z = this.z - otherVector.z;
  3721. result.w = this.w - otherVector.w;
  3722. return this;
  3723. };
  3724. /**
  3725. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3728. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3729. };
  3730. /**
  3731. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3732. * Returns the current Vector4.
  3733. */
  3734. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3735. result.x = this.x - x;
  3736. result.y = this.y - y;
  3737. result.z = this.z - z;
  3738. result.w = this.w - w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3743. */
  3744. Vector4.prototype.negate = function () {
  3745. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3746. };
  3747. /**
  3748. * Multiplies the current Vector4 coordinates by scale (float).
  3749. * Returns the updated Vector4.
  3750. */
  3751. Vector4.prototype.scaleInPlace = function (scale) {
  3752. this.x *= scale;
  3753. this.y *= scale;
  3754. this.z *= scale;
  3755. this.w *= scale;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3760. */
  3761. Vector4.prototype.scale = function (scale) {
  3762. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3763. };
  3764. /**
  3765. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3766. * Returns the current Vector4.
  3767. */
  3768. Vector4.prototype.scaleToRef = function (scale, result) {
  3769. result.x = this.x * scale;
  3770. result.y = this.y * scale;
  3771. result.z = this.z * scale;
  3772. result.w = this.w * scale;
  3773. return this;
  3774. };
  3775. /**
  3776. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3777. */
  3778. Vector4.prototype.equals = function (otherVector) {
  3779. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3780. };
  3781. /**
  3782. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3783. */
  3784. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3785. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3786. return otherVector
  3787. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3788. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3789. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3790. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3791. };
  3792. /**
  3793. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3794. */
  3795. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3796. return this.x === x && this.y === y && this.z === z && this.w === w;
  3797. };
  3798. /**
  3799. * Multiplies in place the current Vector4 by the passed one.
  3800. * Returns the updated Vector4.
  3801. */
  3802. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3803. this.x *= otherVector.x;
  3804. this.y *= otherVector.y;
  3805. this.z *= otherVector.z;
  3806. this.w *= otherVector.w;
  3807. return this;
  3808. };
  3809. /**
  3810. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3811. */
  3812. Vector4.prototype.multiply = function (otherVector) {
  3813. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3814. };
  3815. /**
  3816. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3817. * Returns the current Vector4.
  3818. */
  3819. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3820. result.x = this.x * otherVector.x;
  3821. result.y = this.y * otherVector.y;
  3822. result.z = this.z * otherVector.z;
  3823. result.w = this.w * otherVector.w;
  3824. return this;
  3825. };
  3826. /**
  3827. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3828. */
  3829. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3830. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3831. };
  3832. /**
  3833. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3834. */
  3835. Vector4.prototype.divide = function (otherVector) {
  3836. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3837. };
  3838. /**
  3839. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.divideToRef = function (otherVector, result) {
  3843. result.x = this.x / otherVector.x;
  3844. result.y = this.y / otherVector.y;
  3845. result.z = this.z / otherVector.z;
  3846. result.w = this.w / otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Divides the current Vector3 coordinates by the passed ones.
  3851. * @returns the updated Vector3.
  3852. */
  3853. Vector4.prototype.divideInPlace = function (otherVector) {
  3854. return this.divideToRef(otherVector, this);
  3855. };
  3856. /**
  3857. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3858. * @param other defines the second operand
  3859. * @returns the current updated Vector4
  3860. */
  3861. Vector4.prototype.minimizeInPlace = function (other) {
  3862. if (other.x < this.x)
  3863. this.x = other.x;
  3864. if (other.y < this.y)
  3865. this.y = other.y;
  3866. if (other.z < this.z)
  3867. this.z = other.z;
  3868. if (other.w < this.w)
  3869. this.w = other.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3874. * @param other defines the second operand
  3875. * @returns the current updated Vector4
  3876. */
  3877. Vector4.prototype.maximizeInPlace = function (other) {
  3878. if (other.x > this.x)
  3879. this.x = other.x;
  3880. if (other.y > this.y)
  3881. this.y = other.y;
  3882. if (other.z > this.z)
  3883. this.z = other.z;
  3884. if (other.w > this.w)
  3885. this.w = other.w;
  3886. return this;
  3887. };
  3888. // Properties
  3889. /**
  3890. * Returns the Vector4 length (float).
  3891. */
  3892. Vector4.prototype.length = function () {
  3893. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3894. };
  3895. /**
  3896. * Returns the Vector4 squared length (float).
  3897. */
  3898. Vector4.prototype.lengthSquared = function () {
  3899. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3900. };
  3901. // Methods
  3902. /**
  3903. * Normalizes in place the Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.normalize = function () {
  3907. var len = this.length();
  3908. if (len === 0)
  3909. return this;
  3910. var num = 1.0 / len;
  3911. this.x *= num;
  3912. this.y *= num;
  3913. this.z *= num;
  3914. this.w *= num;
  3915. return this;
  3916. };
  3917. /**
  3918. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3919. */
  3920. Vector4.prototype.toVector3 = function () {
  3921. return new Vector3(this.x, this.y, this.z);
  3922. };
  3923. /**
  3924. * Returns a new Vector4 copied from the current one.
  3925. */
  3926. Vector4.prototype.clone = function () {
  3927. return new Vector4(this.x, this.y, this.z, this.w);
  3928. };
  3929. /**
  3930. * Updates the current Vector4 with the passed one coordinates.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.copyFrom = function (source) {
  3934. this.x = source.x;
  3935. this.y = source.y;
  3936. this.z = source.z;
  3937. this.w = source.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Updates the current Vector4 coordinates with the passed floats.
  3942. * Returns the updated Vector4.
  3943. */
  3944. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3945. this.x = x;
  3946. this.y = y;
  3947. this.z = z;
  3948. this.w = w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Updates the current Vector4 coordinates with the passed floats.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.set = function (x, y, z, w) {
  3956. return this.copyFromFloats(x, y, z, w);
  3957. };
  3958. // Statics
  3959. /**
  3960. * Returns a new Vector4 set from the starting index of the passed array.
  3961. */
  3962. Vector4.FromArray = function (array, offset) {
  3963. if (!offset) {
  3964. offset = 0;
  3965. }
  3966. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3967. };
  3968. /**
  3969. * Updates the passed vector "result" from the starting index of the passed array.
  3970. */
  3971. Vector4.FromArrayToRef = function (array, offset, result) {
  3972. result.x = array[offset];
  3973. result.y = array[offset + 1];
  3974. result.z = array[offset + 2];
  3975. result.w = array[offset + 3];
  3976. };
  3977. /**
  3978. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3979. */
  3980. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3981. Vector4.FromArrayToRef(array, offset, result);
  3982. };
  3983. /**
  3984. * Updates the passed vector "result" coordinates from the passed floats.
  3985. */
  3986. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3987. result.x = x;
  3988. result.y = y;
  3989. result.z = z;
  3990. result.w = w;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3994. */
  3995. Vector4.Zero = function () {
  3996. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3997. };
  3998. /**
  3999. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4000. */
  4001. Vector4.One = function () {
  4002. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4003. };
  4004. /**
  4005. * Returns a new normalized Vector4 from the passed one.
  4006. */
  4007. Vector4.Normalize = function (vector) {
  4008. var result = Vector4.Zero();
  4009. Vector4.NormalizeToRef(vector, result);
  4010. return result;
  4011. };
  4012. /**
  4013. * Updates the passed vector "result" from the normalization of the passed one.
  4014. */
  4015. Vector4.NormalizeToRef = function (vector, result) {
  4016. result.copyFrom(vector);
  4017. result.normalize();
  4018. };
  4019. Vector4.Minimize = function (left, right) {
  4020. var min = left.clone();
  4021. min.minimizeInPlace(right);
  4022. return min;
  4023. };
  4024. Vector4.Maximize = function (left, right) {
  4025. var max = left.clone();
  4026. max.maximizeInPlace(right);
  4027. return max;
  4028. };
  4029. /**
  4030. * Returns the distance (float) between the vectors "value1" and "value2".
  4031. */
  4032. Vector4.Distance = function (value1, value2) {
  4033. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4034. };
  4035. /**
  4036. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4037. */
  4038. Vector4.DistanceSquared = function (value1, value2) {
  4039. var x = value1.x - value2.x;
  4040. var y = value1.y - value2.y;
  4041. var z = value1.z - value2.z;
  4042. var w = value1.w - value2.w;
  4043. return (x * x) + (y * y) + (z * z) + (w * w);
  4044. };
  4045. /**
  4046. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4047. */
  4048. Vector4.Center = function (value1, value2) {
  4049. var center = value1.add(value2);
  4050. center.scaleInPlace(0.5);
  4051. return center;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4055. * This methods computes transformed normalized direction vectors only.
  4056. */
  4057. Vector4.TransformNormal = function (vector, transformation) {
  4058. var result = Vector4.Zero();
  4059. Vector4.TransformNormalToRef(vector, transformation, result);
  4060. return result;
  4061. };
  4062. /**
  4063. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4064. * This methods computes transformed normalized direction vectors only.
  4065. */
  4066. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4067. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4068. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4069. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4070. result.x = x;
  4071. result.y = y;
  4072. result.z = z;
  4073. result.w = vector.w;
  4074. };
  4075. /**
  4076. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4080. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4081. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4082. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4083. result.w = w;
  4084. };
  4085. return Vector4;
  4086. }());
  4087. BABYLON.Vector4 = Vector4;
  4088. var Size = /** @class */ (function () {
  4089. /**
  4090. * Creates a Size object from the passed width and height (floats).
  4091. */
  4092. function Size(width, height) {
  4093. this.width = width;
  4094. this.height = height;
  4095. }
  4096. // Returns a string with the Size width and height.
  4097. Size.prototype.toString = function () {
  4098. return "{W: " + this.width + ", H: " + this.height + "}";
  4099. };
  4100. /**
  4101. * Returns the string "Size"
  4102. */
  4103. Size.prototype.getClassName = function () {
  4104. return "Size";
  4105. };
  4106. /**
  4107. * Returns the Size hash code.
  4108. */
  4109. Size.prototype.getHashCode = function () {
  4110. var hash = this.width || 0;
  4111. hash = (hash * 397) ^ (this.height || 0);
  4112. return hash;
  4113. };
  4114. /**
  4115. * Updates the current size from the passed one.
  4116. * Returns the updated Size.
  4117. */
  4118. Size.prototype.copyFrom = function (src) {
  4119. this.width = src.width;
  4120. this.height = src.height;
  4121. };
  4122. /**
  4123. * Updates in place the current Size from the passed floats.
  4124. * Returns the updated Size.
  4125. */
  4126. Size.prototype.copyFromFloats = function (width, height) {
  4127. this.width = width;
  4128. this.height = height;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates in place the current Size from the passed floats.
  4133. * Returns the updated Size.
  4134. */
  4135. Size.prototype.set = function (width, height) {
  4136. return this.copyFromFloats(width, height);
  4137. };
  4138. /**
  4139. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4140. */
  4141. Size.prototype.multiplyByFloats = function (w, h) {
  4142. return new Size(this.width * w, this.height * h);
  4143. };
  4144. /**
  4145. * Returns a new Size copied from the passed one.
  4146. */
  4147. Size.prototype.clone = function () {
  4148. return new Size(this.width, this.height);
  4149. };
  4150. /**
  4151. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4152. */
  4153. Size.prototype.equals = function (other) {
  4154. if (!other) {
  4155. return false;
  4156. }
  4157. return (this.width === other.width) && (this.height === other.height);
  4158. };
  4159. Object.defineProperty(Size.prototype, "surface", {
  4160. /**
  4161. * Returns the surface of the Size : width * height (float).
  4162. */
  4163. get: function () {
  4164. return this.width * this.height;
  4165. },
  4166. enumerable: true,
  4167. configurable: true
  4168. });
  4169. /**
  4170. * Returns a new Size set to (0.0, 0.0)
  4171. */
  4172. Size.Zero = function () {
  4173. return new Size(0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Size set as the addition result of the current Size and the passed one.
  4177. */
  4178. Size.prototype.add = function (otherSize) {
  4179. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4180. return r;
  4181. };
  4182. /**
  4183. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4184. */
  4185. Size.prototype.subtract = function (otherSize) {
  4186. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4187. return r;
  4188. };
  4189. /**
  4190. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4191. */
  4192. Size.Lerp = function (start, end, amount) {
  4193. var w = start.width + ((end.width - start.width) * amount);
  4194. var h = start.height + ((end.height - start.height) * amount);
  4195. return new Size(w, h);
  4196. };
  4197. return Size;
  4198. }());
  4199. BABYLON.Size = Size;
  4200. var Quaternion = /** @class */ (function () {
  4201. /**
  4202. * Creates a new Quaternion from the passed floats.
  4203. */
  4204. function Quaternion(x, y, z, w) {
  4205. if (x === void 0) { x = 0.0; }
  4206. if (y === void 0) { y = 0.0; }
  4207. if (z === void 0) { z = 0.0; }
  4208. if (w === void 0) { w = 1.0; }
  4209. this.x = x;
  4210. this.y = y;
  4211. this.z = z;
  4212. this.w = w;
  4213. }
  4214. /**
  4215. * Returns a string with the Quaternion coordinates.
  4216. */
  4217. Quaternion.prototype.toString = function () {
  4218. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4219. };
  4220. /**
  4221. * Returns the string "Quaternion".
  4222. */
  4223. Quaternion.prototype.getClassName = function () {
  4224. return "Quaternion";
  4225. };
  4226. /**
  4227. * Returns the Quaternion hash code.
  4228. */
  4229. Quaternion.prototype.getHashCode = function () {
  4230. var hash = this.x || 0;
  4231. hash = (hash * 397) ^ (this.y || 0);
  4232. hash = (hash * 397) ^ (this.z || 0);
  4233. hash = (hash * 397) ^ (this.w || 0);
  4234. return hash;
  4235. };
  4236. /**
  4237. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4238. */
  4239. Quaternion.prototype.asArray = function () {
  4240. return [this.x, this.y, this.z, this.w];
  4241. };
  4242. /**
  4243. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4244. */
  4245. Quaternion.prototype.equals = function (otherQuaternion) {
  4246. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4247. };
  4248. /**
  4249. * Returns a new Quaternion copied from the current one.
  4250. */
  4251. Quaternion.prototype.clone = function () {
  4252. return new Quaternion(this.x, this.y, this.z, this.w);
  4253. };
  4254. /**
  4255. * Updates the current Quaternion from the passed one coordinates.
  4256. * Returns the updated Quaterion.
  4257. */
  4258. Quaternion.prototype.copyFrom = function (other) {
  4259. this.x = other.x;
  4260. this.y = other.y;
  4261. this.z = other.z;
  4262. this.w = other.w;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates the current Quaternion from the passed float coordinates.
  4267. * Returns the updated Quaterion.
  4268. */
  4269. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4270. this.x = x;
  4271. this.y = y;
  4272. this.z = z;
  4273. this.w = w;
  4274. return this;
  4275. };
  4276. /**
  4277. * Updates the current Quaternion from the passed float coordinates.
  4278. * Returns the updated Quaterion.
  4279. */
  4280. Quaternion.prototype.set = function (x, y, z, w) {
  4281. return this.copyFromFloats(x, y, z, w);
  4282. };
  4283. /**
  4284. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4285. */
  4286. Quaternion.prototype.add = function (other) {
  4287. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4288. };
  4289. /**
  4290. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4291. */
  4292. Quaternion.prototype.subtract = function (other) {
  4293. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4294. };
  4295. /**
  4296. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4297. */
  4298. Quaternion.prototype.scale = function (value) {
  4299. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4300. };
  4301. /**
  4302. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4303. */
  4304. Quaternion.prototype.multiply = function (q1) {
  4305. var result = new Quaternion(0, 0, 0, 1.0);
  4306. this.multiplyToRef(q1, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4311. * Returns the current Quaternion.
  4312. */
  4313. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4314. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4315. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4316. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4317. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4318. result.copyFromFloats(x, y, z, w);
  4319. return this;
  4320. };
  4321. /**
  4322. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4323. * Returns the updated Quaternion.
  4324. */
  4325. Quaternion.prototype.multiplyInPlace = function (q1) {
  4326. this.multiplyToRef(q1, this);
  4327. return this;
  4328. };
  4329. /**
  4330. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4331. * Returns the current Quaternion.
  4332. */
  4333. Quaternion.prototype.conjugateToRef = function (ref) {
  4334. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4335. return this;
  4336. };
  4337. /**
  4338. * Conjugates in place the current Quaternion.
  4339. * Returns the updated Quaternion.
  4340. */
  4341. Quaternion.prototype.conjugateInPlace = function () {
  4342. this.x *= -1;
  4343. this.y *= -1;
  4344. this.z *= -1;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4349. */
  4350. Quaternion.prototype.conjugate = function () {
  4351. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4352. return result;
  4353. };
  4354. /**
  4355. * Returns the Quaternion length (float).
  4356. */
  4357. Quaternion.prototype.length = function () {
  4358. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4359. };
  4360. /**
  4361. * Normalize in place the current Quaternion.
  4362. * Returns the updated Quaternion.
  4363. */
  4364. Quaternion.prototype.normalize = function () {
  4365. var length = 1.0 / this.length();
  4366. this.x *= length;
  4367. this.y *= length;
  4368. this.z *= length;
  4369. this.w *= length;
  4370. return this;
  4371. };
  4372. /**
  4373. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toEulerAngles = function (order) {
  4376. if (order === void 0) { order = "YZX"; }
  4377. var result = Vector3.Zero();
  4378. this.toEulerAnglesToRef(result, order);
  4379. return result;
  4380. };
  4381. /**
  4382. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4383. * Returns the current Quaternion.
  4384. */
  4385. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4386. if (order === void 0) { order = "YZX"; }
  4387. var qz = this.z;
  4388. var qx = this.x;
  4389. var qy = this.y;
  4390. var qw = this.w;
  4391. var sqw = qw * qw;
  4392. var sqz = qz * qz;
  4393. var sqx = qx * qx;
  4394. var sqy = qy * qy;
  4395. var zAxisY = qy * qz - qx * qw;
  4396. var limit = .4999999;
  4397. if (zAxisY < -limit) {
  4398. result.y = 2 * Math.atan2(qy, qw);
  4399. result.x = Math.PI / 2;
  4400. result.z = 0;
  4401. }
  4402. else if (zAxisY > limit) {
  4403. result.y = 2 * Math.atan2(qy, qw);
  4404. result.x = -Math.PI / 2;
  4405. result.z = 0;
  4406. }
  4407. else {
  4408. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4409. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4410. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4411. }
  4412. return this;
  4413. };
  4414. /**
  4415. * Updates the passed rotation matrix with the current Quaternion values.
  4416. * Returns the current Quaternion.
  4417. */
  4418. Quaternion.prototype.toRotationMatrix = function (result) {
  4419. var xx = this.x * this.x;
  4420. var yy = this.y * this.y;
  4421. var zz = this.z * this.z;
  4422. var xy = this.x * this.y;
  4423. var zw = this.z * this.w;
  4424. var zx = this.z * this.x;
  4425. var yw = this.y * this.w;
  4426. var yz = this.y * this.z;
  4427. var xw = this.x * this.w;
  4428. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4429. result.m[1] = 2.0 * (xy + zw);
  4430. result.m[2] = 2.0 * (zx - yw);
  4431. result.m[3] = 0;
  4432. result.m[4] = 2.0 * (xy - zw);
  4433. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4434. result.m[6] = 2.0 * (yz + xw);
  4435. result.m[7] = 0;
  4436. result.m[8] = 2.0 * (zx + yw);
  4437. result.m[9] = 2.0 * (yz - xw);
  4438. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4439. result.m[11] = 0;
  4440. result.m[12] = 0;
  4441. result.m[13] = 0;
  4442. result.m[14] = 0;
  4443. result.m[15] = 1.0;
  4444. result._markAsUpdated();
  4445. return this;
  4446. };
  4447. /**
  4448. * Updates the current Quaternion from the passed rotation matrix values.
  4449. * Returns the updated Quaternion.
  4450. */
  4451. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4452. Quaternion.FromRotationMatrixToRef(matrix, this);
  4453. return this;
  4454. };
  4455. // Statics
  4456. /**
  4457. * Returns a new Quaternion set from the passed rotation matrix values.
  4458. */
  4459. Quaternion.FromRotationMatrix = function (matrix) {
  4460. var result = new Quaternion();
  4461. Quaternion.FromRotationMatrixToRef(matrix, result);
  4462. return result;
  4463. };
  4464. /**
  4465. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4466. */
  4467. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4468. var data = matrix.m;
  4469. var m11 = data[0], m12 = data[4], m13 = data[8];
  4470. var m21 = data[1], m22 = data[5], m23 = data[9];
  4471. var m31 = data[2], m32 = data[6], m33 = data[10];
  4472. var trace = m11 + m22 + m33;
  4473. var s;
  4474. if (trace > 0) {
  4475. s = 0.5 / Math.sqrt(trace + 1.0);
  4476. result.w = 0.25 / s;
  4477. result.x = (m32 - m23) * s;
  4478. result.y = (m13 - m31) * s;
  4479. result.z = (m21 - m12) * s;
  4480. }
  4481. else if (m11 > m22 && m11 > m33) {
  4482. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4483. result.w = (m32 - m23) / s;
  4484. result.x = 0.25 * s;
  4485. result.y = (m12 + m21) / s;
  4486. result.z = (m13 + m31) / s;
  4487. }
  4488. else if (m22 > m33) {
  4489. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4490. result.w = (m13 - m31) / s;
  4491. result.x = (m12 + m21) / s;
  4492. result.y = 0.25 * s;
  4493. result.z = (m23 + m32) / s;
  4494. }
  4495. else {
  4496. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4497. result.w = (m21 - m12) / s;
  4498. result.x = (m13 + m31) / s;
  4499. result.y = (m23 + m32) / s;
  4500. result.z = 0.25 * s;
  4501. }
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4505. */
  4506. Quaternion.Zero = function () {
  4507. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4508. };
  4509. /**
  4510. * Returns a new Quaternion as the inverted current Quaternion.
  4511. */
  4512. Quaternion.Inverse = function (q) {
  4513. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4514. };
  4515. /**
  4516. * Returns the identity Quaternion.
  4517. */
  4518. Quaternion.Identity = function () {
  4519. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4520. };
  4521. Quaternion.IsIdentity = function (quaternion) {
  4522. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4523. };
  4524. /**
  4525. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4526. */
  4527. Quaternion.RotationAxis = function (axis, angle) {
  4528. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4529. };
  4530. /**
  4531. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4532. */
  4533. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4534. var sin = Math.sin(angle / 2);
  4535. axis.normalize();
  4536. result.w = Math.cos(angle / 2);
  4537. result.x = axis.x * sin;
  4538. result.y = axis.y * sin;
  4539. result.z = axis.z * sin;
  4540. return result;
  4541. };
  4542. /**
  4543. * Retuns a new Quaternion set from the starting index of the passed array.
  4544. */
  4545. Quaternion.FromArray = function (array, offset) {
  4546. if (!offset) {
  4547. offset = 0;
  4548. }
  4549. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4550. };
  4551. /**
  4552. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4553. */
  4554. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4555. var q = new Quaternion();
  4556. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4557. return q;
  4558. };
  4559. /**
  4560. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4561. */
  4562. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4563. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4564. var halfRoll = roll * 0.5;
  4565. var halfPitch = pitch * 0.5;
  4566. var halfYaw = yaw * 0.5;
  4567. var sinRoll = Math.sin(halfRoll);
  4568. var cosRoll = Math.cos(halfRoll);
  4569. var sinPitch = Math.sin(halfPitch);
  4570. var cosPitch = Math.cos(halfPitch);
  4571. var sinYaw = Math.sin(halfYaw);
  4572. var cosYaw = Math.cos(halfYaw);
  4573. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4574. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4575. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4576. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4577. };
  4578. /**
  4579. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4580. */
  4581. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4582. var result = new Quaternion();
  4583. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4584. return result;
  4585. };
  4586. /**
  4587. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4588. */
  4589. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4590. // Produces a quaternion from Euler angles in the z-x-z orientation
  4591. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4592. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4593. var halfBeta = beta * 0.5;
  4594. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4595. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4596. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4597. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4598. };
  4599. /**
  4600. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4601. * cf to Vector3.RotationFromAxis() documentation.
  4602. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4603. */
  4604. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4605. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4607. return quat;
  4608. };
  4609. /**
  4610. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4611. * cf to Vector3.RotationFromAxis() documentation.
  4612. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4613. */
  4614. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4615. var rotMat = MathTmp.Matrix[0];
  4616. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4617. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4618. };
  4619. Quaternion.Slerp = function (left, right, amount) {
  4620. var result = Quaternion.Identity();
  4621. Quaternion.SlerpToRef(left, right, amount, result);
  4622. return result;
  4623. };
  4624. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4625. var num2;
  4626. var num3;
  4627. var num = amount;
  4628. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4629. var flag = false;
  4630. if (num4 < 0) {
  4631. flag = true;
  4632. num4 = -num4;
  4633. }
  4634. if (num4 > 0.999999) {
  4635. num3 = 1 - num;
  4636. num2 = flag ? -num : num;
  4637. }
  4638. else {
  4639. var num5 = Math.acos(num4);
  4640. var num6 = (1.0 / Math.sin(num5));
  4641. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4642. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4643. }
  4644. result.x = (num3 * left.x) + (num2 * right.x);
  4645. result.y = (num3 * left.y) + (num2 * right.y);
  4646. result.z = (num3 * left.z) + (num2 * right.z);
  4647. result.w = (num3 * left.w) + (num2 * right.w);
  4648. };
  4649. /**
  4650. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4651. */
  4652. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4653. var squared = amount * amount;
  4654. var cubed = amount * squared;
  4655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4657. var part3 = (cubed - (2.0 * squared)) + amount;
  4658. var part4 = cubed - squared;
  4659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4661. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4662. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4663. return new Quaternion(x, y, z, w);
  4664. };
  4665. return Quaternion;
  4666. }());
  4667. BABYLON.Quaternion = Quaternion;
  4668. var Matrix = /** @class */ (function () {
  4669. function Matrix() {
  4670. this._isIdentity = false;
  4671. this._isIdentityDirty = true;
  4672. this.m = new Float32Array(16);
  4673. this._markAsUpdated();
  4674. }
  4675. Matrix.prototype._markAsUpdated = function () {
  4676. this.updateFlag = Matrix._updateFlagSeed++;
  4677. this._isIdentityDirty = true;
  4678. };
  4679. // Properties
  4680. /**
  4681. * Boolean : True is the matrix is the identity matrix
  4682. */
  4683. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4684. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4685. if (this._isIdentityDirty) {
  4686. this._isIdentityDirty = false;
  4687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4688. this._isIdentity = false;
  4689. }
  4690. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4691. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4692. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4693. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4694. this._isIdentity = false;
  4695. }
  4696. else {
  4697. this._isIdentity = true;
  4698. }
  4699. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4700. this._isIdentity = false;
  4701. }
  4702. }
  4703. return this._isIdentity;
  4704. };
  4705. /**
  4706. * Returns the matrix determinant (float).
  4707. */
  4708. Matrix.prototype.determinant = function () {
  4709. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4710. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4711. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4712. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4713. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4714. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4715. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4716. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4717. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4718. };
  4719. // Methods
  4720. /**
  4721. * Returns the matrix underlying array.
  4722. */
  4723. Matrix.prototype.toArray = function () {
  4724. return this.m;
  4725. };
  4726. /**
  4727. * Returns the matrix underlying array.
  4728. */
  4729. Matrix.prototype.asArray = function () {
  4730. return this.toArray();
  4731. };
  4732. /**
  4733. * Inverts in place the Matrix.
  4734. * Returns the Matrix inverted.
  4735. */
  4736. Matrix.prototype.invert = function () {
  4737. this.invertToRef(this);
  4738. return this;
  4739. };
  4740. /**
  4741. * Sets all the matrix elements to zero.
  4742. * Returns the Matrix.
  4743. */
  4744. Matrix.prototype.reset = function () {
  4745. for (var index = 0; index < 16; index++) {
  4746. this.m[index] = 0.0;
  4747. }
  4748. this._markAsUpdated();
  4749. return this;
  4750. };
  4751. /**
  4752. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4753. */
  4754. Matrix.prototype.add = function (other) {
  4755. var result = new Matrix();
  4756. this.addToRef(other, result);
  4757. return result;
  4758. };
  4759. /**
  4760. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4761. * Returns the Matrix.
  4762. */
  4763. Matrix.prototype.addToRef = function (other, result) {
  4764. for (var index = 0; index < 16; index++) {
  4765. result.m[index] = this.m[index] + other.m[index];
  4766. }
  4767. result._markAsUpdated();
  4768. return this;
  4769. };
  4770. /**
  4771. * Adds in place the passed matrix to the current Matrix.
  4772. * Returns the updated Matrix.
  4773. */
  4774. Matrix.prototype.addToSelf = function (other) {
  4775. for (var index = 0; index < 16; index++) {
  4776. this.m[index] += other.m[index];
  4777. }
  4778. this._markAsUpdated();
  4779. return this;
  4780. };
  4781. /**
  4782. * Sets the passed matrix with the current inverted Matrix.
  4783. * Returns the unmodified current Matrix.
  4784. */
  4785. Matrix.prototype.invertToRef = function (other) {
  4786. var l1 = this.m[0];
  4787. var l2 = this.m[1];
  4788. var l3 = this.m[2];
  4789. var l4 = this.m[3];
  4790. var l5 = this.m[4];
  4791. var l6 = this.m[5];
  4792. var l7 = this.m[6];
  4793. var l8 = this.m[7];
  4794. var l9 = this.m[8];
  4795. var l10 = this.m[9];
  4796. var l11 = this.m[10];
  4797. var l12 = this.m[11];
  4798. var l13 = this.m[12];
  4799. var l14 = this.m[13];
  4800. var l15 = this.m[14];
  4801. var l16 = this.m[15];
  4802. var l17 = (l11 * l16) - (l12 * l15);
  4803. var l18 = (l10 * l16) - (l12 * l14);
  4804. var l19 = (l10 * l15) - (l11 * l14);
  4805. var l20 = (l9 * l16) - (l12 * l13);
  4806. var l21 = (l9 * l15) - (l11 * l13);
  4807. var l22 = (l9 * l14) - (l10 * l13);
  4808. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4809. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4810. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4811. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4812. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4813. var l28 = (l7 * l16) - (l8 * l15);
  4814. var l29 = (l6 * l16) - (l8 * l14);
  4815. var l30 = (l6 * l15) - (l7 * l14);
  4816. var l31 = (l5 * l16) - (l8 * l13);
  4817. var l32 = (l5 * l15) - (l7 * l13);
  4818. var l33 = (l5 * l14) - (l6 * l13);
  4819. var l34 = (l7 * l12) - (l8 * l11);
  4820. var l35 = (l6 * l12) - (l8 * l10);
  4821. var l36 = (l6 * l11) - (l7 * l10);
  4822. var l37 = (l5 * l12) - (l8 * l9);
  4823. var l38 = (l5 * l11) - (l7 * l9);
  4824. var l39 = (l5 * l10) - (l6 * l9);
  4825. other.m[0] = l23 * l27;
  4826. other.m[4] = l24 * l27;
  4827. other.m[8] = l25 * l27;
  4828. other.m[12] = l26 * l27;
  4829. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4830. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4831. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4832. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4833. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4834. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4835. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4836. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4837. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4838. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4839. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4840. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4841. other._markAsUpdated();
  4842. return this;
  4843. };
  4844. /**
  4845. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4846. * Returns the updated Matrix.
  4847. */
  4848. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4849. this.m[12] = x;
  4850. this.m[13] = y;
  4851. this.m[14] = z;
  4852. this._markAsUpdated();
  4853. return this;
  4854. };
  4855. /**
  4856. * Inserts the translation vector in the current Matrix.
  4857. * Returns the updated Matrix.
  4858. */
  4859. Matrix.prototype.setTranslation = function (vector3) {
  4860. this.m[12] = vector3.x;
  4861. this.m[13] = vector3.y;
  4862. this.m[14] = vector3.z;
  4863. this._markAsUpdated();
  4864. return this;
  4865. };
  4866. /**
  4867. * Returns a new Vector3 as the extracted translation from the Matrix.
  4868. */
  4869. Matrix.prototype.getTranslation = function () {
  4870. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4871. };
  4872. /**
  4873. * Fill a Vector3 with the extracted translation from the Matrix.
  4874. */
  4875. Matrix.prototype.getTranslationToRef = function (result) {
  4876. result.x = this.m[12];
  4877. result.y = this.m[13];
  4878. result.z = this.m[14];
  4879. return this;
  4880. };
  4881. /**
  4882. * Remove rotation and scaling part from the Matrix.
  4883. * Returns the updated Matrix.
  4884. */
  4885. Matrix.prototype.removeRotationAndScaling = function () {
  4886. this.setRowFromFloats(0, 1, 0, 0, 0);
  4887. this.setRowFromFloats(1, 0, 1, 0, 0);
  4888. this.setRowFromFloats(2, 0, 0, 1, 0);
  4889. return this;
  4890. };
  4891. /**
  4892. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4893. */
  4894. Matrix.prototype.multiply = function (other) {
  4895. var result = new Matrix();
  4896. this.multiplyToRef(other, result);
  4897. return result;
  4898. };
  4899. /**
  4900. * Updates the current Matrix from the passed one values.
  4901. * Returns the updated Matrix.
  4902. */
  4903. Matrix.prototype.copyFrom = function (other) {
  4904. for (var index = 0; index < 16; index++) {
  4905. this.m[index] = other.m[index];
  4906. }
  4907. this._markAsUpdated();
  4908. return this;
  4909. };
  4910. /**
  4911. * Populates the passed array from the starting index with the Matrix values.
  4912. * Returns the Matrix.
  4913. */
  4914. Matrix.prototype.copyToArray = function (array, offset) {
  4915. if (offset === void 0) { offset = 0; }
  4916. for (var index = 0; index < 16; index++) {
  4917. array[offset + index] = this.m[index];
  4918. }
  4919. return this;
  4920. };
  4921. /**
  4922. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4923. */
  4924. Matrix.prototype.multiplyToRef = function (other, result) {
  4925. this.multiplyToArray(other, result.m, 0);
  4926. result._markAsUpdated();
  4927. return this;
  4928. };
  4929. /**
  4930. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4931. */
  4932. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4933. var tm0 = this.m[0];
  4934. var tm1 = this.m[1];
  4935. var tm2 = this.m[2];
  4936. var tm3 = this.m[3];
  4937. var tm4 = this.m[4];
  4938. var tm5 = this.m[5];
  4939. var tm6 = this.m[6];
  4940. var tm7 = this.m[7];
  4941. var tm8 = this.m[8];
  4942. var tm9 = this.m[9];
  4943. var tm10 = this.m[10];
  4944. var tm11 = this.m[11];
  4945. var tm12 = this.m[12];
  4946. var tm13 = this.m[13];
  4947. var tm14 = this.m[14];
  4948. var tm15 = this.m[15];
  4949. var om0 = other.m[0];
  4950. var om1 = other.m[1];
  4951. var om2 = other.m[2];
  4952. var om3 = other.m[3];
  4953. var om4 = other.m[4];
  4954. var om5 = other.m[5];
  4955. var om6 = other.m[6];
  4956. var om7 = other.m[7];
  4957. var om8 = other.m[8];
  4958. var om9 = other.m[9];
  4959. var om10 = other.m[10];
  4960. var om11 = other.m[11];
  4961. var om12 = other.m[12];
  4962. var om13 = other.m[13];
  4963. var om14 = other.m[14];
  4964. var om15 = other.m[15];
  4965. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4966. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4967. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4968. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4969. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4970. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4971. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4972. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4973. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4974. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4975. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4976. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4977. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4978. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4979. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4980. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4981. return this;
  4982. };
  4983. /**
  4984. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4985. */
  4986. Matrix.prototype.equals = function (value) {
  4987. return value &&
  4988. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4989. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4990. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4991. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4992. };
  4993. /**
  4994. * Returns a new Matrix from the current Matrix.
  4995. */
  4996. Matrix.prototype.clone = function () {
  4997. 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]);
  4998. };
  4999. /**
  5000. * Returns the string "Matrix"
  5001. */
  5002. Matrix.prototype.getClassName = function () {
  5003. return "Matrix";
  5004. };
  5005. /**
  5006. * Returns the Matrix hash code.
  5007. */
  5008. Matrix.prototype.getHashCode = function () {
  5009. var hash = this.m[0] || 0;
  5010. for (var i = 1; i < 16; i++) {
  5011. hash = (hash * 397) ^ (this.m[i] || 0);
  5012. }
  5013. return hash;
  5014. };
  5015. /**
  5016. * Decomposes the current Matrix into :
  5017. * - a scale vector3 passed as a reference to update,
  5018. * - a rotation quaternion passed as a reference to update,
  5019. * - a translation vector3 passed as a reference to update.
  5020. * Returns the true if operation was successful.
  5021. */
  5022. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5023. translation.x = this.m[12];
  5024. translation.y = this.m[13];
  5025. translation.z = this.m[14];
  5026. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5027. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5028. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5029. if (this.determinant() <= 0) {
  5030. scale.y *= -1;
  5031. }
  5032. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5033. rotation.x = 0;
  5034. rotation.y = 0;
  5035. rotation.z = 0;
  5036. rotation.w = 1;
  5037. return false;
  5038. }
  5039. 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]);
  5040. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5041. return true;
  5042. };
  5043. /**
  5044. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5045. * @param ref matrix to store the result
  5046. */
  5047. Matrix.prototype.toNormalMatrix = function (ref) {
  5048. this.invertToRef(ref);
  5049. ref.transpose();
  5050. var m = ref.m;
  5051. 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);
  5052. };
  5053. /**
  5054. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5055. */
  5056. Matrix.prototype.getRotationMatrix = function () {
  5057. var result = Matrix.Identity();
  5058. this.getRotationMatrixToRef(result);
  5059. return result;
  5060. };
  5061. /**
  5062. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5063. * Returns the current Matrix.
  5064. */
  5065. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5066. var m = this.m;
  5067. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5068. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5069. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5070. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5071. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5072. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5073. 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);
  5074. return this;
  5075. };
  5076. // Statics
  5077. /**
  5078. * Returns a new Matrix set from the starting index of the passed array.
  5079. */
  5080. Matrix.FromArray = function (array, offset) {
  5081. var result = new Matrix();
  5082. if (!offset) {
  5083. offset = 0;
  5084. }
  5085. Matrix.FromArrayToRef(array, offset, result);
  5086. return result;
  5087. };
  5088. /**
  5089. * Sets the passed "result" matrix from the starting index of the passed array.
  5090. */
  5091. Matrix.FromArrayToRef = function (array, offset, result) {
  5092. for (var index = 0; index < 16; index++) {
  5093. result.m[index] = array[index + offset];
  5094. }
  5095. result._markAsUpdated();
  5096. };
  5097. /**
  5098. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5099. */
  5100. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = array[index + offset] * scale;
  5103. }
  5104. result._markAsUpdated();
  5105. };
  5106. /**
  5107. * Sets the passed matrix "result" with the 16 passed floats.
  5108. */
  5109. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5110. result.m[0] = initialM11;
  5111. result.m[1] = initialM12;
  5112. result.m[2] = initialM13;
  5113. result.m[3] = initialM14;
  5114. result.m[4] = initialM21;
  5115. result.m[5] = initialM22;
  5116. result.m[6] = initialM23;
  5117. result.m[7] = initialM24;
  5118. result.m[8] = initialM31;
  5119. result.m[9] = initialM32;
  5120. result.m[10] = initialM33;
  5121. result.m[11] = initialM34;
  5122. result.m[12] = initialM41;
  5123. result.m[13] = initialM42;
  5124. result.m[14] = initialM43;
  5125. result.m[15] = initialM44;
  5126. result._markAsUpdated();
  5127. };
  5128. /**
  5129. * Returns the index-th row of the current matrix as a new Vector4.
  5130. */
  5131. Matrix.prototype.getRow = function (index) {
  5132. if (index < 0 || index > 3) {
  5133. return null;
  5134. }
  5135. var i = index * 4;
  5136. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5137. };
  5138. /**
  5139. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5140. * Returns the updated Matrix.
  5141. */
  5142. Matrix.prototype.setRow = function (index, row) {
  5143. if (index < 0 || index > 3) {
  5144. return this;
  5145. }
  5146. var i = index * 4;
  5147. this.m[i + 0] = row.x;
  5148. this.m[i + 1] = row.y;
  5149. this.m[i + 2] = row.z;
  5150. this.m[i + 3] = row.w;
  5151. this._markAsUpdated();
  5152. return this;
  5153. };
  5154. /**
  5155. * Compute the transpose of the matrix.
  5156. * Returns a new Matrix.
  5157. */
  5158. Matrix.prototype.transpose = function () {
  5159. return Matrix.Transpose(this);
  5160. };
  5161. /**
  5162. * Compute the transpose of the matrix.
  5163. * Returns the current matrix.
  5164. */
  5165. Matrix.prototype.transposeToRef = function (result) {
  5166. Matrix.TransposeToRef(this, result);
  5167. return this;
  5168. };
  5169. /**
  5170. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5171. * Returns the updated Matrix.
  5172. */
  5173. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5174. if (index < 0 || index > 3) {
  5175. return this;
  5176. }
  5177. var i = index * 4;
  5178. this.m[i + 0] = x;
  5179. this.m[i + 1] = y;
  5180. this.m[i + 2] = z;
  5181. this.m[i + 3] = w;
  5182. this._markAsUpdated();
  5183. return this;
  5184. };
  5185. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5186. /**
  5187. * Static identity matrix to be used as readonly matrix
  5188. * Must not be updated.
  5189. */
  5190. get: function () {
  5191. return Matrix._identityReadOnly;
  5192. },
  5193. enumerable: true,
  5194. configurable: true
  5195. });
  5196. /**
  5197. * Returns a new Matrix set from the 16 passed floats.
  5198. */
  5199. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5200. var result = new Matrix();
  5201. result.m[0] = initialM11;
  5202. result.m[1] = initialM12;
  5203. result.m[2] = initialM13;
  5204. result.m[3] = initialM14;
  5205. result.m[4] = initialM21;
  5206. result.m[5] = initialM22;
  5207. result.m[6] = initialM23;
  5208. result.m[7] = initialM24;
  5209. result.m[8] = initialM31;
  5210. result.m[9] = initialM32;
  5211. result.m[10] = initialM33;
  5212. result.m[11] = initialM34;
  5213. result.m[12] = initialM41;
  5214. result.m[13] = initialM42;
  5215. result.m[14] = initialM43;
  5216. result.m[15] = initialM44;
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5221. */
  5222. Matrix.Compose = function (scale, rotation, translation) {
  5223. var result = Matrix.Identity();
  5224. Matrix.ComposeToRef(scale, rotation, translation, result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5229. */
  5230. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5231. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5232. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5233. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5234. result.setTranslation(translation);
  5235. };
  5236. /**
  5237. * Returns a new indentity Matrix.
  5238. */
  5239. Matrix.Identity = function () {
  5240. 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);
  5241. };
  5242. /**
  5243. * Sets the passed "result" as an identity matrix.
  5244. */
  5245. Matrix.IdentityToRef = function (result) {
  5246. 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);
  5247. };
  5248. /**
  5249. * Returns a new zero Matrix.
  5250. */
  5251. Matrix.Zero = function () {
  5252. 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);
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the X axis.
  5256. */
  5257. Matrix.RotationX = function (angle) {
  5258. var result = new Matrix();
  5259. Matrix.RotationXToRef(angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Returns a new Matrix as the passed inverted one.
  5264. */
  5265. Matrix.Invert = function (source) {
  5266. var result = new Matrix();
  5267. source.invertToRef(result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5272. */
  5273. Matrix.RotationXToRef = function (angle, result) {
  5274. var s = Math.sin(angle);
  5275. var c = Math.cos(angle);
  5276. result.m[0] = 1.0;
  5277. result.m[15] = 1.0;
  5278. result.m[5] = c;
  5279. result.m[10] = c;
  5280. result.m[9] = -s;
  5281. result.m[6] = s;
  5282. result.m[1] = 0.0;
  5283. result.m[2] = 0.0;
  5284. result.m[3] = 0.0;
  5285. result.m[4] = 0.0;
  5286. result.m[7] = 0.0;
  5287. result.m[8] = 0.0;
  5288. result.m[11] = 0.0;
  5289. result.m[12] = 0.0;
  5290. result.m[13] = 0.0;
  5291. result.m[14] = 0.0;
  5292. result._markAsUpdated();
  5293. };
  5294. /**
  5295. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5296. */
  5297. Matrix.RotationY = function (angle) {
  5298. var result = new Matrix();
  5299. Matrix.RotationYToRef(angle, result);
  5300. return result;
  5301. };
  5302. /**
  5303. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5304. */
  5305. Matrix.RotationYToRef = function (angle, result) {
  5306. var s = Math.sin(angle);
  5307. var c = Math.cos(angle);
  5308. result.m[5] = 1.0;
  5309. result.m[15] = 1.0;
  5310. result.m[0] = c;
  5311. result.m[2] = -s;
  5312. result.m[8] = s;
  5313. result.m[10] = c;
  5314. result.m[1] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[6] = 0.0;
  5318. result.m[7] = 0.0;
  5319. result.m[9] = 0.0;
  5320. result.m[11] = 0.0;
  5321. result.m[12] = 0.0;
  5322. result.m[13] = 0.0;
  5323. result.m[14] = 0.0;
  5324. result._markAsUpdated();
  5325. };
  5326. /**
  5327. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5328. */
  5329. Matrix.RotationZ = function (angle) {
  5330. var result = new Matrix();
  5331. Matrix.RotationZToRef(angle, result);
  5332. return result;
  5333. };
  5334. /**
  5335. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5336. */
  5337. Matrix.RotationZToRef = function (angle, result) {
  5338. var s = Math.sin(angle);
  5339. var c = Math.cos(angle);
  5340. result.m[10] = 1.0;
  5341. result.m[15] = 1.0;
  5342. result.m[0] = c;
  5343. result.m[1] = s;
  5344. result.m[4] = -s;
  5345. result.m[5] = c;
  5346. result.m[2] = 0.0;
  5347. result.m[3] = 0.0;
  5348. result.m[6] = 0.0;
  5349. result.m[7] = 0.0;
  5350. result.m[8] = 0.0;
  5351. result.m[9] = 0.0;
  5352. result.m[11] = 0.0;
  5353. result.m[12] = 0.0;
  5354. result.m[13] = 0.0;
  5355. result.m[14] = 0.0;
  5356. result._markAsUpdated();
  5357. };
  5358. /**
  5359. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5360. */
  5361. Matrix.RotationAxis = function (axis, angle) {
  5362. var result = Matrix.Zero();
  5363. Matrix.RotationAxisToRef(axis, angle, result);
  5364. return result;
  5365. };
  5366. /**
  5367. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5368. */
  5369. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5370. var s = Math.sin(-angle);
  5371. var c = Math.cos(-angle);
  5372. var c1 = 1 - c;
  5373. axis.normalize();
  5374. result.m[0] = (axis.x * axis.x) * c1 + c;
  5375. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5376. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5377. result.m[3] = 0.0;
  5378. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5379. result.m[5] = (axis.y * axis.y) * c1 + c;
  5380. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5381. result.m[7] = 0.0;
  5382. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5383. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5384. result.m[10] = (axis.z * axis.z) * c1 + c;
  5385. result.m[11] = 0.0;
  5386. result.m[15] = 1.0;
  5387. result._markAsUpdated();
  5388. };
  5389. /**
  5390. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5391. */
  5392. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5393. var result = new Matrix();
  5394. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5395. return result;
  5396. };
  5397. /**
  5398. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5399. */
  5400. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5401. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5402. this._tempQuaternion.toRotationMatrix(result);
  5403. };
  5404. /**
  5405. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5406. */
  5407. Matrix.Scaling = function (x, y, z) {
  5408. var result = Matrix.Zero();
  5409. Matrix.ScalingToRef(x, y, z, result);
  5410. return result;
  5411. };
  5412. /**
  5413. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5414. */
  5415. Matrix.ScalingToRef = function (x, y, z, result) {
  5416. result.m[0] = x;
  5417. result.m[1] = 0.0;
  5418. result.m[2] = 0.0;
  5419. result.m[3] = 0.0;
  5420. result.m[4] = 0.0;
  5421. result.m[5] = y;
  5422. result.m[6] = 0.0;
  5423. result.m[7] = 0.0;
  5424. result.m[8] = 0.0;
  5425. result.m[9] = 0.0;
  5426. result.m[10] = z;
  5427. result.m[11] = 0.0;
  5428. result.m[12] = 0.0;
  5429. result.m[13] = 0.0;
  5430. result.m[14] = 0.0;
  5431. result.m[15] = 1.0;
  5432. result._markAsUpdated();
  5433. };
  5434. /**
  5435. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5436. */
  5437. Matrix.Translation = function (x, y, z) {
  5438. var result = Matrix.Identity();
  5439. Matrix.TranslationToRef(x, y, z, result);
  5440. return result;
  5441. };
  5442. /**
  5443. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5444. */
  5445. Matrix.TranslationToRef = function (x, y, z, result) {
  5446. 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);
  5447. };
  5448. /**
  5449. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5450. * @param startValue defines the start value
  5451. * @param endValue defines the end value
  5452. * @param gradient defines the gradient factor
  5453. * @returns the new matrix
  5454. */
  5455. Matrix.Lerp = function (startValue, endValue, gradient) {
  5456. var result = Matrix.Zero();
  5457. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5458. return result;
  5459. };
  5460. /**
  5461. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5462. * @param startValue defines the start value
  5463. * @param endValue defines the end value
  5464. * @param gradient defines the gradient factor
  5465. * @param result defines the Matrix object where to store data
  5466. */
  5467. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5468. for (var index = 0; index < 16; index++) {
  5469. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5470. }
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new Matrix whose values are computed by :
  5475. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5476. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5477. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5478. */
  5479. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5480. var startScale = new Vector3(0, 0, 0);
  5481. var startRotation = new Quaternion();
  5482. var startTranslation = new Vector3(0, 0, 0);
  5483. startValue.decompose(startScale, startRotation, startTranslation);
  5484. var endScale = new Vector3(0, 0, 0);
  5485. var endRotation = new Quaternion();
  5486. var endTranslation = new Vector3(0, 0, 0);
  5487. endValue.decompose(endScale, endRotation, endTranslation);
  5488. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5489. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5490. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5491. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5492. };
  5493. /**
  5494. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5495. * This methods works for a Left-Handed system.
  5496. */
  5497. Matrix.LookAtLH = function (eye, target, up) {
  5498. var result = Matrix.Zero();
  5499. Matrix.LookAtLHToRef(eye, target, up, result);
  5500. return result;
  5501. };
  5502. /**
  5503. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5504. * This methods works for a Left-Handed system.
  5505. */
  5506. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5507. // Z axis
  5508. target.subtractToRef(eye, this._zAxis);
  5509. this._zAxis.normalize();
  5510. // X axis
  5511. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5512. if (this._xAxis.lengthSquared() === 0) {
  5513. this._xAxis.x = 1.0;
  5514. }
  5515. else {
  5516. this._xAxis.normalize();
  5517. }
  5518. // Y axis
  5519. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5520. this._yAxis.normalize();
  5521. // Eye angles
  5522. var ex = -Vector3.Dot(this._xAxis, eye);
  5523. var ey = -Vector3.Dot(this._yAxis, eye);
  5524. var ez = -Vector3.Dot(this._zAxis, eye);
  5525. 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);
  5526. };
  5527. /**
  5528. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5529. * This methods works for a Right-Handed system.
  5530. */
  5531. Matrix.LookAtRH = function (eye, target, up) {
  5532. var result = Matrix.Zero();
  5533. Matrix.LookAtRHToRef(eye, target, up, result);
  5534. return result;
  5535. };
  5536. /**
  5537. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5538. * This methods works for a Left-Handed system.
  5539. */
  5540. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5541. // Z axis
  5542. eye.subtractToRef(target, this._zAxis);
  5543. this._zAxis.normalize();
  5544. // X axis
  5545. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5546. if (this._xAxis.lengthSquared() === 0) {
  5547. this._xAxis.x = 1.0;
  5548. }
  5549. else {
  5550. this._xAxis.normalize();
  5551. }
  5552. // Y axis
  5553. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5554. this._yAxis.normalize();
  5555. // Eye angles
  5556. var ex = -Vector3.Dot(this._xAxis, eye);
  5557. var ey = -Vector3.Dot(this._yAxis, eye);
  5558. var ez = -Vector3.Dot(this._zAxis, eye);
  5559. 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);
  5560. };
  5561. /**
  5562. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5563. */
  5564. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5567. return matrix;
  5568. };
  5569. /**
  5570. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5571. */
  5572. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5573. var n = znear;
  5574. var f = zfar;
  5575. var a = 2.0 / width;
  5576. var b = 2.0 / height;
  5577. var c = 2.0 / (f - n);
  5578. var d = -(f + n) / (f - n);
  5579. 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);
  5580. };
  5581. /**
  5582. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5583. */
  5584. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5585. var matrix = Matrix.Zero();
  5586. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5587. return matrix;
  5588. };
  5589. /**
  5590. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5591. */
  5592. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5593. var n = znear;
  5594. var f = zfar;
  5595. var a = 2.0 / (right - left);
  5596. var b = 2.0 / (top - bottom);
  5597. var c = 2.0 / (f - n);
  5598. var d = -(f + n) / (f - n);
  5599. var i0 = (left + right) / (left - right);
  5600. var i1 = (top + bottom) / (bottom - top);
  5601. 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);
  5602. };
  5603. /**
  5604. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5605. */
  5606. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5607. var matrix = Matrix.Zero();
  5608. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5609. return matrix;
  5610. };
  5611. /**
  5612. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5613. */
  5614. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5615. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5616. result.m[10] *= -1.0;
  5617. };
  5618. /**
  5619. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5620. */
  5621. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5622. var matrix = Matrix.Zero();
  5623. var n = znear;
  5624. var f = zfar;
  5625. var a = 2.0 * n / width;
  5626. var b = 2.0 * n / height;
  5627. var c = (f + n) / (f - n);
  5628. var d = -2.0 * f * n / (f - n);
  5629. 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);
  5630. return matrix;
  5631. };
  5632. /**
  5633. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5634. */
  5635. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5636. var matrix = Matrix.Zero();
  5637. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5638. return matrix;
  5639. };
  5640. /**
  5641. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5642. */
  5643. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5645. var n = znear;
  5646. var f = zfar;
  5647. var t = 1.0 / (Math.tan(fov * 0.5));
  5648. var a = isVerticalFovFixed ? (t / aspect) : t;
  5649. var b = isVerticalFovFixed ? t : (t * aspect);
  5650. var c = (f + n) / (f - n);
  5651. var d = -2.0 * f * n / (f - n);
  5652. 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);
  5653. };
  5654. /**
  5655. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5656. */
  5657. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5664. */
  5665. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5666. //alternatively this could be expressed as:
  5667. // m = PerspectiveFovLHToRef
  5668. // m[10] *= -1.0;
  5669. // m[11] *= -1.0;
  5670. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5671. var n = znear;
  5672. var f = zfar;
  5673. var t = 1.0 / (Math.tan(fov * 0.5));
  5674. var a = isVerticalFovFixed ? (t / aspect) : t;
  5675. var b = isVerticalFovFixed ? t : (t * aspect);
  5676. var c = -(f + n) / (f - n);
  5677. var d = -2 * f * n / (f - n);
  5678. 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);
  5679. };
  5680. /**
  5681. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5682. */
  5683. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5684. if (rightHanded === void 0) { rightHanded = false; }
  5685. var rightHandedFactor = rightHanded ? -1 : 1;
  5686. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5687. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5688. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5689. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5690. var xScale = 2.0 / (leftTan + rightTan);
  5691. var yScale = 2.0 / (upTan + downTan);
  5692. result.m[0] = xScale;
  5693. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5694. result.m[5] = yScale;
  5695. result.m[6] = result.m[7] = 0.0;
  5696. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5697. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5698. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5699. result.m[10] = -zfar / (znear - zfar);
  5700. result.m[11] = 1.0 * rightHandedFactor;
  5701. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5702. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5703. // result.m[14] = (znear * zfar) / (znear - zfar);
  5704. result._markAsUpdated();
  5705. };
  5706. /**
  5707. * Returns the final transformation matrix : world * view * projection * viewport
  5708. */
  5709. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5710. var cw = viewport.width;
  5711. var ch = viewport.height;
  5712. var cx = viewport.x;
  5713. var cy = viewport.y;
  5714. 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);
  5715. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5716. };
  5717. /**
  5718. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5719. */
  5720. Matrix.GetAsMatrix2x2 = function (matrix) {
  5721. return new Float32Array([
  5722. matrix.m[0], matrix.m[1],
  5723. matrix.m[4], matrix.m[5]
  5724. ]);
  5725. };
  5726. /**
  5727. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5728. */
  5729. Matrix.GetAsMatrix3x3 = function (matrix) {
  5730. return new Float32Array([
  5731. matrix.m[0], matrix.m[1], matrix.m[2],
  5732. matrix.m[4], matrix.m[5], matrix.m[6],
  5733. matrix.m[8], matrix.m[9], matrix.m[10]
  5734. ]);
  5735. };
  5736. /**
  5737. * Compute the transpose of the passed Matrix.
  5738. * Returns a new Matrix.
  5739. */
  5740. Matrix.Transpose = function (matrix) {
  5741. var result = new Matrix();
  5742. Matrix.TransposeToRef(matrix, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5747. */
  5748. Matrix.TransposeToRef = function (matrix, result) {
  5749. result.m[0] = matrix.m[0];
  5750. result.m[1] = matrix.m[4];
  5751. result.m[2] = matrix.m[8];
  5752. result.m[3] = matrix.m[12];
  5753. result.m[4] = matrix.m[1];
  5754. result.m[5] = matrix.m[5];
  5755. result.m[6] = matrix.m[9];
  5756. result.m[7] = matrix.m[13];
  5757. result.m[8] = matrix.m[2];
  5758. result.m[9] = matrix.m[6];
  5759. result.m[10] = matrix.m[10];
  5760. result.m[11] = matrix.m[14];
  5761. result.m[12] = matrix.m[3];
  5762. result.m[13] = matrix.m[7];
  5763. result.m[14] = matrix.m[11];
  5764. result.m[15] = matrix.m[15];
  5765. };
  5766. /**
  5767. * Returns a new Matrix as the reflection matrix across the passed plane.
  5768. */
  5769. Matrix.Reflection = function (plane) {
  5770. var matrix = new Matrix();
  5771. Matrix.ReflectionToRef(plane, matrix);
  5772. return matrix;
  5773. };
  5774. /**
  5775. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5776. */
  5777. Matrix.ReflectionToRef = function (plane, result) {
  5778. plane.normalize();
  5779. var x = plane.normal.x;
  5780. var y = plane.normal.y;
  5781. var z = plane.normal.z;
  5782. var temp = -2 * x;
  5783. var temp2 = -2 * y;
  5784. var temp3 = -2 * z;
  5785. result.m[0] = (temp * x) + 1;
  5786. result.m[1] = temp2 * x;
  5787. result.m[2] = temp3 * x;
  5788. result.m[3] = 0.0;
  5789. result.m[4] = temp * y;
  5790. result.m[5] = (temp2 * y) + 1;
  5791. result.m[6] = temp3 * y;
  5792. result.m[7] = 0.0;
  5793. result.m[8] = temp * z;
  5794. result.m[9] = temp2 * z;
  5795. result.m[10] = (temp3 * z) + 1;
  5796. result.m[11] = 0.0;
  5797. result.m[12] = temp * plane.d;
  5798. result.m[13] = temp2 * plane.d;
  5799. result.m[14] = temp3 * plane.d;
  5800. result.m[15] = 1.0;
  5801. result._markAsUpdated();
  5802. };
  5803. /**
  5804. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5805. */
  5806. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5807. result.m[0] = xaxis.x;
  5808. result.m[1] = xaxis.y;
  5809. result.m[2] = xaxis.z;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = yaxis.x;
  5812. result.m[5] = yaxis.y;
  5813. result.m[6] = yaxis.z;
  5814. result.m[7] = 0.0;
  5815. result.m[8] = zaxis.x;
  5816. result.m[9] = zaxis.y;
  5817. result.m[10] = zaxis.z;
  5818. result.m[11] = 0.0;
  5819. result.m[12] = 0.0;
  5820. result.m[13] = 0.0;
  5821. result.m[14] = 0.0;
  5822. result.m[15] = 1.0;
  5823. result._markAsUpdated();
  5824. };
  5825. /**
  5826. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5827. */
  5828. Matrix.FromQuaternionToRef = function (quat, result) {
  5829. var xx = quat.x * quat.x;
  5830. var yy = quat.y * quat.y;
  5831. var zz = quat.z * quat.z;
  5832. var xy = quat.x * quat.y;
  5833. var zw = quat.z * quat.w;
  5834. var zx = quat.z * quat.x;
  5835. var yw = quat.y * quat.w;
  5836. var yz = quat.y * quat.z;
  5837. var xw = quat.x * quat.w;
  5838. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5839. result.m[1] = 2.0 * (xy + zw);
  5840. result.m[2] = 2.0 * (zx - yw);
  5841. result.m[3] = 0.0;
  5842. result.m[4] = 2.0 * (xy - zw);
  5843. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5844. result.m[6] = 2.0 * (yz + xw);
  5845. result.m[7] = 0.0;
  5846. result.m[8] = 2.0 * (zx + yw);
  5847. result.m[9] = 2.0 * (yz - xw);
  5848. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5849. result.m[11] = 0.0;
  5850. result.m[12] = 0.0;
  5851. result.m[13] = 0.0;
  5852. result.m[14] = 0.0;
  5853. result.m[15] = 1.0;
  5854. result._markAsUpdated();
  5855. };
  5856. Matrix._tempQuaternion = new Quaternion();
  5857. Matrix._xAxis = Vector3.Zero();
  5858. Matrix._yAxis = Vector3.Zero();
  5859. Matrix._zAxis = Vector3.Zero();
  5860. Matrix._updateFlagSeed = 0;
  5861. Matrix._identityReadOnly = Matrix.Identity();
  5862. return Matrix;
  5863. }());
  5864. BABYLON.Matrix = Matrix;
  5865. var Plane = /** @class */ (function () {
  5866. /**
  5867. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5868. */
  5869. function Plane(a, b, c, d) {
  5870. this.normal = new Vector3(a, b, c);
  5871. this.d = d;
  5872. }
  5873. /**
  5874. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5875. */
  5876. Plane.prototype.asArray = function () {
  5877. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5878. };
  5879. // Methods
  5880. /**
  5881. * Returns a new plane copied from the current Plane.
  5882. */
  5883. Plane.prototype.clone = function () {
  5884. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5885. };
  5886. /**
  5887. * Returns the string "Plane".
  5888. */
  5889. Plane.prototype.getClassName = function () {
  5890. return "Plane";
  5891. };
  5892. /**
  5893. * Returns the Plane hash code.
  5894. */
  5895. Plane.prototype.getHashCode = function () {
  5896. var hash = this.normal.getHashCode();
  5897. hash = (hash * 397) ^ (this.d || 0);
  5898. return hash;
  5899. };
  5900. /**
  5901. * Normalize the current Plane in place.
  5902. * Returns the updated Plane.
  5903. */
  5904. Plane.prototype.normalize = function () {
  5905. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5906. var magnitude = 0.0;
  5907. if (norm !== 0) {
  5908. magnitude = 1.0 / norm;
  5909. }
  5910. this.normal.x *= magnitude;
  5911. this.normal.y *= magnitude;
  5912. this.normal.z *= magnitude;
  5913. this.d *= magnitude;
  5914. return this;
  5915. };
  5916. /**
  5917. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5918. */
  5919. Plane.prototype.transform = function (transformation) {
  5920. var transposedMatrix = Matrix.Transpose(transformation);
  5921. var x = this.normal.x;
  5922. var y = this.normal.y;
  5923. var z = this.normal.z;
  5924. var d = this.d;
  5925. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5926. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5927. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5928. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5929. return new Plane(normalX, normalY, normalZ, finalD);
  5930. };
  5931. /**
  5932. * Returns the dot product (float) of the point coordinates and the plane normal.
  5933. */
  5934. Plane.prototype.dotCoordinate = function (point) {
  5935. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5936. };
  5937. /**
  5938. * Updates the current Plane from the plane defined by the three passed points.
  5939. * Returns the updated Plane.
  5940. */
  5941. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5942. var x1 = point2.x - point1.x;
  5943. var y1 = point2.y - point1.y;
  5944. var z1 = point2.z - point1.z;
  5945. var x2 = point3.x - point1.x;
  5946. var y2 = point3.y - point1.y;
  5947. var z2 = point3.z - point1.z;
  5948. var yz = (y1 * z2) - (z1 * y2);
  5949. var xz = (z1 * x2) - (x1 * z2);
  5950. var xy = (x1 * y2) - (y1 * x2);
  5951. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5952. var invPyth;
  5953. if (pyth !== 0) {
  5954. invPyth = 1.0 / pyth;
  5955. }
  5956. else {
  5957. invPyth = 0.0;
  5958. }
  5959. this.normal.x = yz * invPyth;
  5960. this.normal.y = xz * invPyth;
  5961. this.normal.z = xy * invPyth;
  5962. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5963. return this;
  5964. };
  5965. /**
  5966. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5967. */
  5968. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5969. var dot = Vector3.Dot(this.normal, direction);
  5970. return (dot <= epsilon);
  5971. };
  5972. /**
  5973. * Returns the signed distance (float) from the passed point to the Plane.
  5974. */
  5975. Plane.prototype.signedDistanceTo = function (point) {
  5976. return Vector3.Dot(point, this.normal) + this.d;
  5977. };
  5978. // Statics
  5979. /**
  5980. * Returns a new Plane from the passed array.
  5981. */
  5982. Plane.FromArray = function (array) {
  5983. return new Plane(array[0], array[1], array[2], array[3]);
  5984. };
  5985. /**
  5986. * Returns a new Plane defined by the three passed points.
  5987. */
  5988. Plane.FromPoints = function (point1, point2, point3) {
  5989. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5990. result.copyFromPoints(point1, point2, point3);
  5991. return result;
  5992. };
  5993. /**
  5994. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5995. * Note : the vector "normal" is updated because normalized.
  5996. */
  5997. Plane.FromPositionAndNormal = function (origin, normal) {
  5998. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5999. normal.normalize();
  6000. result.normal = normal;
  6001. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6002. return result;
  6003. };
  6004. /**
  6005. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6006. */
  6007. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6008. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6009. return Vector3.Dot(point, normal) + d;
  6010. };
  6011. return Plane;
  6012. }());
  6013. BABYLON.Plane = Plane;
  6014. var Viewport = /** @class */ (function () {
  6015. /**
  6016. * Creates a Viewport object located at (x, y) and sized (width, height).
  6017. */
  6018. function Viewport(x, y, width, height) {
  6019. this.x = x;
  6020. this.y = y;
  6021. this.width = width;
  6022. this.height = height;
  6023. }
  6024. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6025. if (renderWidthOrEngine.getRenderWidth) {
  6026. var engine = renderWidthOrEngine;
  6027. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6028. }
  6029. var renderWidth = renderWidthOrEngine;
  6030. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6031. };
  6032. /**
  6033. * Returns a new Viewport copied from the current one.
  6034. */
  6035. Viewport.prototype.clone = function () {
  6036. return new Viewport(this.x, this.y, this.width, this.height);
  6037. };
  6038. return Viewport;
  6039. }());
  6040. BABYLON.Viewport = Viewport;
  6041. var Frustum = /** @class */ (function () {
  6042. function Frustum() {
  6043. }
  6044. /**
  6045. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6046. */
  6047. Frustum.GetPlanes = function (transform) {
  6048. var frustumPlanes = [];
  6049. for (var index = 0; index < 6; index++) {
  6050. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6051. }
  6052. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6053. return frustumPlanes;
  6054. };
  6055. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6056. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6057. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6058. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6059. frustumPlane.d = transform.m[15] + transform.m[14];
  6060. frustumPlane.normalize();
  6061. };
  6062. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6063. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6064. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6065. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6066. frustumPlane.d = transform.m[15] - transform.m[14];
  6067. frustumPlane.normalize();
  6068. };
  6069. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6070. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6071. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6072. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6073. frustumPlane.d = transform.m[15] + transform.m[12];
  6074. frustumPlane.normalize();
  6075. };
  6076. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6077. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6078. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6079. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6080. frustumPlane.d = transform.m[15] - transform.m[12];
  6081. frustumPlane.normalize();
  6082. };
  6083. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6084. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6085. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6086. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6087. frustumPlane.d = transform.m[15] - transform.m[13];
  6088. frustumPlane.normalize();
  6089. };
  6090. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6091. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6092. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6093. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6094. frustumPlane.d = transform.m[15] + transform.m[13];
  6095. frustumPlane.normalize();
  6096. };
  6097. /**
  6098. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6099. */
  6100. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6101. // Near
  6102. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6103. // Far
  6104. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6105. // Left
  6106. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6107. // Right
  6108. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6109. // Top
  6110. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6111. // Bottom
  6112. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6113. };
  6114. return Frustum;
  6115. }());
  6116. BABYLON.Frustum = Frustum;
  6117. var Space;
  6118. (function (Space) {
  6119. Space[Space["LOCAL"] = 0] = "LOCAL";
  6120. Space[Space["WORLD"] = 1] = "WORLD";
  6121. Space[Space["BONE"] = 2] = "BONE";
  6122. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6123. var Axis = /** @class */ (function () {
  6124. function Axis() {
  6125. }
  6126. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6127. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6128. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6129. return Axis;
  6130. }());
  6131. BABYLON.Axis = Axis;
  6132. ;
  6133. var BezierCurve = /** @class */ (function () {
  6134. function BezierCurve() {
  6135. }
  6136. /**
  6137. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6138. */
  6139. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6140. // Extract X (which is equal to time here)
  6141. var f0 = 1 - 3 * x2 + 3 * x1;
  6142. var f1 = 3 * x2 - 6 * x1;
  6143. var f2 = 3 * x1;
  6144. var refinedT = t;
  6145. for (var i = 0; i < 5; i++) {
  6146. var refinedT2 = refinedT * refinedT;
  6147. var refinedT3 = refinedT2 * refinedT;
  6148. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6149. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6150. refinedT -= (x - t) * slope;
  6151. refinedT = Math.min(1, Math.max(0, refinedT));
  6152. }
  6153. // Resolve cubic bezier for the given x
  6154. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6155. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6156. Math.pow(refinedT, 3);
  6157. };
  6158. return BezierCurve;
  6159. }());
  6160. BABYLON.BezierCurve = BezierCurve;
  6161. var Orientation;
  6162. (function (Orientation) {
  6163. Orientation[Orientation["CW"] = 0] = "CW";
  6164. Orientation[Orientation["CCW"] = 1] = "CCW";
  6165. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6166. var Angle = /** @class */ (function () {
  6167. /**
  6168. * Creates an Angle object of "radians" radians (float).
  6169. */
  6170. function Angle(radians) {
  6171. var _this = this;
  6172. /**
  6173. * Returns the Angle value in degrees (float).
  6174. */
  6175. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6176. /**
  6177. * Returns the Angle value in radians (float).
  6178. */
  6179. this.radians = function () { return _this._radians; };
  6180. this._radians = radians;
  6181. if (this._radians < 0.0)
  6182. this._radians += (2.0 * Math.PI);
  6183. }
  6184. /**
  6185. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6186. */
  6187. Angle.BetweenTwoPoints = function (a, b) {
  6188. var delta = b.subtract(a);
  6189. var theta = Math.atan2(delta.y, delta.x);
  6190. return new Angle(theta);
  6191. };
  6192. /**
  6193. * Returns a new Angle object from the passed float in radians.
  6194. */
  6195. Angle.FromRadians = function (radians) {
  6196. return new Angle(radians);
  6197. };
  6198. /**
  6199. * Returns a new Angle object from the passed float in degrees.
  6200. */
  6201. Angle.FromDegrees = function (degrees) {
  6202. return new Angle(degrees * Math.PI / 180.0);
  6203. };
  6204. return Angle;
  6205. }());
  6206. BABYLON.Angle = Angle;
  6207. var Arc2 = /** @class */ (function () {
  6208. /**
  6209. * Creates an Arc object from the three passed points : start, middle and end.
  6210. */
  6211. function Arc2(startPoint, midPoint, endPoint) {
  6212. this.startPoint = startPoint;
  6213. this.midPoint = midPoint;
  6214. this.endPoint = endPoint;
  6215. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6216. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6217. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6218. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6219. 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);
  6220. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6221. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6222. var a1 = this.startAngle.degrees();
  6223. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6224. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6225. // angles correction
  6226. if (a2 - a1 > +180.0)
  6227. a2 -= 360.0;
  6228. if (a2 - a1 < -180.0)
  6229. a2 += 360.0;
  6230. if (a3 - a2 > +180.0)
  6231. a3 -= 360.0;
  6232. if (a3 - a2 < -180.0)
  6233. a3 += 360.0;
  6234. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6235. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6236. }
  6237. return Arc2;
  6238. }());
  6239. BABYLON.Arc2 = Arc2;
  6240. var Path2 = /** @class */ (function () {
  6241. /**
  6242. * Creates a Path2 object from the starting 2D coordinates x and y.
  6243. */
  6244. function Path2(x, y) {
  6245. this._points = new Array();
  6246. this._length = 0.0;
  6247. this.closed = false;
  6248. this._points.push(new Vector2(x, y));
  6249. }
  6250. /**
  6251. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6252. * Returns the updated Path2.
  6253. */
  6254. Path2.prototype.addLineTo = function (x, y) {
  6255. if (this.closed) {
  6256. return this;
  6257. }
  6258. var newPoint = new Vector2(x, y);
  6259. var previousPoint = this._points[this._points.length - 1];
  6260. this._points.push(newPoint);
  6261. this._length += newPoint.subtract(previousPoint).length();
  6262. return this;
  6263. };
  6264. /**
  6265. * 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.
  6266. * Returns the updated Path2.
  6267. */
  6268. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6269. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6270. if (this.closed) {
  6271. return this;
  6272. }
  6273. var startPoint = this._points[this._points.length - 1];
  6274. var midPoint = new Vector2(midX, midY);
  6275. var endPoint = new Vector2(endX, endY);
  6276. var arc = new Arc2(startPoint, midPoint, endPoint);
  6277. var increment = arc.angle.radians() / numberOfSegments;
  6278. if (arc.orientation === Orientation.CW)
  6279. increment *= -1;
  6280. var currentAngle = arc.startAngle.radians() + increment;
  6281. for (var i = 0; i < numberOfSegments; i++) {
  6282. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6283. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6284. this.addLineTo(x, y);
  6285. currentAngle += increment;
  6286. }
  6287. return this;
  6288. };
  6289. /**
  6290. * Closes the Path2.
  6291. * Returns the Path2.
  6292. */
  6293. Path2.prototype.close = function () {
  6294. this.closed = true;
  6295. return this;
  6296. };
  6297. /**
  6298. * Returns the Path2 total length (float).
  6299. */
  6300. Path2.prototype.length = function () {
  6301. var result = this._length;
  6302. if (!this.closed) {
  6303. var lastPoint = this._points[this._points.length - 1];
  6304. var firstPoint = this._points[0];
  6305. result += (firstPoint.subtract(lastPoint).length());
  6306. }
  6307. return result;
  6308. };
  6309. /**
  6310. * Returns the Path2 internal array of points.
  6311. */
  6312. Path2.prototype.getPoints = function () {
  6313. return this._points;
  6314. };
  6315. /**
  6316. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6317. */
  6318. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6319. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6320. return Vector2.Zero();
  6321. }
  6322. var lengthPosition = normalizedLengthPosition * this.length();
  6323. var previousOffset = 0;
  6324. for (var i = 0; i < this._points.length; i++) {
  6325. var j = (i + 1) % this._points.length;
  6326. var a = this._points[i];
  6327. var b = this._points[j];
  6328. var bToA = b.subtract(a);
  6329. var nextOffset = (bToA.length() + previousOffset);
  6330. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6331. var dir = bToA.normalize();
  6332. var localOffset = lengthPosition - previousOffset;
  6333. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6334. }
  6335. previousOffset = nextOffset;
  6336. }
  6337. return Vector2.Zero();
  6338. };
  6339. /**
  6340. * Returns a new Path2 starting at the coordinates (x, y).
  6341. */
  6342. Path2.StartingAt = function (x, y) {
  6343. return new Path2(x, y);
  6344. };
  6345. return Path2;
  6346. }());
  6347. BABYLON.Path2 = Path2;
  6348. var Path3D = /** @class */ (function () {
  6349. /**
  6350. * new Path3D(path, normal, raw)
  6351. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6352. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6353. * path : an array of Vector3, the curve axis of the Path3D
  6354. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6355. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6356. */
  6357. function Path3D(path, firstNormal, raw) {
  6358. if (firstNormal === void 0) { firstNormal = null; }
  6359. this.path = path;
  6360. this._curve = new Array();
  6361. this._distances = new Array();
  6362. this._tangents = new Array();
  6363. this._normals = new Array();
  6364. this._binormals = new Array();
  6365. for (var p = 0; p < path.length; p++) {
  6366. this._curve[p] = path[p].clone(); // hard copy
  6367. }
  6368. this._raw = raw || false;
  6369. this._compute(firstNormal);
  6370. }
  6371. /**
  6372. * Returns the Path3D array of successive Vector3 designing its curve.
  6373. */
  6374. Path3D.prototype.getCurve = function () {
  6375. return this._curve;
  6376. };
  6377. /**
  6378. * Returns an array populated with tangent vectors on each Path3D curve point.
  6379. */
  6380. Path3D.prototype.getTangents = function () {
  6381. return this._tangents;
  6382. };
  6383. /**
  6384. * Returns an array populated with normal vectors on each Path3D curve point.
  6385. */
  6386. Path3D.prototype.getNormals = function () {
  6387. return this._normals;
  6388. };
  6389. /**
  6390. * Returns an array populated with binormal vectors on each Path3D curve point.
  6391. */
  6392. Path3D.prototype.getBinormals = function () {
  6393. return this._binormals;
  6394. };
  6395. /**
  6396. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6397. */
  6398. Path3D.prototype.getDistances = function () {
  6399. return this._distances;
  6400. };
  6401. /**
  6402. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6403. * Returns the same object updated.
  6404. */
  6405. Path3D.prototype.update = function (path, firstNormal) {
  6406. if (firstNormal === void 0) { firstNormal = null; }
  6407. for (var p = 0; p < path.length; p++) {
  6408. this._curve[p].x = path[p].x;
  6409. this._curve[p].y = path[p].y;
  6410. this._curve[p].z = path[p].z;
  6411. }
  6412. this._compute(firstNormal);
  6413. return this;
  6414. };
  6415. // private function compute() : computes tangents, normals and binormals
  6416. Path3D.prototype._compute = function (firstNormal) {
  6417. var l = this._curve.length;
  6418. // first and last tangents
  6419. this._tangents[0] = this._getFirstNonNullVector(0);
  6420. if (!this._raw) {
  6421. this._tangents[0].normalize();
  6422. }
  6423. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6424. if (!this._raw) {
  6425. this._tangents[l - 1].normalize();
  6426. }
  6427. // normals and binormals at first point : arbitrary vector with _normalVector()
  6428. var tg0 = this._tangents[0];
  6429. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6430. this._normals[0] = pp0;
  6431. if (!this._raw) {
  6432. this._normals[0].normalize();
  6433. }
  6434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6435. if (!this._raw) {
  6436. this._binormals[0].normalize();
  6437. }
  6438. this._distances[0] = 0.0;
  6439. // normals and binormals : next points
  6440. var prev; // previous vector (segment)
  6441. var cur; // current vector (segment)
  6442. var curTang; // current tangent
  6443. // previous normal
  6444. var prevBinor; // previous binormal
  6445. for (var i = 1; i < l; i++) {
  6446. // tangents
  6447. prev = this._getLastNonNullVector(i);
  6448. if (i < l - 1) {
  6449. cur = this._getFirstNonNullVector(i);
  6450. this._tangents[i] = prev.add(cur);
  6451. this._tangents[i].normalize();
  6452. }
  6453. this._distances[i] = this._distances[i - 1] + prev.length();
  6454. // normals and binormals
  6455. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6456. curTang = this._tangents[i];
  6457. prevBinor = this._binormals[i - 1];
  6458. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6459. if (!this._raw) {
  6460. this._normals[i].normalize();
  6461. }
  6462. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6463. if (!this._raw) {
  6464. this._binormals[i].normalize();
  6465. }
  6466. }
  6467. };
  6468. // private function getFirstNonNullVector(index)
  6469. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6470. Path3D.prototype._getFirstNonNullVector = function (index) {
  6471. var i = 1;
  6472. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6473. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6474. i++;
  6475. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6476. }
  6477. return nNVector;
  6478. };
  6479. // private function getLastNonNullVector(index)
  6480. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6481. Path3D.prototype._getLastNonNullVector = function (index) {
  6482. var i = 1;
  6483. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6484. while (nLVector.length() === 0 && index > i + 1) {
  6485. i++;
  6486. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6487. }
  6488. return nLVector;
  6489. };
  6490. // private function normalVector(v0, vt, va) :
  6491. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6492. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6493. Path3D.prototype._normalVector = function (v0, vt, va) {
  6494. var normal0;
  6495. var tgl = vt.length();
  6496. if (tgl === 0.0) {
  6497. tgl = 1.0;
  6498. }
  6499. if (va === undefined || va === null) {
  6500. var point;
  6501. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6502. point = new Vector3(0.0, -1.0, 0.0);
  6503. }
  6504. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6505. point = new Vector3(1.0, 0.0, 0.0);
  6506. }
  6507. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6508. point = new Vector3(0.0, 0.0, 1.0);
  6509. }
  6510. else {
  6511. point = Vector3.Zero();
  6512. }
  6513. normal0 = Vector3.Cross(vt, point);
  6514. }
  6515. else {
  6516. normal0 = Vector3.Cross(vt, va);
  6517. Vector3.CrossToRef(normal0, vt, normal0);
  6518. }
  6519. normal0.normalize();
  6520. return normal0;
  6521. };
  6522. return Path3D;
  6523. }());
  6524. BABYLON.Path3D = Path3D;
  6525. var Curve3 = /** @class */ (function () {
  6526. /**
  6527. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6528. * A Curve3 is designed from a series of successive Vector3.
  6529. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6530. */
  6531. function Curve3(points) {
  6532. this._length = 0.0;
  6533. this._points = points;
  6534. this._length = this._computeLength(points);
  6535. }
  6536. /**
  6537. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6538. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6539. * @param v1 (Vector3) the control point
  6540. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6541. * @param nbPoints (integer) the wanted number of points in the curve
  6542. */
  6543. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6544. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6545. var bez = new Array();
  6546. var equation = function (t, val0, val1, val2) {
  6547. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6548. return res;
  6549. };
  6550. for (var i = 0; i <= nbPoints; i++) {
  6551. 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)));
  6552. }
  6553. return new Curve3(bez);
  6554. };
  6555. /**
  6556. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6557. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6558. * @param v1 (Vector3) the first control point
  6559. * @param v2 (Vector3) the second control point
  6560. * @param v3 (Vector3) the end point of the Cubic Bezier
  6561. * @param nbPoints (integer) the wanted number of points in the curve
  6562. */
  6563. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6564. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6565. var bez = new Array();
  6566. var equation = function (t, val0, val1, val2, val3) {
  6567. 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;
  6568. return res;
  6569. };
  6570. for (var i = 0; i <= nbPoints; i++) {
  6571. 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)));
  6572. }
  6573. return new Curve3(bez);
  6574. };
  6575. /**
  6576. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6577. * @param p1 (Vector3) the origin point of the Hermite Spline
  6578. * @param t1 (Vector3) the tangent vector at the origin point
  6579. * @param p2 (Vector3) the end point of the Hermite Spline
  6580. * @param t2 (Vector3) the tangent vector at the end point
  6581. * @param nbPoints (integer) the wanted number of points in the curve
  6582. */
  6583. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6584. var hermite = new Array();
  6585. var step = 1.0 / nbPoints;
  6586. for (var i = 0; i <= nbPoints; i++) {
  6587. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6588. }
  6589. return new Curve3(hermite);
  6590. };
  6591. /**
  6592. * Returns a Curve3 object along a CatmullRom Spline curve :
  6593. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6594. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6595. */
  6596. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6597. var totalPoints = new Array();
  6598. totalPoints.push(points[0].clone());
  6599. Array.prototype.push.apply(totalPoints, points);
  6600. totalPoints.push(points[points.length - 1].clone());
  6601. var catmullRom = new Array();
  6602. var step = 1.0 / nbPoints;
  6603. var amount = 0.0;
  6604. for (var i = 0; i < totalPoints.length - 3; i++) {
  6605. amount = 0;
  6606. for (var c = 0; c < nbPoints; c++) {
  6607. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6608. amount += step;
  6609. }
  6610. }
  6611. i--;
  6612. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6613. return new Curve3(catmullRom);
  6614. };
  6615. /**
  6616. * Returns the Curve3 stored array of successive Vector3
  6617. */
  6618. Curve3.prototype.getPoints = function () {
  6619. return this._points;
  6620. };
  6621. /**
  6622. * Returns the computed length (float) of the curve.
  6623. */
  6624. Curve3.prototype.length = function () {
  6625. return this._length;
  6626. };
  6627. /**
  6628. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6629. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6630. * curveA and curveB keep unchanged.
  6631. */
  6632. Curve3.prototype.continue = function (curve) {
  6633. var lastPoint = this._points[this._points.length - 1];
  6634. var continuedPoints = this._points.slice();
  6635. var curvePoints = curve.getPoints();
  6636. for (var i = 1; i < curvePoints.length; i++) {
  6637. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6638. }
  6639. var continuedCurve = new Curve3(continuedPoints);
  6640. return continuedCurve;
  6641. };
  6642. Curve3.prototype._computeLength = function (path) {
  6643. var l = 0;
  6644. for (var i = 1; i < path.length; i++) {
  6645. l += (path[i].subtract(path[i - 1])).length();
  6646. }
  6647. return l;
  6648. };
  6649. return Curve3;
  6650. }());
  6651. BABYLON.Curve3 = Curve3;
  6652. // Vertex formats
  6653. var PositionNormalVertex = /** @class */ (function () {
  6654. function PositionNormalVertex(position, normal) {
  6655. if (position === void 0) { position = Vector3.Zero(); }
  6656. if (normal === void 0) { normal = Vector3.Up(); }
  6657. this.position = position;
  6658. this.normal = normal;
  6659. }
  6660. PositionNormalVertex.prototype.clone = function () {
  6661. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6662. };
  6663. return PositionNormalVertex;
  6664. }());
  6665. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6666. var PositionNormalTextureVertex = /** @class */ (function () {
  6667. function PositionNormalTextureVertex(position, normal, uv) {
  6668. if (position === void 0) { position = Vector3.Zero(); }
  6669. if (normal === void 0) { normal = Vector3.Up(); }
  6670. if (uv === void 0) { uv = Vector2.Zero(); }
  6671. this.position = position;
  6672. this.normal = normal;
  6673. this.uv = uv;
  6674. }
  6675. PositionNormalTextureVertex.prototype.clone = function () {
  6676. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6677. };
  6678. return PositionNormalTextureVertex;
  6679. }());
  6680. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6681. // Temporary pre-allocated objects for engine internal use
  6682. // usage in any internal function :
  6683. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6684. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6685. var Tmp = /** @class */ (function () {
  6686. function Tmp() {
  6687. }
  6688. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6689. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6690. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6691. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6692. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6693. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6694. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6695. Matrix.Zero(), Matrix.Zero(),
  6696. Matrix.Zero(), Matrix.Zero(),
  6697. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6698. return Tmp;
  6699. }());
  6700. BABYLON.Tmp = Tmp;
  6701. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6702. var MathTmp = /** @class */ (function () {
  6703. function MathTmp() {
  6704. }
  6705. MathTmp.Vector3 = [Vector3.Zero()];
  6706. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6707. MathTmp.Quaternion = [Quaternion.Zero()];
  6708. return MathTmp;
  6709. }());
  6710. })(BABYLON || (BABYLON = {}));
  6711. //# sourceMappingURL=babylon.math.js.map
  6712. var BABYLON;
  6713. (function (BABYLON) {
  6714. var Scalar = /** @class */ (function () {
  6715. function Scalar() {
  6716. }
  6717. /**
  6718. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6719. */
  6720. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6721. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6722. var num = a - b;
  6723. return -epsilon <= num && num <= epsilon;
  6724. };
  6725. /**
  6726. * Returns a string : the upper case translation of the number i to hexadecimal.
  6727. */
  6728. Scalar.ToHex = function (i) {
  6729. var str = i.toString(16);
  6730. if (i <= 15) {
  6731. return ("0" + str).toUpperCase();
  6732. }
  6733. return str.toUpperCase();
  6734. };
  6735. /**
  6736. * Returns -1 if value is negative and +1 is value is positive.
  6737. * Returns the value itself if it's equal to zero.
  6738. */
  6739. Scalar.Sign = function (value) {
  6740. value = +value; // convert to a number
  6741. if (value === 0 || isNaN(value))
  6742. return value;
  6743. return value > 0 ? 1 : -1;
  6744. };
  6745. /**
  6746. * Returns the value itself if it's between min and max.
  6747. * Returns min if the value is lower than min.
  6748. * Returns max if the value is greater than max.
  6749. */
  6750. Scalar.Clamp = function (value, min, max) {
  6751. if (min === void 0) { min = 0; }
  6752. if (max === void 0) { max = 1; }
  6753. return Math.min(max, Math.max(min, value));
  6754. };
  6755. /**
  6756. * Returns the log2 of value.
  6757. */
  6758. Scalar.Log2 = function (value) {
  6759. return Math.log(value) * Math.LOG2E;
  6760. };
  6761. /**
  6762. * Loops the value, so that it is never larger than length and never smaller than 0.
  6763. *
  6764. * This is similar to the modulo operator but it works with floating point numbers.
  6765. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6766. * With t = 5 and length = 2.5, the result would be 0.0.
  6767. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6768. */
  6769. Scalar.Repeat = function (value, length) {
  6770. return value - Math.floor(value / length) * length;
  6771. };
  6772. /**
  6773. * Normalize the value between 0.0 and 1.0 using min and max values
  6774. */
  6775. Scalar.Normalize = function (value, min, max) {
  6776. return (value - min) / (max - min);
  6777. };
  6778. /**
  6779. * Denormalize the value from 0.0 and 1.0 using min and max values
  6780. */
  6781. Scalar.Denormalize = function (normalized, min, max) {
  6782. return (normalized * (max - min) + min);
  6783. };
  6784. /**
  6785. * Calculates the shortest difference between two given angles given in degrees.
  6786. */
  6787. Scalar.DeltaAngle = function (current, target) {
  6788. var num = Scalar.Repeat(target - current, 360.0);
  6789. if (num > 180.0) {
  6790. num -= 360.0;
  6791. }
  6792. return num;
  6793. };
  6794. /**
  6795. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6796. *
  6797. * The returned value will move back and forth between 0 and length
  6798. */
  6799. Scalar.PingPong = function (tx, length) {
  6800. var t = Scalar.Repeat(tx, length * 2.0);
  6801. return length - Math.abs(t - length);
  6802. };
  6803. /**
  6804. * Interpolates between min and max with smoothing at the limits.
  6805. *
  6806. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6807. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6808. */
  6809. Scalar.SmoothStep = function (from, to, tx) {
  6810. var t = Scalar.Clamp(tx);
  6811. t = -2.0 * t * t * t + 3.0 * t * t;
  6812. return to * t + from * (1.0 - t);
  6813. };
  6814. /**
  6815. * Moves a value current towards target.
  6816. *
  6817. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6818. * Negative values of maxDelta pushes the value away from target.
  6819. */
  6820. Scalar.MoveTowards = function (current, target, maxDelta) {
  6821. var result = 0;
  6822. if (Math.abs(target - current) <= maxDelta) {
  6823. result = target;
  6824. }
  6825. else {
  6826. result = current + Scalar.Sign(target - current) * maxDelta;
  6827. }
  6828. return result;
  6829. };
  6830. /**
  6831. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6832. *
  6833. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6834. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6835. */
  6836. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6837. var num = Scalar.DeltaAngle(current, target);
  6838. var result = 0;
  6839. if (-maxDelta < num && num < maxDelta) {
  6840. result = target;
  6841. }
  6842. else {
  6843. target = current + num;
  6844. result = Scalar.MoveTowards(current, target, maxDelta);
  6845. }
  6846. return result;
  6847. };
  6848. /**
  6849. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6850. */
  6851. Scalar.Lerp = function (start, end, amount) {
  6852. return start + ((end - start) * amount);
  6853. };
  6854. /**
  6855. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6856. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6857. */
  6858. Scalar.LerpAngle = function (start, end, amount) {
  6859. var num = Scalar.Repeat(end - start, 360.0);
  6860. if (num > 180.0) {
  6861. num -= 360.0;
  6862. }
  6863. return start + num * Scalar.Clamp(amount);
  6864. };
  6865. /**
  6866. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6867. */
  6868. Scalar.InverseLerp = function (a, b, value) {
  6869. var result = 0;
  6870. if (a != b) {
  6871. result = Scalar.Clamp((value - a) / (b - a));
  6872. }
  6873. else {
  6874. result = 0.0;
  6875. }
  6876. return result;
  6877. };
  6878. /**
  6879. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6880. */
  6881. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6882. var squared = amount * amount;
  6883. var cubed = amount * squared;
  6884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6886. var part3 = (cubed - (2.0 * squared)) + amount;
  6887. var part4 = cubed - squared;
  6888. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6889. };
  6890. /**
  6891. * Returns a random float number between and min and max values
  6892. */
  6893. Scalar.RandomRange = function (min, max) {
  6894. if (min === max)
  6895. return min;
  6896. return ((Math.random() * (max - min)) + min);
  6897. };
  6898. /**
  6899. * This function returns percentage of a number in a given range.
  6900. *
  6901. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6902. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6903. */
  6904. Scalar.RangeToPercent = function (number, min, max) {
  6905. return ((number - min) / (max - min));
  6906. };
  6907. /**
  6908. * This function returns number that corresponds to the percentage in a given range.
  6909. *
  6910. * PercentToRange(0.34,0,100) will return 34.
  6911. */
  6912. Scalar.PercentToRange = function (percent, min, max) {
  6913. return ((max - min) * percent + min);
  6914. };
  6915. /**
  6916. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6917. * @param angle The angle to normalize in radian.
  6918. * @return The converted angle.
  6919. */
  6920. Scalar.NormalizeRadians = function (angle) {
  6921. // More precise but slower version kept for reference.
  6922. // angle = angle % Tools.TwoPi;
  6923. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6924. //if (angle > Math.PI) {
  6925. // angle -= Tools.TwoPi;
  6926. //}
  6927. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6928. return angle;
  6929. };
  6930. /**
  6931. * Two pi constants convenient for computation.
  6932. */
  6933. Scalar.TwoPi = Math.PI * 2;
  6934. return Scalar;
  6935. }());
  6936. BABYLON.Scalar = Scalar;
  6937. })(BABYLON || (BABYLON = {}));
  6938. //# sourceMappingURL=babylon.math.scalar.js.map
  6939. //# sourceMappingURL=babylon.mixins.js.map
  6940. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6941. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6942. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6943. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6944. //# sourceMappingURL=babylon.webgl2.js.map
  6945. var BABYLON;
  6946. (function (BABYLON) {
  6947. var __decoratorInitialStore = {};
  6948. var __mergedStore = {};
  6949. var _copySource = function (creationFunction, source, instanciate) {
  6950. var destination = creationFunction();
  6951. // Tags
  6952. if (BABYLON.Tags) {
  6953. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6954. }
  6955. var classStore = getMergedStore(destination);
  6956. // Properties
  6957. for (var property in classStore) {
  6958. var propertyDescriptor = classStore[property];
  6959. var sourceProperty = source[property];
  6960. var propertyType = propertyDescriptor.type;
  6961. if (sourceProperty !== undefined && sourceProperty !== null) {
  6962. switch (propertyType) {
  6963. case 0: // Value
  6964. case 6:// Mesh reference
  6965. destination[property] = sourceProperty;
  6966. break;
  6967. case 1:// Texture
  6968. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6969. break;
  6970. case 2: // Color3
  6971. case 3: // FresnelParameters
  6972. case 4: // Vector2
  6973. case 5: // Vector3
  6974. case 7: // Color Curves
  6975. case 10:// Quaternion
  6976. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6977. break;
  6978. }
  6979. }
  6980. }
  6981. return destination;
  6982. };
  6983. function getDirectStore(target) {
  6984. var classKey = target.getClassName();
  6985. if (!__decoratorInitialStore[classKey]) {
  6986. __decoratorInitialStore[classKey] = {};
  6987. }
  6988. return __decoratorInitialStore[classKey];
  6989. }
  6990. /**
  6991. * Return the list of properties flagged as serializable
  6992. * @param target: host object
  6993. */
  6994. function getMergedStore(target) {
  6995. var classKey = target.getClassName();
  6996. if (__mergedStore[classKey]) {
  6997. return __mergedStore[classKey];
  6998. }
  6999. __mergedStore[classKey] = {};
  7000. var store = __mergedStore[classKey];
  7001. var currentTarget = target;
  7002. var currentKey = classKey;
  7003. while (currentKey) {
  7004. var initialStore = __decoratorInitialStore[currentKey];
  7005. for (var property in initialStore) {
  7006. store[property] = initialStore[property];
  7007. }
  7008. var parent_1 = void 0;
  7009. var done = false;
  7010. do {
  7011. parent_1 = Object.getPrototypeOf(currentTarget);
  7012. if (!parent_1.getClassName) {
  7013. done = true;
  7014. break;
  7015. }
  7016. if (parent_1.getClassName() !== currentKey) {
  7017. break;
  7018. }
  7019. currentTarget = parent_1;
  7020. } while (parent_1);
  7021. if (done) {
  7022. break;
  7023. }
  7024. currentKey = parent_1.getClassName();
  7025. currentTarget = parent_1;
  7026. }
  7027. return store;
  7028. }
  7029. function generateSerializableMember(type, sourceName) {
  7030. return function (target, propertyKey) {
  7031. var classStore = getDirectStore(target);
  7032. if (!classStore[propertyKey]) {
  7033. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7034. }
  7035. };
  7036. }
  7037. function generateExpandMember(setCallback, targetKey) {
  7038. if (targetKey === void 0) { targetKey = null; }
  7039. return function (target, propertyKey) {
  7040. var key = targetKey || ("_" + propertyKey);
  7041. Object.defineProperty(target, propertyKey, {
  7042. get: function () {
  7043. return this[key];
  7044. },
  7045. set: function (value) {
  7046. if (this[key] === value) {
  7047. return;
  7048. }
  7049. this[key] = value;
  7050. target[setCallback].apply(this);
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. };
  7056. }
  7057. function expandToProperty(callback, targetKey) {
  7058. if (targetKey === void 0) { targetKey = null; }
  7059. return generateExpandMember(callback, targetKey);
  7060. }
  7061. BABYLON.expandToProperty = expandToProperty;
  7062. function serialize(sourceName) {
  7063. return generateSerializableMember(0, sourceName); // value member
  7064. }
  7065. BABYLON.serialize = serialize;
  7066. function serializeAsTexture(sourceName) {
  7067. return generateSerializableMember(1, sourceName); // texture member
  7068. }
  7069. BABYLON.serializeAsTexture = serializeAsTexture;
  7070. function serializeAsColor3(sourceName) {
  7071. return generateSerializableMember(2, sourceName); // color3 member
  7072. }
  7073. BABYLON.serializeAsColor3 = serializeAsColor3;
  7074. function serializeAsFresnelParameters(sourceName) {
  7075. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7076. }
  7077. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7078. function serializeAsVector2(sourceName) {
  7079. return generateSerializableMember(4, sourceName); // vector2 member
  7080. }
  7081. BABYLON.serializeAsVector2 = serializeAsVector2;
  7082. function serializeAsVector3(sourceName) {
  7083. return generateSerializableMember(5, sourceName); // vector3 member
  7084. }
  7085. BABYLON.serializeAsVector3 = serializeAsVector3;
  7086. function serializeAsMeshReference(sourceName) {
  7087. return generateSerializableMember(6, sourceName); // mesh reference member
  7088. }
  7089. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7090. function serializeAsColorCurves(sourceName) {
  7091. return generateSerializableMember(7, sourceName); // color curves
  7092. }
  7093. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7094. function serializeAsColor4(sourceName) {
  7095. return generateSerializableMember(8, sourceName); // color 4
  7096. }
  7097. BABYLON.serializeAsColor4 = serializeAsColor4;
  7098. function serializeAsImageProcessingConfiguration(sourceName) {
  7099. return generateSerializableMember(9, sourceName); // image processing
  7100. }
  7101. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7102. function serializeAsQuaternion(sourceName) {
  7103. return generateSerializableMember(10, sourceName); // quaternion member
  7104. }
  7105. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7106. var SerializationHelper = /** @class */ (function () {
  7107. function SerializationHelper() {
  7108. }
  7109. SerializationHelper.Serialize = function (entity, serializationObject) {
  7110. if (!serializationObject) {
  7111. serializationObject = {};
  7112. }
  7113. // Tags
  7114. if (BABYLON.Tags) {
  7115. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7116. }
  7117. var serializedProperties = getMergedStore(entity);
  7118. // Properties
  7119. for (var property in serializedProperties) {
  7120. var propertyDescriptor = serializedProperties[property];
  7121. var targetPropertyName = propertyDescriptor.sourceName || property;
  7122. var propertyType = propertyDescriptor.type;
  7123. var sourceProperty = entity[property];
  7124. if (sourceProperty !== undefined && sourceProperty !== null) {
  7125. switch (propertyType) {
  7126. case 0:// Value
  7127. serializationObject[targetPropertyName] = sourceProperty;
  7128. break;
  7129. case 1:// Texture
  7130. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7131. break;
  7132. case 2:// Color3
  7133. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7134. break;
  7135. case 3:// FresnelParameters
  7136. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7137. break;
  7138. case 4:// Vector2
  7139. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7140. break;
  7141. case 5:// Vector3
  7142. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7143. break;
  7144. case 6:// Mesh reference
  7145. serializationObject[targetPropertyName] = sourceProperty.id;
  7146. break;
  7147. case 7:// Color Curves
  7148. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7149. break;
  7150. case 8:// Color 4
  7151. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7152. break;
  7153. case 9:// Image Processing
  7154. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7155. break;
  7156. }
  7157. }
  7158. }
  7159. return serializationObject;
  7160. };
  7161. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7162. if (rootUrl === void 0) { rootUrl = null; }
  7163. var destination = creationFunction();
  7164. if (!rootUrl) {
  7165. rootUrl = "";
  7166. }
  7167. // Tags
  7168. if (BABYLON.Tags) {
  7169. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7170. }
  7171. var classStore = getMergedStore(destination);
  7172. // Properties
  7173. for (var property in classStore) {
  7174. var propertyDescriptor = classStore[property];
  7175. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7176. var propertyType = propertyDescriptor.type;
  7177. if (sourceProperty !== undefined && sourceProperty !== null) {
  7178. var dest = destination;
  7179. switch (propertyType) {
  7180. case 0:// Value
  7181. dest[property] = sourceProperty;
  7182. break;
  7183. case 1:// Texture
  7184. if (scene) {
  7185. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7186. }
  7187. break;
  7188. case 2:// Color3
  7189. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7190. break;
  7191. case 3:// FresnelParameters
  7192. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7193. break;
  7194. case 4:// Vector2
  7195. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7196. break;
  7197. case 5:// Vector3
  7198. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7199. break;
  7200. case 6:// Mesh reference
  7201. if (scene) {
  7202. dest[property] = scene.getLastMeshByID(sourceProperty);
  7203. }
  7204. break;
  7205. case 7:// Color Curves
  7206. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7207. break;
  7208. case 8:// Color 4
  7209. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7210. break;
  7211. case 9:// Image Processing
  7212. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7213. break;
  7214. }
  7215. }
  7216. }
  7217. return destination;
  7218. };
  7219. SerializationHelper.Clone = function (creationFunction, source) {
  7220. return _copySource(creationFunction, source, false);
  7221. };
  7222. SerializationHelper.Instanciate = function (creationFunction, source) {
  7223. return _copySource(creationFunction, source, true);
  7224. };
  7225. return SerializationHelper;
  7226. }());
  7227. BABYLON.SerializationHelper = SerializationHelper;
  7228. })(BABYLON || (BABYLON = {}));
  7229. //# sourceMappingURL=babylon.decorators.js.map
  7230. var BABYLON;
  7231. (function (BABYLON) {
  7232. /**
  7233. * Wrapper class for promise with external resolve and reject.
  7234. */
  7235. var Deferred = /** @class */ (function () {
  7236. /**
  7237. * Constructor for this deferred object.
  7238. */
  7239. function Deferred() {
  7240. var _this = this;
  7241. this.promise = new Promise(function (resolve, reject) {
  7242. _this._resolve = resolve;
  7243. _this._reject = reject;
  7244. });
  7245. }
  7246. Object.defineProperty(Deferred.prototype, "resolve", {
  7247. /**
  7248. * The resolve method of the promise associated with this deferred object.
  7249. */
  7250. get: function () {
  7251. return this._resolve;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(Deferred.prototype, "reject", {
  7257. /**
  7258. * The reject method of the promise associated with this deferred object.
  7259. */
  7260. get: function () {
  7261. return this._reject;
  7262. },
  7263. enumerable: true,
  7264. configurable: true
  7265. });
  7266. return Deferred;
  7267. }());
  7268. BABYLON.Deferred = Deferred;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.deferred.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. /**
  7274. * A class serves as a medium between the observable and its observers
  7275. */
  7276. var EventState = /** @class */ (function () {
  7277. /**
  7278. * Create a new EventState
  7279. * @param mask defines the mask associated with this state
  7280. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7281. * @param target defines the original target of the state
  7282. * @param currentTarget defines the current target of the state
  7283. */
  7284. function EventState(mask, skipNextObservers, target, currentTarget) {
  7285. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7286. this.initalize(mask, skipNextObservers, target, currentTarget);
  7287. }
  7288. /**
  7289. * Initialize the current event state
  7290. * @param mask defines the mask associated with this state
  7291. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7292. * @param target defines the original target of the state
  7293. * @param currentTarget defines the current target of the state
  7294. * @returns the current event state
  7295. */
  7296. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7297. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7298. this.mask = mask;
  7299. this.skipNextObservers = skipNextObservers;
  7300. this.target = target;
  7301. this.currentTarget = currentTarget;
  7302. return this;
  7303. };
  7304. return EventState;
  7305. }());
  7306. BABYLON.EventState = EventState;
  7307. /**
  7308. * Represent an Observer registered to a given Observable object.
  7309. */
  7310. var Observer = /** @class */ (function () {
  7311. /**
  7312. * Creates a new observer
  7313. * @param callback defines the callback to call when the observer is notified
  7314. * @param mask defines the mask of the observer (used to filter notifications)
  7315. * @param scope defines the current scope used to restore the JS context
  7316. */
  7317. function Observer(
  7318. /**
  7319. * Defines the callback to call when the observer is notified
  7320. */
  7321. callback,
  7322. /**
  7323. * Defines the mask of the observer (used to filter notifications)
  7324. */
  7325. mask,
  7326. /**
  7327. * Defines the current scope used to restore the JS context
  7328. */
  7329. scope) {
  7330. if (scope === void 0) { scope = null; }
  7331. this.callback = callback;
  7332. this.mask = mask;
  7333. this.scope = scope;
  7334. /** @ignore */
  7335. this._willBeUnregistered = false;
  7336. /**
  7337. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7338. */
  7339. this.unregisterOnNextCall = false;
  7340. }
  7341. return Observer;
  7342. }());
  7343. BABYLON.Observer = Observer;
  7344. /**
  7345. * Represent a list of observers registered to multiple Observables object.
  7346. */
  7347. var MultiObserver = /** @class */ (function () {
  7348. function MultiObserver() {
  7349. }
  7350. /**
  7351. * Release associated resources
  7352. */
  7353. MultiObserver.prototype.dispose = function () {
  7354. if (this._observers && this._observables) {
  7355. for (var index = 0; index < this._observers.length; index++) {
  7356. this._observables[index].remove(this._observers[index]);
  7357. }
  7358. }
  7359. this._observers = null;
  7360. this._observables = null;
  7361. };
  7362. /**
  7363. * Raise a callback when one of the observable will notify
  7364. * @param observables defines a list of observables to watch
  7365. * @param callback defines the callback to call on notification
  7366. * @param mask defines the mask used to filter notifications
  7367. * @param scope defines the current scope used to restore the JS context
  7368. * @returns the new MultiObserver
  7369. */
  7370. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7371. if (mask === void 0) { mask = -1; }
  7372. if (scope === void 0) { scope = null; }
  7373. var result = new MultiObserver();
  7374. result._observers = new Array();
  7375. result._observables = observables;
  7376. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7377. var observable = observables_1[_i];
  7378. var observer = observable.add(callback, mask, false, scope);
  7379. if (observer) {
  7380. result._observers.push(observer);
  7381. }
  7382. }
  7383. return result;
  7384. };
  7385. return MultiObserver;
  7386. }());
  7387. BABYLON.MultiObserver = MultiObserver;
  7388. /**
  7389. * The Observable class is a simple implementation of the Observable pattern.
  7390. * 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.
  7391. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7392. * 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).
  7393. * 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.
  7394. */
  7395. var Observable = /** @class */ (function () {
  7396. /**
  7397. * Creates a new observable
  7398. * @param onObserverAdded defines a callback to call when a new observer is added
  7399. */
  7400. function Observable(onObserverAdded) {
  7401. this._observers = new Array();
  7402. this._eventState = new EventState(0);
  7403. if (onObserverAdded) {
  7404. this._onObserverAdded = onObserverAdded;
  7405. }
  7406. }
  7407. /**
  7408. * Create a new Observer with the specified callback
  7409. * @param callback the callback that will be executed for that Observer
  7410. * @param mask the mask used to filter observers
  7411. * @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.
  7412. * @param scope optional scope for the callback to be called from
  7413. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7414. * @returns the new observer created for the callback
  7415. */
  7416. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7417. if (mask === void 0) { mask = -1; }
  7418. if (insertFirst === void 0) { insertFirst = false; }
  7419. if (scope === void 0) { scope = null; }
  7420. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7421. if (!callback) {
  7422. return null;
  7423. }
  7424. var observer = new Observer(callback, mask, scope);
  7425. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7426. if (insertFirst) {
  7427. this._observers.unshift(observer);
  7428. }
  7429. else {
  7430. this._observers.push(observer);
  7431. }
  7432. if (this._onObserverAdded) {
  7433. this._onObserverAdded(observer);
  7434. }
  7435. return observer;
  7436. };
  7437. /**
  7438. * Remove an Observer from the Observable object
  7439. * @param observer the instance of the Observer to remove
  7440. * @returns false if it doesn't belong to this Observable
  7441. */
  7442. Observable.prototype.remove = function (observer) {
  7443. if (!observer) {
  7444. return false;
  7445. }
  7446. var index = this._observers.indexOf(observer);
  7447. if (index !== -1) {
  7448. this._observers.splice(index, 1);
  7449. return true;
  7450. }
  7451. return false;
  7452. };
  7453. /**
  7454. * Remove a callback from the Observable object
  7455. * @param callback the callback to remove
  7456. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7457. * @returns false if it doesn't belong to this Observable
  7458. */
  7459. Observable.prototype.removeCallback = function (callback, scope) {
  7460. for (var index = 0; index < this._observers.length; index++) {
  7461. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7462. this._observers.splice(index, 1);
  7463. return true;
  7464. }
  7465. }
  7466. return false;
  7467. };
  7468. Observable.prototype._deferUnregister = function (observer) {
  7469. var _this = this;
  7470. observer.unregisterOnNextCall = false;
  7471. observer._willBeUnregistered = true;
  7472. BABYLON.Tools.SetImmediate(function () {
  7473. _this.remove(observer);
  7474. });
  7475. };
  7476. /**
  7477. * Notify all Observers by calling their respective callback with the given data
  7478. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7479. * @param eventData defines the data to send to all observers
  7480. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7481. * @param target defines the original target of the state
  7482. * @param currentTarget defines the current target of the state
  7483. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7484. */
  7485. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7486. if (mask === void 0) { mask = -1; }
  7487. if (!this._observers.length) {
  7488. return true;
  7489. }
  7490. var state = this._eventState;
  7491. state.mask = mask;
  7492. state.target = target;
  7493. state.currentTarget = currentTarget;
  7494. state.skipNextObservers = false;
  7495. state.lastReturnValue = eventData;
  7496. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7497. var obs = _a[_i];
  7498. if (obs._willBeUnregistered) {
  7499. continue;
  7500. }
  7501. if (obs.mask & mask) {
  7502. if (obs.scope) {
  7503. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7504. }
  7505. else {
  7506. state.lastReturnValue = obs.callback(eventData, state);
  7507. }
  7508. if (obs.unregisterOnNextCall) {
  7509. this._deferUnregister(obs);
  7510. }
  7511. }
  7512. if (state.skipNextObservers) {
  7513. return false;
  7514. }
  7515. }
  7516. return true;
  7517. };
  7518. /**
  7519. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7520. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7521. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7522. * and it is crucial that all callbacks will be executed.
  7523. * The order of the callbacks is kept, callbacks are not executed parallel.
  7524. *
  7525. * @param eventData The data to be sent to each callback
  7526. * @param mask is used to filter observers defaults to -1
  7527. * @param target defines the callback target (see EventState)
  7528. * @param currentTarget defines he current object in the bubbling phase
  7529. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7530. */
  7531. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7532. var _this = this;
  7533. if (mask === void 0) { mask = -1; }
  7534. // create an empty promise
  7535. var p = Promise.resolve(eventData);
  7536. // no observers? return this promise.
  7537. if (!this._observers.length) {
  7538. return p;
  7539. }
  7540. var state = this._eventState;
  7541. state.mask = mask;
  7542. state.target = target;
  7543. state.currentTarget = currentTarget;
  7544. state.skipNextObservers = false;
  7545. // execute one callback after another (not using Promise.all, the order is important)
  7546. this._observers.forEach(function (obs) {
  7547. if (state.skipNextObservers) {
  7548. return;
  7549. }
  7550. if (obs._willBeUnregistered) {
  7551. return;
  7552. }
  7553. if (obs.mask & mask) {
  7554. if (obs.scope) {
  7555. p = p.then(function (lastReturnedValue) {
  7556. state.lastReturnValue = lastReturnedValue;
  7557. return obs.callback.apply(obs.scope, [eventData, state]);
  7558. });
  7559. }
  7560. else {
  7561. p = p.then(function (lastReturnedValue) {
  7562. state.lastReturnValue = lastReturnedValue;
  7563. return obs.callback(eventData, state);
  7564. });
  7565. }
  7566. if (obs.unregisterOnNextCall) {
  7567. _this._deferUnregister(obs);
  7568. }
  7569. }
  7570. });
  7571. // return the eventData
  7572. return p.then(function () { return eventData; });
  7573. };
  7574. /**
  7575. * Notify a specific observer
  7576. * @param observer defines the observer to notify
  7577. * @param eventData defines the data to be sent to each callback
  7578. * @param mask is used to filter observers defaults to -1
  7579. */
  7580. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7581. if (mask === void 0) { mask = -1; }
  7582. var state = this._eventState;
  7583. state.mask = mask;
  7584. state.skipNextObservers = false;
  7585. observer.callback(eventData, state);
  7586. };
  7587. /**
  7588. * Gets a boolean indicating if the observable has at least one observer
  7589. * @returns true is the Observable has at least one Observer registered
  7590. */
  7591. Observable.prototype.hasObservers = function () {
  7592. return this._observers.length > 0;
  7593. };
  7594. /**
  7595. * Clear the list of observers
  7596. */
  7597. Observable.prototype.clear = function () {
  7598. this._observers = new Array();
  7599. this._onObserverAdded = null;
  7600. };
  7601. /**
  7602. * Clone the current observable
  7603. * @returns a new observable
  7604. */
  7605. Observable.prototype.clone = function () {
  7606. var result = new Observable();
  7607. result._observers = this._observers.slice(0);
  7608. return result;
  7609. };
  7610. /**
  7611. * Does this observable handles observer registered with a given mask
  7612. * @param mask defines the mask to be tested
  7613. * @return whether or not one observer registered with the given mask is handeled
  7614. **/
  7615. Observable.prototype.hasSpecificMask = function (mask) {
  7616. if (mask === void 0) { mask = -1; }
  7617. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7618. var obs = _a[_i];
  7619. if (obs.mask & mask || obs.mask === mask) {
  7620. return true;
  7621. }
  7622. }
  7623. return false;
  7624. };
  7625. return Observable;
  7626. }());
  7627. BABYLON.Observable = Observable;
  7628. })(BABYLON || (BABYLON = {}));
  7629. //# sourceMappingURL=babylon.observable.js.map
  7630. var BABYLON;
  7631. (function (BABYLON) {
  7632. var SmartArray = /** @class */ (function () {
  7633. function SmartArray(capacity) {
  7634. this.length = 0;
  7635. this.data = new Array(capacity);
  7636. this._id = SmartArray._GlobalId++;
  7637. }
  7638. SmartArray.prototype.push = function (value) {
  7639. this.data[this.length++] = value;
  7640. if (this.length > this.data.length) {
  7641. this.data.length *= 2;
  7642. }
  7643. };
  7644. SmartArray.prototype.forEach = function (func) {
  7645. for (var index = 0; index < this.length; index++) {
  7646. func(this.data[index]);
  7647. }
  7648. };
  7649. SmartArray.prototype.sort = function (compareFn) {
  7650. this.data.sort(compareFn);
  7651. };
  7652. SmartArray.prototype.reset = function () {
  7653. this.length = 0;
  7654. };
  7655. SmartArray.prototype.dispose = function () {
  7656. this.reset();
  7657. if (this.data) {
  7658. this.data.length = 0;
  7659. this.data = [];
  7660. }
  7661. };
  7662. SmartArray.prototype.concat = function (array) {
  7663. if (array.length === 0) {
  7664. return;
  7665. }
  7666. if (this.length + array.length > this.data.length) {
  7667. this.data.length = (this.length + array.length) * 2;
  7668. }
  7669. for (var index = 0; index < array.length; index++) {
  7670. this.data[this.length++] = (array.data || array)[index];
  7671. }
  7672. };
  7673. SmartArray.prototype.indexOf = function (value) {
  7674. var position = this.data.indexOf(value);
  7675. if (position >= this.length) {
  7676. return -1;
  7677. }
  7678. return position;
  7679. };
  7680. SmartArray.prototype.contains = function (value) {
  7681. return this.data.indexOf(value) !== -1;
  7682. };
  7683. // Statics
  7684. SmartArray._GlobalId = 0;
  7685. return SmartArray;
  7686. }());
  7687. BABYLON.SmartArray = SmartArray;
  7688. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7689. __extends(SmartArrayNoDuplicate, _super);
  7690. function SmartArrayNoDuplicate() {
  7691. var _this = _super !== null && _super.apply(this, arguments) || this;
  7692. _this._duplicateId = 0;
  7693. return _this;
  7694. }
  7695. SmartArrayNoDuplicate.prototype.push = function (value) {
  7696. _super.prototype.push.call(this, value);
  7697. if (!value.__smartArrayFlags) {
  7698. value.__smartArrayFlags = {};
  7699. }
  7700. value.__smartArrayFlags[this._id] = this._duplicateId;
  7701. };
  7702. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7703. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7704. return false;
  7705. }
  7706. this.push(value);
  7707. return true;
  7708. };
  7709. SmartArrayNoDuplicate.prototype.reset = function () {
  7710. _super.prototype.reset.call(this);
  7711. this._duplicateId++;
  7712. };
  7713. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7714. if (array.length === 0) {
  7715. return;
  7716. }
  7717. if (this.length + array.length > this.data.length) {
  7718. this.data.length = (this.length + array.length) * 2;
  7719. }
  7720. for (var index = 0; index < array.length; index++) {
  7721. var item = (array.data || array)[index];
  7722. this.pushNoDuplicate(item);
  7723. }
  7724. };
  7725. return SmartArrayNoDuplicate;
  7726. }(SmartArray));
  7727. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.smartArray.js.map
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7733. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7734. var LoadFileError = /** @class */ (function (_super) {
  7735. __extends(LoadFileError, _super);
  7736. function LoadFileError(message, request) {
  7737. var _this = _super.call(this, message) || this;
  7738. _this.request = request;
  7739. _this.name = "LoadFileError";
  7740. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7741. return _this;
  7742. }
  7743. // Polyfill for Object.setPrototypeOf if necessary.
  7744. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7745. return LoadFileError;
  7746. }(Error));
  7747. BABYLON.LoadFileError = LoadFileError;
  7748. var RetryStrategy = /** @class */ (function () {
  7749. function RetryStrategy() {
  7750. }
  7751. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7752. if (maxRetries === void 0) { maxRetries = 3; }
  7753. if (baseInterval === void 0) { baseInterval = 500; }
  7754. return function (url, request, retryIndex) {
  7755. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7756. return -1;
  7757. }
  7758. return Math.pow(2, retryIndex) * baseInterval;
  7759. };
  7760. };
  7761. return RetryStrategy;
  7762. }());
  7763. BABYLON.RetryStrategy = RetryStrategy;
  7764. // Screenshots
  7765. var screenshotCanvas;
  7766. var cloneValue = function (source, destinationObject) {
  7767. if (!source)
  7768. return null;
  7769. if (source instanceof BABYLON.Mesh) {
  7770. return null;
  7771. }
  7772. if (source instanceof BABYLON.SubMesh) {
  7773. return source.clone(destinationObject);
  7774. }
  7775. else if (source.clone) {
  7776. return source.clone();
  7777. }
  7778. return null;
  7779. };
  7780. var Tools = /** @class */ (function () {
  7781. function Tools() {
  7782. }
  7783. /**
  7784. * Interpolates between a and b via alpha
  7785. * @param a The lower value (returned when alpha = 0)
  7786. * @param b The upper value (returned when alpha = 1)
  7787. * @param alpha The interpolation-factor
  7788. * @return The mixed value
  7789. */
  7790. Tools.Mix = function (a, b, alpha) {
  7791. return a * (1 - alpha) + b * alpha;
  7792. };
  7793. Tools.Instantiate = function (className) {
  7794. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7795. return Tools.RegisteredExternalClasses[className];
  7796. }
  7797. var arr = className.split(".");
  7798. var fn = (window || this);
  7799. for (var i = 0, len = arr.length; i < len; i++) {
  7800. fn = fn[arr[i]];
  7801. }
  7802. if (typeof fn !== "function") {
  7803. return null;
  7804. }
  7805. return fn;
  7806. };
  7807. /**
  7808. * Provides a slice function that will work even on IE
  7809. * @param data defines the array to slice
  7810. * @returns the new sliced array
  7811. */
  7812. Tools.Slice = function (data) {
  7813. if (data.slice) {
  7814. return data.slice();
  7815. }
  7816. return Array.prototype.slice.call(data);
  7817. };
  7818. Tools.SetImmediate = function (action) {
  7819. if (window.setImmediate) {
  7820. window.setImmediate(action);
  7821. }
  7822. else {
  7823. setTimeout(action, 1);
  7824. }
  7825. };
  7826. Tools.IsExponentOfTwo = function (value) {
  7827. var count = 1;
  7828. do {
  7829. count *= 2;
  7830. } while (count < value);
  7831. return count === value;
  7832. };
  7833. /**
  7834. * Find the next highest power of two.
  7835. * @param x Number to start search from.
  7836. * @return Next highest power of two.
  7837. */
  7838. Tools.CeilingPOT = function (x) {
  7839. x--;
  7840. x |= x >> 1;
  7841. x |= x >> 2;
  7842. x |= x >> 4;
  7843. x |= x >> 8;
  7844. x |= x >> 16;
  7845. x++;
  7846. return x;
  7847. };
  7848. /**
  7849. * Find the next lowest power of two.
  7850. * @param x Number to start search from.
  7851. * @return Next lowest power of two.
  7852. */
  7853. Tools.FloorPOT = function (x) {
  7854. x = x | (x >> 1);
  7855. x = x | (x >> 2);
  7856. x = x | (x >> 4);
  7857. x = x | (x >> 8);
  7858. x = x | (x >> 16);
  7859. return x - (x >> 1);
  7860. };
  7861. /**
  7862. * Find the nearest power of two.
  7863. * @param x Number to start search from.
  7864. * @return Next nearest power of two.
  7865. */
  7866. Tools.NearestPOT = function (x) {
  7867. var c = Tools.CeilingPOT(x);
  7868. var f = Tools.FloorPOT(x);
  7869. return (c - x) > (x - f) ? f : c;
  7870. };
  7871. Tools.GetExponentOfTwo = function (value, max, mode) {
  7872. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7873. var pot;
  7874. switch (mode) {
  7875. case BABYLON.Engine.SCALEMODE_FLOOR:
  7876. pot = Tools.FloorPOT(value);
  7877. break;
  7878. case BABYLON.Engine.SCALEMODE_NEAREST:
  7879. pot = Tools.NearestPOT(value);
  7880. break;
  7881. case BABYLON.Engine.SCALEMODE_CEILING:
  7882. default:
  7883. pot = Tools.CeilingPOT(value);
  7884. break;
  7885. }
  7886. return Math.min(pot, max);
  7887. };
  7888. Tools.GetFilename = function (path) {
  7889. var index = path.lastIndexOf("/");
  7890. if (index < 0)
  7891. return path;
  7892. return path.substring(index + 1);
  7893. };
  7894. /**
  7895. * Extracts the "folder" part of a path (everything before the filename).
  7896. * @param uri The URI to extract the info from
  7897. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7898. * @returns The "folder" part of the path
  7899. */
  7900. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7901. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7902. var index = uri.lastIndexOf("/");
  7903. if (index < 0) {
  7904. if (returnUnchangedIfNoSlash) {
  7905. return uri;
  7906. }
  7907. return "";
  7908. }
  7909. return uri.substring(0, index + 1);
  7910. };
  7911. Tools.GetDOMTextContent = function (element) {
  7912. var result = "";
  7913. var child = element.firstChild;
  7914. while (child) {
  7915. if (child.nodeType === 3) {
  7916. result += child.textContent;
  7917. }
  7918. child = child.nextSibling;
  7919. }
  7920. return result;
  7921. };
  7922. Tools.ToDegrees = function (angle) {
  7923. return angle * 180 / Math.PI;
  7924. };
  7925. Tools.ToRadians = function (angle) {
  7926. return angle * Math.PI / 180;
  7927. };
  7928. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7929. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7930. var output = "";
  7931. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7932. var i = 0;
  7933. var bytes = new Uint8Array(buffer);
  7934. while (i < bytes.length) {
  7935. chr1 = bytes[i++];
  7936. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7937. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7938. enc1 = chr1 >> 2;
  7939. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7940. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7941. enc4 = chr3 & 63;
  7942. if (isNaN(chr2)) {
  7943. enc3 = enc4 = 64;
  7944. }
  7945. else if (isNaN(chr3)) {
  7946. enc4 = 64;
  7947. }
  7948. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7949. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7950. }
  7951. return "data:image/png;base64," + output;
  7952. };
  7953. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7954. if (bias === void 0) { bias = null; }
  7955. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7956. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7957. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7958. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7959. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7960. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7961. }
  7962. if (bias) {
  7963. minimum.x -= minimum.x * bias.x + bias.y;
  7964. minimum.y -= minimum.y * bias.x + bias.y;
  7965. minimum.z -= minimum.z * bias.x + bias.y;
  7966. maximum.x += maximum.x * bias.x + bias.y;
  7967. maximum.y += maximum.y * bias.x + bias.y;
  7968. maximum.z += maximum.z * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7976. if (bias === void 0) { bias = null; }
  7977. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7978. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7979. if (!stride) {
  7980. stride = 3;
  7981. }
  7982. for (var index = start; index < start + count; index++) {
  7983. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7986. }
  7987. if (bias) {
  7988. minimum.x -= minimum.x * bias.x + bias.y;
  7989. minimum.y -= minimum.y * bias.x + bias.y;
  7990. minimum.z -= minimum.z * bias.x + bias.y;
  7991. maximum.x += maximum.x * bias.x + bias.y;
  7992. maximum.y += maximum.y * bias.x + bias.y;
  7993. maximum.z += maximum.z * bias.x + bias.y;
  7994. }
  7995. return {
  7996. minimum: minimum,
  7997. maximum: maximum
  7998. };
  7999. };
  8000. Tools.Vector2ArrayFeeder = function (array) {
  8001. return function (index) {
  8002. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8003. var length = isFloatArray ? array.length / 2 : array.length;
  8004. if (index >= length) {
  8005. return null;
  8006. }
  8007. if (isFloatArray) {
  8008. var fa = array;
  8009. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8010. }
  8011. var a = array;
  8012. return a[index];
  8013. };
  8014. };
  8015. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8016. if (bias === void 0) { bias = null; }
  8017. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8018. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8019. var i = 0;
  8020. var cur = feeder(i++);
  8021. while (cur) {
  8022. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8023. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8024. cur = feeder(i++);
  8025. }
  8026. if (bias) {
  8027. minimum.x -= minimum.x * bias.x + bias.y;
  8028. minimum.y -= minimum.y * bias.x + bias.y;
  8029. maximum.x += maximum.x * bias.x + bias.y;
  8030. maximum.y += maximum.y * bias.x + bias.y;
  8031. }
  8032. return {
  8033. minimum: minimum,
  8034. maximum: maximum
  8035. };
  8036. };
  8037. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8038. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8039. return null;
  8040. return Array.isArray(obj) ? obj : [obj];
  8041. };
  8042. // Misc.
  8043. Tools.GetPointerPrefix = function () {
  8044. var eventPrefix = "pointer";
  8045. // Check if pointer events are supported
  8046. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8047. eventPrefix = "mouse";
  8048. }
  8049. return eventPrefix;
  8050. };
  8051. /**
  8052. * @param func - the function to be called
  8053. * @param requester - the object that will request the next frame. Falls back to window.
  8054. */
  8055. Tools.QueueNewFrame = function (func, requester) {
  8056. if (!Tools.IsWindowObjectExist()) {
  8057. return setTimeout(func, 16);
  8058. }
  8059. if (!requester) {
  8060. requester = window;
  8061. }
  8062. if (requester.requestAnimationFrame) {
  8063. return requester.requestAnimationFrame(func);
  8064. }
  8065. else if (requester.msRequestAnimationFrame) {
  8066. return requester.msRequestAnimationFrame(func);
  8067. }
  8068. else if (requester.webkitRequestAnimationFrame) {
  8069. return requester.webkitRequestAnimationFrame(func);
  8070. }
  8071. else if (requester.mozRequestAnimationFrame) {
  8072. return requester.mozRequestAnimationFrame(func);
  8073. }
  8074. else if (requester.oRequestAnimationFrame) {
  8075. return requester.oRequestAnimationFrame(func);
  8076. }
  8077. else {
  8078. return window.setTimeout(func, 16);
  8079. }
  8080. };
  8081. Tools.RequestFullscreen = function (element) {
  8082. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8083. if (!requestFunction)
  8084. return;
  8085. requestFunction.call(element);
  8086. };
  8087. Tools.ExitFullscreen = function () {
  8088. if (document.exitFullscreen) {
  8089. document.exitFullscreen();
  8090. }
  8091. else if (document.mozCancelFullScreen) {
  8092. document.mozCancelFullScreen();
  8093. }
  8094. else if (document.webkitCancelFullScreen) {
  8095. document.webkitCancelFullScreen();
  8096. }
  8097. else if (document.msCancelFullScreen) {
  8098. document.msCancelFullScreen();
  8099. }
  8100. };
  8101. Tools.SetCorsBehavior = function (url, element) {
  8102. if (url && url.indexOf("data:") === 0) {
  8103. return;
  8104. }
  8105. if (Tools.CorsBehavior) {
  8106. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8107. element.crossOrigin = Tools.CorsBehavior;
  8108. }
  8109. else {
  8110. var result = Tools.CorsBehavior(url);
  8111. if (result) {
  8112. element.crossOrigin = result;
  8113. }
  8114. }
  8115. }
  8116. };
  8117. // External files
  8118. Tools.CleanUrl = function (url) {
  8119. url = url.replace(/#/mg, "%23");
  8120. return url;
  8121. };
  8122. Tools.LoadImage = function (url, onLoad, onError, database) {
  8123. if (url instanceof ArrayBuffer) {
  8124. url = Tools.EncodeArrayBufferTobase64(url);
  8125. }
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. var img = new Image();
  8129. Tools.SetCorsBehavior(url, img);
  8130. var loadHandler = function () {
  8131. img.removeEventListener("load", loadHandler);
  8132. img.removeEventListener("error", errorHandler);
  8133. onLoad(img);
  8134. };
  8135. var errorHandler = function (err) {
  8136. img.removeEventListener("load", loadHandler);
  8137. img.removeEventListener("error", errorHandler);
  8138. Tools.Error("Error while trying to load image: " + url);
  8139. if (onError) {
  8140. onError("Error while trying to load image: " + url, err);
  8141. }
  8142. };
  8143. img.addEventListener("load", loadHandler);
  8144. img.addEventListener("error", errorHandler);
  8145. var noIndexedDB = function () {
  8146. img.src = url;
  8147. };
  8148. var loadFromIndexedDB = function () {
  8149. if (database) {
  8150. database.loadImageFromDB(url, img);
  8151. }
  8152. };
  8153. //ANY database to do!
  8154. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8155. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8156. }
  8157. else {
  8158. if (url.indexOf("file:") !== -1) {
  8159. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8160. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8161. try {
  8162. var blobURL;
  8163. try {
  8164. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8165. }
  8166. catch (ex) {
  8167. // Chrome doesn't support oneTimeOnly parameter
  8168. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8169. }
  8170. img.src = blobURL;
  8171. }
  8172. catch (e) {
  8173. img.src = "";
  8174. }
  8175. return img;
  8176. }
  8177. }
  8178. noIndexedDB();
  8179. }
  8180. return img;
  8181. };
  8182. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8183. url = Tools.CleanUrl(url);
  8184. url = Tools.PreprocessUrl(url);
  8185. // If file and file input are set
  8186. if (url.indexOf("file:") !== -1) {
  8187. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8188. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8189. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8190. }
  8191. }
  8192. var loadUrl = Tools.BaseUrl + url;
  8193. var aborted = false;
  8194. var fileRequest = {
  8195. onCompleteObservable: new BABYLON.Observable(),
  8196. abort: function () { return aborted = true; },
  8197. };
  8198. var requestFile = function () {
  8199. var request = new XMLHttpRequest();
  8200. var retryHandle = null;
  8201. fileRequest.abort = function () {
  8202. aborted = true;
  8203. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8204. request.abort();
  8205. }
  8206. if (retryHandle !== null) {
  8207. clearTimeout(retryHandle);
  8208. retryHandle = null;
  8209. }
  8210. };
  8211. var retryLoop = function (retryIndex) {
  8212. request.open('GET', loadUrl, true);
  8213. if (useArrayBuffer) {
  8214. request.responseType = "arraybuffer";
  8215. }
  8216. if (onProgress) {
  8217. request.addEventListener("progress", onProgress);
  8218. }
  8219. var onLoadEnd = function () {
  8220. request.removeEventListener("loadend", onLoadEnd);
  8221. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8222. fileRequest.onCompleteObservable.clear();
  8223. };
  8224. request.addEventListener("loadend", onLoadEnd);
  8225. var onReadyStateChange = function () {
  8226. if (aborted) {
  8227. return;
  8228. }
  8229. // In case of undefined state in some browsers.
  8230. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8231. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8232. request.removeEventListener("readystatechange", onReadyStateChange);
  8233. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8234. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8235. return;
  8236. }
  8237. var retryStrategy = Tools.DefaultRetryStrategy;
  8238. if (retryStrategy) {
  8239. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8240. if (waitTime !== -1) {
  8241. // Prevent the request from completing for retry.
  8242. request.removeEventListener("loadend", onLoadEnd);
  8243. request = new XMLHttpRequest();
  8244. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8245. return;
  8246. }
  8247. }
  8248. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8249. if (onError) {
  8250. onError(request, e);
  8251. }
  8252. else {
  8253. throw e;
  8254. }
  8255. }
  8256. };
  8257. request.addEventListener("readystatechange", onReadyStateChange);
  8258. request.send();
  8259. };
  8260. retryLoop(0);
  8261. };
  8262. // Caching all files
  8263. if (database && database.enableSceneOffline) {
  8264. var noIndexedDB_1 = function () {
  8265. if (!aborted) {
  8266. requestFile();
  8267. }
  8268. };
  8269. var loadFromIndexedDB = function () {
  8270. // TODO: database needs to support aborting and should return a IFileRequest
  8271. if (aborted) {
  8272. return;
  8273. }
  8274. if (database) {
  8275. database.loadFileFromDB(url, function (data) {
  8276. if (!aborted) {
  8277. onSuccess(data);
  8278. }
  8279. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8280. }, onProgress ? function (event) {
  8281. if (!aborted) {
  8282. onProgress(event);
  8283. }
  8284. } : undefined, noIndexedDB_1, useArrayBuffer);
  8285. }
  8286. };
  8287. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8288. }
  8289. else {
  8290. requestFile();
  8291. }
  8292. return fileRequest;
  8293. };
  8294. /**
  8295. * Load a script (identified by an url). When the url returns, the
  8296. * content of this file is added into a new script element, attached to the DOM (body element)
  8297. */
  8298. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8299. var head = document.getElementsByTagName('head')[0];
  8300. var script = document.createElement('script');
  8301. script.type = 'text/javascript';
  8302. script.src = scriptUrl;
  8303. script.onload = function () {
  8304. if (onSuccess) {
  8305. onSuccess();
  8306. }
  8307. };
  8308. script.onerror = function (e) {
  8309. if (onError) {
  8310. onError("Unable to load script", e);
  8311. }
  8312. };
  8313. head.appendChild(script);
  8314. };
  8315. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8316. var reader = new FileReader();
  8317. var request = {
  8318. onCompleteObservable: new BABYLON.Observable(),
  8319. abort: function () { return reader.abort(); },
  8320. };
  8321. reader.onloadend = function (e) {
  8322. request.onCompleteObservable.notifyObservers(request);
  8323. };
  8324. reader.onload = function (e) {
  8325. //target doesn't have result from ts 1.3
  8326. callback(e.target['result']);
  8327. };
  8328. reader.onprogress = progressCallback;
  8329. reader.readAsDataURL(fileToLoad);
  8330. return request;
  8331. };
  8332. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8333. var reader = new FileReader();
  8334. var request = {
  8335. onCompleteObservable: new BABYLON.Observable(),
  8336. abort: function () { return reader.abort(); },
  8337. };
  8338. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8339. reader.onerror = function (e) {
  8340. Tools.Log("Error while reading file: " + fileToLoad.name);
  8341. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8342. };
  8343. reader.onload = function (e) {
  8344. //target doesn't have result from ts 1.3
  8345. callback(e.target['result']);
  8346. };
  8347. if (progressCallBack) {
  8348. reader.onprogress = progressCallBack;
  8349. }
  8350. if (!useArrayBuffer) {
  8351. // Asynchronous read
  8352. reader.readAsText(fileToLoad);
  8353. }
  8354. else {
  8355. reader.readAsArrayBuffer(fileToLoad);
  8356. }
  8357. return request;
  8358. };
  8359. //returns a downloadable url to a file content.
  8360. Tools.FileAsURL = function (content) {
  8361. var fileBlob = new Blob([content]);
  8362. var url = window.URL || window.webkitURL;
  8363. var link = url.createObjectURL(fileBlob);
  8364. return link;
  8365. };
  8366. // Misc.
  8367. Tools.Format = function (value, decimals) {
  8368. if (decimals === void 0) { decimals = 2; }
  8369. return value.toFixed(decimals);
  8370. };
  8371. Tools.CheckExtends = function (v, min, max) {
  8372. if (v.x < min.x)
  8373. min.x = v.x;
  8374. if (v.y < min.y)
  8375. min.y = v.y;
  8376. if (v.z < min.z)
  8377. min.z = v.z;
  8378. if (v.x > max.x)
  8379. max.x = v.x;
  8380. if (v.y > max.y)
  8381. max.y = v.y;
  8382. if (v.z > max.z)
  8383. max.z = v.z;
  8384. };
  8385. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8386. for (var prop in source) {
  8387. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8388. continue;
  8389. }
  8390. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8391. continue;
  8392. }
  8393. var sourceValue = source[prop];
  8394. var typeOfSourceValue = typeof sourceValue;
  8395. if (typeOfSourceValue === "function") {
  8396. continue;
  8397. }
  8398. if (typeOfSourceValue === "object") {
  8399. if (sourceValue instanceof Array) {
  8400. destination[prop] = [];
  8401. if (sourceValue.length > 0) {
  8402. if (typeof sourceValue[0] == "object") {
  8403. for (var index = 0; index < sourceValue.length; index++) {
  8404. var clonedValue = cloneValue(sourceValue[index], destination);
  8405. if (destination[prop].indexOf(clonedValue) === -1) {
  8406. destination[prop].push(clonedValue);
  8407. }
  8408. }
  8409. }
  8410. else {
  8411. destination[prop] = sourceValue.slice(0);
  8412. }
  8413. }
  8414. }
  8415. else {
  8416. destination[prop] = cloneValue(sourceValue, destination);
  8417. }
  8418. }
  8419. else {
  8420. destination[prop] = sourceValue;
  8421. }
  8422. }
  8423. };
  8424. Tools.IsEmpty = function (obj) {
  8425. for (var i in obj) {
  8426. if (obj.hasOwnProperty(i)) {
  8427. return false;
  8428. }
  8429. }
  8430. return true;
  8431. };
  8432. Tools.RegisterTopRootEvents = function (events) {
  8433. for (var index = 0; index < events.length; index++) {
  8434. var event = events[index];
  8435. window.addEventListener(event.name, event.handler, false);
  8436. try {
  8437. if (window.parent) {
  8438. window.parent.addEventListener(event.name, event.handler, false);
  8439. }
  8440. }
  8441. catch (e) {
  8442. // Silently fails...
  8443. }
  8444. }
  8445. };
  8446. Tools.UnregisterTopRootEvents = function (events) {
  8447. for (var index = 0; index < events.length; index++) {
  8448. var event = events[index];
  8449. window.removeEventListener(event.name, event.handler);
  8450. try {
  8451. if (window.parent) {
  8452. window.parent.removeEventListener(event.name, event.handler);
  8453. }
  8454. }
  8455. catch (e) {
  8456. // Silently fails...
  8457. }
  8458. }
  8459. };
  8460. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8461. if (mimeType === void 0) { mimeType = "image/png"; }
  8462. // Read the contents of the framebuffer
  8463. var numberOfChannelsByLine = width * 4;
  8464. var halfHeight = height / 2;
  8465. //Reading datas from WebGL
  8466. var data = engine.readPixels(0, 0, width, height);
  8467. //To flip image on Y axis.
  8468. for (var i = 0; i < halfHeight; i++) {
  8469. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8470. var currentCell = j + i * numberOfChannelsByLine;
  8471. var targetLine = height - i - 1;
  8472. var targetCell = j + targetLine * numberOfChannelsByLine;
  8473. var temp = data[currentCell];
  8474. data[currentCell] = data[targetCell];
  8475. data[targetCell] = temp;
  8476. }
  8477. }
  8478. // Create a 2D canvas to store the result
  8479. if (!screenshotCanvas) {
  8480. screenshotCanvas = document.createElement('canvas');
  8481. }
  8482. screenshotCanvas.width = width;
  8483. screenshotCanvas.height = height;
  8484. var context = screenshotCanvas.getContext('2d');
  8485. if (context) {
  8486. // Copy the pixels to a 2D canvas
  8487. var imageData = context.createImageData(width, height);
  8488. var castData = (imageData.data);
  8489. castData.set(data);
  8490. context.putImageData(imageData, 0, 0);
  8491. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8492. }
  8493. };
  8494. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8495. if (mimeType === void 0) { mimeType = "image/png"; }
  8496. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8497. if (successCallback) {
  8498. successCallback(base64Image);
  8499. }
  8500. else {
  8501. // We need HTMLCanvasElement.toBlob for HD screenshots
  8502. if (!screenshotCanvas.toBlob) {
  8503. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8504. screenshotCanvas.toBlob = function (callback, type, quality) {
  8505. var _this = this;
  8506. setTimeout(function () {
  8507. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8508. for (var i = 0; i < len; i++) {
  8509. arr[i] = binStr.charCodeAt(i);
  8510. }
  8511. callback(new Blob([arr], { type: type || 'image/png' }));
  8512. });
  8513. };
  8514. }
  8515. screenshotCanvas.toBlob(function (blob) {
  8516. var url = URL.createObjectURL(blob);
  8517. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8518. if (("download" in document.createElement("a"))) {
  8519. var a = window.document.createElement("a");
  8520. a.href = url;
  8521. if (fileName) {
  8522. a.setAttribute("download", fileName);
  8523. }
  8524. else {
  8525. var date = new Date();
  8526. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8527. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8528. }
  8529. window.document.body.appendChild(a);
  8530. a.addEventListener("click", function () {
  8531. if (a.parentElement) {
  8532. a.parentElement.removeChild(a);
  8533. }
  8534. });
  8535. a.click();
  8536. }
  8537. else {
  8538. var newWindow = window.open("");
  8539. if (!newWindow)
  8540. return;
  8541. var img = newWindow.document.createElement("img");
  8542. img.onload = function () {
  8543. // no longer need to read the blob so it's revoked
  8544. URL.revokeObjectURL(url);
  8545. };
  8546. img.src = url;
  8547. newWindow.document.body.appendChild(img);
  8548. }
  8549. });
  8550. }
  8551. };
  8552. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8553. if (mimeType === void 0) { mimeType = "image/png"; }
  8554. var width;
  8555. var height;
  8556. // If a precision value is specified
  8557. if (size.precision) {
  8558. width = Math.round(engine.getRenderWidth() * size.precision);
  8559. height = Math.round(width / engine.getAspectRatio(camera));
  8560. }
  8561. else if (size.width && size.height) {
  8562. width = size.width;
  8563. height = size.height;
  8564. }
  8565. else if (size.width && !size.height) {
  8566. width = size.width;
  8567. height = Math.round(width / engine.getAspectRatio(camera));
  8568. }
  8569. else if (size.height && !size.width) {
  8570. height = size.height;
  8571. width = Math.round(height * engine.getAspectRatio(camera));
  8572. }
  8573. else if (!isNaN(size)) {
  8574. height = size;
  8575. width = size;
  8576. }
  8577. else {
  8578. Tools.Error("Invalid 'size' parameter !");
  8579. return;
  8580. }
  8581. if (!screenshotCanvas) {
  8582. screenshotCanvas = document.createElement('canvas');
  8583. }
  8584. screenshotCanvas.width = width;
  8585. screenshotCanvas.height = height;
  8586. var renderContext = screenshotCanvas.getContext("2d");
  8587. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8588. var newWidth = width;
  8589. var newHeight = newWidth / ratio;
  8590. if (newHeight > height) {
  8591. newHeight = height;
  8592. newWidth = newHeight * ratio;
  8593. }
  8594. var offsetX = Math.max(0, width - newWidth) / 2;
  8595. var offsetY = Math.max(0, height - newHeight) / 2;
  8596. var renderingCanvas = engine.getRenderingCanvas();
  8597. if (renderContext && renderingCanvas) {
  8598. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8599. }
  8600. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8601. };
  8602. /**
  8603. * Generates an image screenshot from the specified camera.
  8604. *
  8605. * @param engine The engine to use for rendering
  8606. * @param camera The camera to use for rendering
  8607. * @param size This parameter can be set to a single number or to an object with the
  8608. * following (optional) properties: precision, width, height. If a single number is passed,
  8609. * it will be used for both width and height. If an object is passed, the screenshot size
  8610. * will be derived from the parameters. The precision property is a multiplier allowing
  8611. * rendering at a higher or lower resolution.
  8612. * @param successCallback The callback receives a single parameter which contains the
  8613. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8614. * src parameter of an <img> to display it.
  8615. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8616. * Check your browser for supported MIME types.
  8617. * @param samples Texture samples (default: 1)
  8618. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8619. * @param fileName A name for for the downloaded file.
  8620. * @constructor
  8621. */
  8622. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8623. if (mimeType === void 0) { mimeType = "image/png"; }
  8624. if (samples === void 0) { samples = 1; }
  8625. if (antialiasing === void 0) { antialiasing = false; }
  8626. var width;
  8627. var height;
  8628. //If a precision value is specified
  8629. if (size.precision) {
  8630. width = Math.round(engine.getRenderWidth() * size.precision);
  8631. height = Math.round(width / engine.getAspectRatio(camera));
  8632. size = { width: width, height: height };
  8633. }
  8634. else if (size.width && size.height) {
  8635. width = size.width;
  8636. height = size.height;
  8637. }
  8638. else if (size.width && !size.height) {
  8639. width = size.width;
  8640. height = Math.round(width / engine.getAspectRatio(camera));
  8641. size = { width: width, height: height };
  8642. }
  8643. else if (size.height && !size.width) {
  8644. height = size.height;
  8645. width = Math.round(height * engine.getAspectRatio(camera));
  8646. size = { width: width, height: height };
  8647. }
  8648. else if (!isNaN(size)) {
  8649. height = size;
  8650. width = size;
  8651. }
  8652. else {
  8653. Tools.Error("Invalid 'size' parameter !");
  8654. return;
  8655. }
  8656. var scene = camera.getScene();
  8657. var previousCamera = null;
  8658. if (scene.activeCamera !== camera) {
  8659. previousCamera = scene.activeCamera;
  8660. scene.activeCamera = camera;
  8661. }
  8662. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8663. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8664. texture.renderList = null;
  8665. texture.samples = samples;
  8666. if (antialiasing) {
  8667. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8668. }
  8669. texture.onAfterRenderObservable.add(function () {
  8670. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8671. });
  8672. scene.incrementRenderId();
  8673. scene.resetCachedMaterial();
  8674. texture.render(true);
  8675. texture.dispose();
  8676. if (previousCamera) {
  8677. scene.activeCamera = previousCamera;
  8678. }
  8679. camera.getProjectionMatrix(true); // Force cache refresh;
  8680. };
  8681. // XHR response validator for local file scenario
  8682. Tools.ValidateXHRData = function (xhr, dataType) {
  8683. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8684. if (dataType === void 0) { dataType = 7; }
  8685. try {
  8686. if (dataType & 1) {
  8687. if (xhr.responseText && xhr.responseText.length > 0) {
  8688. return true;
  8689. }
  8690. else if (dataType === 1) {
  8691. return false;
  8692. }
  8693. }
  8694. if (dataType & 2) {
  8695. // Check header width and height since there is no "TGA" magic number
  8696. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8697. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8698. return true;
  8699. }
  8700. else if (dataType === 2) {
  8701. return false;
  8702. }
  8703. }
  8704. if (dataType & 4) {
  8705. // Check for the "DDS" magic number
  8706. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8707. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8708. return true;
  8709. }
  8710. else {
  8711. return false;
  8712. }
  8713. }
  8714. }
  8715. catch (e) {
  8716. // Global protection
  8717. }
  8718. return false;
  8719. };
  8720. /**
  8721. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8722. * Be aware Math.random() could cause collisions, but:
  8723. * "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"
  8724. */
  8725. Tools.RandomId = function () {
  8726. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8727. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8728. return v.toString(16);
  8729. });
  8730. };
  8731. /**
  8732. * Test if the given uri is a base64 string.
  8733. * @param uri The uri to test
  8734. * @return True if the uri is a base64 string or false otherwise.
  8735. */
  8736. Tools.IsBase64 = function (uri) {
  8737. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8738. };
  8739. /**
  8740. * Decode the given base64 uri.
  8741. * @param uri The uri to decode
  8742. * @return The decoded base64 data.
  8743. */
  8744. Tools.DecodeBase64 = function (uri) {
  8745. var decodedString = atob(uri.split(",")[1]);
  8746. var bufferLength = decodedString.length;
  8747. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8748. for (var i = 0; i < bufferLength; i++) {
  8749. bufferView[i] = decodedString.charCodeAt(i);
  8750. }
  8751. return bufferView.buffer;
  8752. };
  8753. Object.defineProperty(Tools, "NoneLogLevel", {
  8754. get: function () {
  8755. return Tools._NoneLogLevel;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(Tools, "MessageLogLevel", {
  8761. get: function () {
  8762. return Tools._MessageLogLevel;
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Object.defineProperty(Tools, "WarningLogLevel", {
  8768. get: function () {
  8769. return Tools._WarningLogLevel;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(Tools, "ErrorLogLevel", {
  8775. get: function () {
  8776. return Tools._ErrorLogLevel;
  8777. },
  8778. enumerable: true,
  8779. configurable: true
  8780. });
  8781. Object.defineProperty(Tools, "AllLogLevel", {
  8782. get: function () {
  8783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Tools._AddLogEntry = function (entry) {
  8789. Tools._LogCache = entry + Tools._LogCache;
  8790. if (Tools.OnNewCacheEntry) {
  8791. Tools.OnNewCacheEntry(entry);
  8792. }
  8793. };
  8794. Tools._FormatMessage = function (message) {
  8795. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8796. var date = new Date();
  8797. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8798. };
  8799. Tools._LogDisabled = function (message) {
  8800. // nothing to do
  8801. };
  8802. Tools._LogEnabled = function (message) {
  8803. var formattedMessage = Tools._FormatMessage(message);
  8804. console.log("BJS - " + formattedMessage);
  8805. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8806. Tools._AddLogEntry(entry);
  8807. };
  8808. Tools._WarnDisabled = function (message) {
  8809. // nothing to do
  8810. };
  8811. Tools._WarnEnabled = function (message) {
  8812. var formattedMessage = Tools._FormatMessage(message);
  8813. console.warn("BJS - " + formattedMessage);
  8814. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8815. Tools._AddLogEntry(entry);
  8816. };
  8817. Tools._ErrorDisabled = function (message) {
  8818. // nothing to do
  8819. };
  8820. Tools._ErrorEnabled = function (message) {
  8821. Tools.errorsCount++;
  8822. var formattedMessage = Tools._FormatMessage(message);
  8823. console.error("BJS - " + formattedMessage);
  8824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8825. Tools._AddLogEntry(entry);
  8826. };
  8827. Object.defineProperty(Tools, "LogCache", {
  8828. get: function () {
  8829. return Tools._LogCache;
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Tools.ClearLogCache = function () {
  8835. Tools._LogCache = "";
  8836. Tools.errorsCount = 0;
  8837. };
  8838. Object.defineProperty(Tools, "LogLevels", {
  8839. set: function (level) {
  8840. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8841. Tools.Log = Tools._LogEnabled;
  8842. }
  8843. else {
  8844. Tools.Log = Tools._LogDisabled;
  8845. }
  8846. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8847. Tools.Warn = Tools._WarnEnabled;
  8848. }
  8849. else {
  8850. Tools.Warn = Tools._WarnDisabled;
  8851. }
  8852. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8853. Tools.Error = Tools._ErrorEnabled;
  8854. }
  8855. else {
  8856. Tools.Error = Tools._ErrorDisabled;
  8857. }
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Tools.IsWindowObjectExist = function () {
  8863. return (typeof window) !== "undefined";
  8864. };
  8865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8866. get: function () {
  8867. return Tools._PerformanceNoneLogLevel;
  8868. },
  8869. enumerable: true,
  8870. configurable: true
  8871. });
  8872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8873. get: function () {
  8874. return Tools._PerformanceUserMarkLogLevel;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8880. get: function () {
  8881. return Tools._PerformanceConsoleLogLevel;
  8882. },
  8883. enumerable: true,
  8884. configurable: true
  8885. });
  8886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8887. set: function (level) {
  8888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8891. return;
  8892. }
  8893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8896. return;
  8897. }
  8898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8900. },
  8901. enumerable: true,
  8902. configurable: true
  8903. });
  8904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8905. };
  8906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8907. };
  8908. Tools._StartUserMark = function (counterName, condition) {
  8909. if (condition === void 0) { condition = true; }
  8910. if (!Tools._performance) {
  8911. if (!Tools.IsWindowObjectExist()) {
  8912. return;
  8913. }
  8914. Tools._performance = window.performance;
  8915. }
  8916. if (!condition || !Tools._performance.mark) {
  8917. return;
  8918. }
  8919. Tools._performance.mark(counterName + "-Begin");
  8920. };
  8921. Tools._EndUserMark = function (counterName, condition) {
  8922. if (condition === void 0) { condition = true; }
  8923. if (!condition || !Tools._performance.mark) {
  8924. return;
  8925. }
  8926. Tools._performance.mark(counterName + "-End");
  8927. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8928. };
  8929. Tools._StartPerformanceConsole = function (counterName, condition) {
  8930. if (condition === void 0) { condition = true; }
  8931. if (!condition) {
  8932. return;
  8933. }
  8934. Tools._StartUserMark(counterName, condition);
  8935. if (console.time) {
  8936. console.time(counterName);
  8937. }
  8938. };
  8939. Tools._EndPerformanceConsole = function (counterName, condition) {
  8940. if (condition === void 0) { condition = true; }
  8941. if (!condition) {
  8942. return;
  8943. }
  8944. Tools._EndUserMark(counterName, condition);
  8945. if (console.time) {
  8946. console.timeEnd(counterName);
  8947. }
  8948. };
  8949. Object.defineProperty(Tools, "Now", {
  8950. get: function () {
  8951. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8952. return window.performance.now();
  8953. }
  8954. return new Date().getTime();
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. /**
  8960. * This method will return the name of the class used to create the instance of the given object.
  8961. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8962. * @param object the object to get the class name from
  8963. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8964. */
  8965. Tools.GetClassName = function (object, isType) {
  8966. if (isType === void 0) { isType = false; }
  8967. var name = null;
  8968. if (!isType && object.getClassName) {
  8969. name = object.getClassName();
  8970. }
  8971. else {
  8972. if (object instanceof Object) {
  8973. var classObj = isType ? object : Object.getPrototypeOf(object);
  8974. name = classObj.constructor["__bjsclassName__"];
  8975. }
  8976. if (!name) {
  8977. name = typeof object;
  8978. }
  8979. }
  8980. return name;
  8981. };
  8982. Tools.First = function (array, predicate) {
  8983. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8984. var el = array_1[_i];
  8985. if (predicate(el)) {
  8986. return el;
  8987. }
  8988. }
  8989. return null;
  8990. };
  8991. /**
  8992. * This method will return the name of the full name of the class, including its owning module (if any).
  8993. * 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).
  8994. * @param object the object to get the class name from
  8995. * @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.
  8996. */
  8997. Tools.getFullClassName = function (object, isType) {
  8998. if (isType === void 0) { isType = false; }
  8999. var className = null;
  9000. var moduleName = null;
  9001. if (!isType && object.getClassName) {
  9002. className = object.getClassName();
  9003. }
  9004. else {
  9005. if (object instanceof Object) {
  9006. var classObj = isType ? object : Object.getPrototypeOf(object);
  9007. className = classObj.constructor["__bjsclassName__"];
  9008. moduleName = classObj.constructor["__bjsmoduleName__"];
  9009. }
  9010. if (!className) {
  9011. className = typeof object;
  9012. }
  9013. }
  9014. if (!className) {
  9015. return null;
  9016. }
  9017. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9018. };
  9019. /**
  9020. * 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.
  9021. * @param array
  9022. */
  9023. Tools.arrayOrStringFeeder = function (array) {
  9024. return function (index) {
  9025. if (index >= array.length) {
  9026. return null;
  9027. }
  9028. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9029. if (val && val.getHashCode) {
  9030. val = val.getHashCode();
  9031. }
  9032. if (typeof val === "string") {
  9033. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9034. }
  9035. return val;
  9036. };
  9037. };
  9038. /**
  9039. * Compute the hashCode of a stream of number
  9040. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9041. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9042. * @return the hash code computed
  9043. */
  9044. Tools.hashCodeFromStream = function (feeder) {
  9045. // Based from here: http://stackoverflow.com/a/7616484/802124
  9046. var hash = 0;
  9047. var index = 0;
  9048. var chr = feeder(index++);
  9049. while (chr != null) {
  9050. hash = ((hash << 5) - hash) + chr;
  9051. hash |= 0; // Convert to 32bit integer
  9052. chr = feeder(index++);
  9053. }
  9054. return hash;
  9055. };
  9056. /**
  9057. * Returns a promise that resolves after the given amount of time.
  9058. * @param delay Number of milliseconds to delay
  9059. * @returns Promise that resolves after the given amount of time
  9060. */
  9061. Tools.DelayAsync = function (delay) {
  9062. return new Promise(function (resolve) {
  9063. setTimeout(function () {
  9064. resolve();
  9065. }, delay);
  9066. });
  9067. };
  9068. Tools.BaseUrl = "";
  9069. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9070. /**
  9071. * Default behaviour for cors in the application.
  9072. * It can be a string if the expected behavior is identical in the entire app.
  9073. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9074. */
  9075. Tools.CorsBehavior = "anonymous";
  9076. Tools.UseFallbackTexture = true;
  9077. /**
  9078. * Use this object to register external classes like custom textures or material
  9079. * to allow the laoders to instantiate them
  9080. */
  9081. Tools.RegisteredExternalClasses = {};
  9082. // Used in case of a texture loading problem
  9083. 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";
  9084. Tools.PreprocessUrl = function (url) {
  9085. return url;
  9086. };
  9087. // Logs
  9088. Tools._NoneLogLevel = 0;
  9089. Tools._MessageLogLevel = 1;
  9090. Tools._WarningLogLevel = 2;
  9091. Tools._ErrorLogLevel = 4;
  9092. Tools._LogCache = "";
  9093. Tools.errorsCount = 0;
  9094. Tools.Log = Tools._LogEnabled;
  9095. Tools.Warn = Tools._WarnEnabled;
  9096. Tools.Error = Tools._ErrorEnabled;
  9097. // Performances
  9098. Tools._PerformanceNoneLogLevel = 0;
  9099. Tools._PerformanceUserMarkLogLevel = 1;
  9100. Tools._PerformanceConsoleLogLevel = 2;
  9101. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9102. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9103. return Tools;
  9104. }());
  9105. BABYLON.Tools = Tools;
  9106. /**
  9107. * This class is used to track a performance counter which is number based.
  9108. * The user has access to many properties which give statistics of different nature
  9109. *
  9110. * The implementer can track two kinds of Performance Counter: time and count
  9111. * 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.
  9112. * 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.
  9113. */
  9114. var PerfCounter = /** @class */ (function () {
  9115. function PerfCounter() {
  9116. this._startMonitoringTime = 0;
  9117. this._min = 0;
  9118. this._max = 0;
  9119. this._average = 0;
  9120. this._lastSecAverage = 0;
  9121. this._current = 0;
  9122. this._totalValueCount = 0;
  9123. this._totalAccumulated = 0;
  9124. this._lastSecAccumulated = 0;
  9125. this._lastSecTime = 0;
  9126. this._lastSecValueCount = 0;
  9127. }
  9128. Object.defineProperty(PerfCounter.prototype, "min", {
  9129. /**
  9130. * Returns the smallest value ever
  9131. */
  9132. get: function () {
  9133. return this._min;
  9134. },
  9135. enumerable: true,
  9136. configurable: true
  9137. });
  9138. Object.defineProperty(PerfCounter.prototype, "max", {
  9139. /**
  9140. * Returns the biggest value ever
  9141. */
  9142. get: function () {
  9143. return this._max;
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(PerfCounter.prototype, "average", {
  9149. /**
  9150. * Returns the average value since the performance counter is running
  9151. */
  9152. get: function () {
  9153. return this._average;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9159. /**
  9160. * Returns the average value of the last second the counter was monitored
  9161. */
  9162. get: function () {
  9163. return this._lastSecAverage;
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. Object.defineProperty(PerfCounter.prototype, "current", {
  9169. /**
  9170. * Returns the current value
  9171. */
  9172. get: function () {
  9173. return this._current;
  9174. },
  9175. enumerable: true,
  9176. configurable: true
  9177. });
  9178. Object.defineProperty(PerfCounter.prototype, "total", {
  9179. get: function () {
  9180. return this._totalAccumulated;
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. Object.defineProperty(PerfCounter.prototype, "count", {
  9186. get: function () {
  9187. return this._totalValueCount;
  9188. },
  9189. enumerable: true,
  9190. configurable: true
  9191. });
  9192. /**
  9193. * Call this method to start monitoring a new frame.
  9194. * 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.
  9195. */
  9196. PerfCounter.prototype.fetchNewFrame = function () {
  9197. this._totalValueCount++;
  9198. this._current = 0;
  9199. this._lastSecValueCount++;
  9200. };
  9201. /**
  9202. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9203. * @param newCount the count value to add to the monitored count
  9204. * @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.
  9205. */
  9206. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9207. if (!PerfCounter.Enabled) {
  9208. return;
  9209. }
  9210. this._current += newCount;
  9211. if (fetchResult) {
  9212. this._fetchResult();
  9213. }
  9214. };
  9215. /**
  9216. * Start monitoring this performance counter
  9217. */
  9218. PerfCounter.prototype.beginMonitoring = function () {
  9219. if (!PerfCounter.Enabled) {
  9220. return;
  9221. }
  9222. this._startMonitoringTime = Tools.Now;
  9223. };
  9224. /**
  9225. * Compute the time lapsed since the previous beginMonitoring() call.
  9226. * @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
  9227. */
  9228. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9229. if (newFrame === void 0) { newFrame = true; }
  9230. if (!PerfCounter.Enabled) {
  9231. return;
  9232. }
  9233. if (newFrame) {
  9234. this.fetchNewFrame();
  9235. }
  9236. var currentTime = Tools.Now;
  9237. this._current = currentTime - this._startMonitoringTime;
  9238. if (newFrame) {
  9239. this._fetchResult();
  9240. }
  9241. };
  9242. PerfCounter.prototype._fetchResult = function () {
  9243. this._totalAccumulated += this._current;
  9244. this._lastSecAccumulated += this._current;
  9245. // Min/Max update
  9246. this._min = Math.min(this._min, this._current);
  9247. this._max = Math.max(this._max, this._current);
  9248. this._average = this._totalAccumulated / this._totalValueCount;
  9249. // Reset last sec?
  9250. var now = Tools.Now;
  9251. if ((now - this._lastSecTime) > 1000) {
  9252. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9253. this._lastSecTime = now;
  9254. this._lastSecAccumulated = 0;
  9255. this._lastSecValueCount = 0;
  9256. }
  9257. };
  9258. PerfCounter.Enabled = true;
  9259. return PerfCounter;
  9260. }());
  9261. BABYLON.PerfCounter = PerfCounter;
  9262. /**
  9263. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9264. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9265. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9266. * @param name The name of the class, case should be preserved
  9267. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9268. */
  9269. function className(name, module) {
  9270. return function (target) {
  9271. target["__bjsclassName__"] = name;
  9272. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9273. };
  9274. }
  9275. BABYLON.className = className;
  9276. /**
  9277. * An implementation of a loop for asynchronous functions.
  9278. */
  9279. var AsyncLoop = /** @class */ (function () {
  9280. /**
  9281. * Constroctor.
  9282. * @param iterations the number of iterations.
  9283. * @param _fn the function to run each iteration
  9284. * @param _successCallback the callback that will be called upon succesful execution
  9285. * @param offset starting offset.
  9286. */
  9287. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9288. if (offset === void 0) { offset = 0; }
  9289. this.iterations = iterations;
  9290. this._fn = _fn;
  9291. this._successCallback = _successCallback;
  9292. this.index = offset - 1;
  9293. this._done = false;
  9294. }
  9295. /**
  9296. * Execute the next iteration. Must be called after the last iteration was finished.
  9297. */
  9298. AsyncLoop.prototype.executeNext = function () {
  9299. if (!this._done) {
  9300. if (this.index + 1 < this.iterations) {
  9301. ++this.index;
  9302. this._fn(this);
  9303. }
  9304. else {
  9305. this.breakLoop();
  9306. }
  9307. }
  9308. };
  9309. /**
  9310. * Break the loop and run the success callback.
  9311. */
  9312. AsyncLoop.prototype.breakLoop = function () {
  9313. this._done = true;
  9314. this._successCallback();
  9315. };
  9316. /**
  9317. * Helper function
  9318. */
  9319. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9320. if (offset === void 0) { offset = 0; }
  9321. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9322. loop.executeNext();
  9323. return loop;
  9324. };
  9325. /**
  9326. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9327. * @param iterations total number of iterations
  9328. * @param syncedIterations number of synchronous iterations in each async iteration.
  9329. * @param fn the function to call each iteration.
  9330. * @param callback a success call back that will be called when iterating stops.
  9331. * @param breakFunction a break condition (optional)
  9332. * @param timeout timeout settings for the setTimeout function. default - 0.
  9333. * @constructor
  9334. */
  9335. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9336. if (timeout === void 0) { timeout = 0; }
  9337. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9338. if (breakFunction && breakFunction())
  9339. loop.breakLoop();
  9340. else {
  9341. setTimeout(function () {
  9342. for (var i = 0; i < syncedIterations; ++i) {
  9343. var iteration = (loop.index * syncedIterations) + i;
  9344. if (iteration >= iterations)
  9345. break;
  9346. fn(iteration);
  9347. if (breakFunction && breakFunction()) {
  9348. loop.breakLoop();
  9349. break;
  9350. }
  9351. }
  9352. loop.executeNext();
  9353. }, timeout);
  9354. }
  9355. }, callback);
  9356. };
  9357. return AsyncLoop;
  9358. }());
  9359. BABYLON.AsyncLoop = AsyncLoop;
  9360. })(BABYLON || (BABYLON = {}));
  9361. //# sourceMappingURL=babylon.tools.js.map
  9362. var BABYLON;
  9363. (function (BABYLON) {
  9364. var PromiseStates;
  9365. (function (PromiseStates) {
  9366. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9367. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9368. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9369. })(PromiseStates || (PromiseStates = {}));
  9370. var FulFillmentAgregator = /** @class */ (function () {
  9371. function FulFillmentAgregator() {
  9372. this.count = 0;
  9373. this.target = 0;
  9374. this.results = [];
  9375. }
  9376. return FulFillmentAgregator;
  9377. }());
  9378. var InternalPromise = /** @class */ (function () {
  9379. function InternalPromise(resolver) {
  9380. var _this = this;
  9381. this._state = PromiseStates.Pending;
  9382. this._children = new Array();
  9383. this._rejectWasConsumed = false;
  9384. if (!resolver) {
  9385. return;
  9386. }
  9387. try {
  9388. resolver(function (value) {
  9389. _this._resolve(value);
  9390. }, function (reason) {
  9391. _this._reject(reason);
  9392. });
  9393. }
  9394. catch (e) {
  9395. this._reject(e);
  9396. }
  9397. }
  9398. InternalPromise.prototype.catch = function (onRejected) {
  9399. return this.then(undefined, onRejected);
  9400. };
  9401. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9402. var _this = this;
  9403. var newPromise = new InternalPromise();
  9404. newPromise._onFulfilled = onFulfilled;
  9405. newPromise._onRejected = onRejected;
  9406. // Composition
  9407. this._children.push(newPromise);
  9408. if (this._state !== PromiseStates.Pending) {
  9409. BABYLON.Tools.SetImmediate(function () {
  9410. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9411. var returnedValue = newPromise._resolve(_this._result);
  9412. if (returnedValue !== undefined && returnedValue !== null) {
  9413. if (returnedValue._state !== undefined) {
  9414. var returnedPromise = returnedValue;
  9415. newPromise._children.push(returnedPromise);
  9416. newPromise = returnedPromise;
  9417. }
  9418. else {
  9419. newPromise._result = returnedValue;
  9420. }
  9421. }
  9422. }
  9423. else {
  9424. newPromise._reject(_this._reason);
  9425. }
  9426. });
  9427. }
  9428. return newPromise;
  9429. };
  9430. InternalPromise.prototype._moveChildren = function (children) {
  9431. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9432. if (this._state === PromiseStates.Fulfilled) {
  9433. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9434. var child = _b[_i];
  9435. child._resolve(this._result);
  9436. }
  9437. }
  9438. else if (this._state === PromiseStates.Rejected) {
  9439. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9440. var child = _d[_c];
  9441. child._reject(this._reason);
  9442. }
  9443. }
  9444. var _a;
  9445. };
  9446. InternalPromise.prototype._resolve = function (value) {
  9447. try {
  9448. this._state = PromiseStates.Fulfilled;
  9449. this._result = value;
  9450. var returnedValue = null;
  9451. if (this._onFulfilled) {
  9452. returnedValue = this._onFulfilled(value);
  9453. }
  9454. if (returnedValue !== undefined && returnedValue !== null) {
  9455. if (returnedValue._state !== undefined) {
  9456. // Transmit children
  9457. var returnedPromise = returnedValue;
  9458. returnedPromise._moveChildren(this._children);
  9459. }
  9460. else {
  9461. value = returnedValue;
  9462. }
  9463. }
  9464. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9465. var child = _a[_i];
  9466. child._resolve(value);
  9467. }
  9468. this._children.length = 0;
  9469. delete this._onFulfilled;
  9470. delete this._onRejected;
  9471. return returnedValue;
  9472. }
  9473. catch (e) {
  9474. this._reject(e, true);
  9475. }
  9476. return null;
  9477. };
  9478. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9479. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9480. this._state = PromiseStates.Rejected;
  9481. this._reason = reason;
  9482. if (this._onRejected && !onLocalThrow) {
  9483. try {
  9484. this._onRejected(reason);
  9485. this._rejectWasConsumed = true;
  9486. }
  9487. catch (e) {
  9488. reason = e;
  9489. }
  9490. }
  9491. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9492. var child = _a[_i];
  9493. if (this._rejectWasConsumed) {
  9494. child._resolve(null);
  9495. }
  9496. else {
  9497. child._reject(reason);
  9498. }
  9499. }
  9500. this._children.length = 0;
  9501. delete this._onFulfilled;
  9502. delete this._onRejected;
  9503. };
  9504. InternalPromise.resolve = function (value) {
  9505. var newPromise = new InternalPromise();
  9506. newPromise._resolve(value);
  9507. return newPromise;
  9508. };
  9509. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9510. promise.then(function (value) {
  9511. agregator.results[index] = value;
  9512. agregator.count++;
  9513. if (agregator.count === agregator.target) {
  9514. agregator.rootPromise._resolve(agregator.results);
  9515. }
  9516. return null;
  9517. }, function (reason) {
  9518. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9519. agregator.rootPromise._reject(reason);
  9520. }
  9521. });
  9522. };
  9523. InternalPromise.all = function (promises) {
  9524. var newPromise = new InternalPromise();
  9525. var agregator = new FulFillmentAgregator();
  9526. agregator.target = promises.length;
  9527. agregator.rootPromise = newPromise;
  9528. if (promises.length) {
  9529. for (var index = 0; index < promises.length; index++) {
  9530. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9531. }
  9532. }
  9533. else {
  9534. newPromise._resolve([]);
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.race = function (promises) {
  9539. var newPromise = new InternalPromise();
  9540. if (promises.length) {
  9541. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9542. var promise = promises_1[_i];
  9543. promise.then(function (value) {
  9544. if (newPromise) {
  9545. newPromise._resolve(value);
  9546. newPromise = null;
  9547. }
  9548. return null;
  9549. }, function (reason) {
  9550. if (newPromise) {
  9551. newPromise._reject(reason);
  9552. newPromise = null;
  9553. }
  9554. });
  9555. }
  9556. }
  9557. return newPromise;
  9558. };
  9559. return InternalPromise;
  9560. }());
  9561. /**
  9562. * Helper class that provides a small promise polyfill
  9563. */
  9564. var PromisePolyfill = /** @class */ (function () {
  9565. function PromisePolyfill() {
  9566. }
  9567. /**
  9568. * Static function used to check if the polyfill is required
  9569. * If this is the case then the function will inject the polyfill to window.Promise
  9570. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9571. */
  9572. PromisePolyfill.Apply = function (force) {
  9573. if (force === void 0) { force = false; }
  9574. if (force || typeof Promise === 'undefined') {
  9575. var root = window;
  9576. root.Promise = InternalPromise;
  9577. }
  9578. };
  9579. return PromisePolyfill;
  9580. }());
  9581. BABYLON.PromisePolyfill = PromisePolyfill;
  9582. })(BABYLON || (BABYLON = {}));
  9583. //# sourceMappingURL=babylon.promise.js.map
  9584. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. /**
  9588. * Helper class to push actions to a pool of workers.
  9589. */
  9590. var WorkerPool = /** @class */ (function () {
  9591. /**
  9592. * Constructor
  9593. * @param workers Array of workers to use for actions
  9594. */
  9595. function WorkerPool(workers) {
  9596. this._pendingActions = new Array();
  9597. this._workerInfos = workers.map(function (worker) { return ({
  9598. worker: worker,
  9599. active: false
  9600. }); });
  9601. }
  9602. /**
  9603. * Terminates all workers and clears any pending actions.
  9604. */
  9605. WorkerPool.prototype.dispose = function () {
  9606. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9607. var workerInfo = _a[_i];
  9608. workerInfo.worker.terminate();
  9609. }
  9610. delete this._workerInfos;
  9611. delete this._pendingActions;
  9612. };
  9613. /**
  9614. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9615. * pended until a worker has completed its action.
  9616. * @param action The action to perform. Call onComplete when the action is complete.
  9617. */
  9618. WorkerPool.prototype.push = function (action) {
  9619. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9620. var workerInfo = _a[_i];
  9621. if (!workerInfo.active) {
  9622. this._execute(workerInfo, action);
  9623. return;
  9624. }
  9625. }
  9626. this._pendingActions.push(action);
  9627. };
  9628. WorkerPool.prototype._execute = function (workerInfo, action) {
  9629. var _this = this;
  9630. workerInfo.active = true;
  9631. action(workerInfo.worker, function () {
  9632. workerInfo.active = false;
  9633. var nextAction = _this._pendingActions.shift();
  9634. if (nextAction) {
  9635. _this._execute(workerInfo, nextAction);
  9636. }
  9637. });
  9638. };
  9639. return WorkerPool;
  9640. }());
  9641. BABYLON.WorkerPool = WorkerPool;
  9642. })(BABYLON || (BABYLON = {}));
  9643. //# sourceMappingURL=babylon.workerPool.js.map
  9644. var BABYLON;
  9645. (function (BABYLON) {
  9646. var _AlphaState = /** @class */ (function () {
  9647. /**
  9648. * Initializes the state.
  9649. */
  9650. function _AlphaState() {
  9651. this._isAlphaBlendDirty = false;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. this._alphaBlend = false;
  9656. this._blendFunctionParameters = new Array(4);
  9657. this._blendEquationParameters = new Array(2);
  9658. this._blendConstants = new Array(4);
  9659. this.reset();
  9660. }
  9661. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9662. get: function () {
  9663. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9669. get: function () {
  9670. return this._alphaBlend;
  9671. },
  9672. set: function (value) {
  9673. if (this._alphaBlend === value) {
  9674. return;
  9675. }
  9676. this._alphaBlend = value;
  9677. this._isAlphaBlendDirty = true;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9683. if (this._blendConstants[0] === r &&
  9684. this._blendConstants[1] === g &&
  9685. this._blendConstants[2] === b &&
  9686. this._blendConstants[3] === a) {
  9687. return;
  9688. }
  9689. this._blendConstants[0] = r;
  9690. this._blendConstants[1] = g;
  9691. this._blendConstants[2] = b;
  9692. this._blendConstants[3] = a;
  9693. this._isBlendConstantsDirty = true;
  9694. };
  9695. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9696. if (this._blendFunctionParameters[0] === value0 &&
  9697. this._blendFunctionParameters[1] === value1 &&
  9698. this._blendFunctionParameters[2] === value2 &&
  9699. this._blendFunctionParameters[3] === value3) {
  9700. return;
  9701. }
  9702. this._blendFunctionParameters[0] = value0;
  9703. this._blendFunctionParameters[1] = value1;
  9704. this._blendFunctionParameters[2] = value2;
  9705. this._blendFunctionParameters[3] = value3;
  9706. this._isBlendFunctionParametersDirty = true;
  9707. };
  9708. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9709. if (this._blendEquationParameters[0] === rgb &&
  9710. this._blendEquationParameters[1] === alpha) {
  9711. return;
  9712. }
  9713. this._blendEquationParameters[0] = rgb;
  9714. this._blendEquationParameters[1] = alpha;
  9715. this._isBlendEquationParametersDirty = true;
  9716. };
  9717. _AlphaState.prototype.reset = function () {
  9718. this._alphaBlend = false;
  9719. this._blendFunctionParameters[0] = null;
  9720. this._blendFunctionParameters[1] = null;
  9721. this._blendFunctionParameters[2] = null;
  9722. this._blendFunctionParameters[3] = null;
  9723. this._blendEquationParameters[0] = null;
  9724. this._blendEquationParameters[1] = null;
  9725. this._blendConstants[0] = null;
  9726. this._blendConstants[1] = null;
  9727. this._blendConstants[2] = null;
  9728. this._blendConstants[3] = null;
  9729. this._isAlphaBlendDirty = true;
  9730. this._isBlendFunctionParametersDirty = false;
  9731. this._isBlendEquationParametersDirty = false;
  9732. this._isBlendConstantsDirty = false;
  9733. };
  9734. _AlphaState.prototype.apply = function (gl) {
  9735. if (!this.isDirty) {
  9736. return;
  9737. }
  9738. // Alpha blend
  9739. if (this._isAlphaBlendDirty) {
  9740. if (this._alphaBlend) {
  9741. gl.enable(gl.BLEND);
  9742. }
  9743. else {
  9744. gl.disable(gl.BLEND);
  9745. }
  9746. this._isAlphaBlendDirty = false;
  9747. }
  9748. // Alpha function
  9749. if (this._isBlendFunctionParametersDirty) {
  9750. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9751. this._isBlendFunctionParametersDirty = false;
  9752. }
  9753. // Alpha equation
  9754. if (this._isBlendEquationParametersDirty) {
  9755. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9756. this._isBlendEquationParametersDirty = false;
  9757. }
  9758. // Constants
  9759. if (this._isBlendConstantsDirty) {
  9760. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9761. this._isBlendConstantsDirty = false;
  9762. }
  9763. };
  9764. return _AlphaState;
  9765. }());
  9766. BABYLON._AlphaState = _AlphaState;
  9767. })(BABYLON || (BABYLON = {}));
  9768. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9769. var BABYLON;
  9770. (function (BABYLON) {
  9771. var _DepthCullingState = /** @class */ (function () {
  9772. /**
  9773. * Initializes the state.
  9774. */
  9775. function _DepthCullingState() {
  9776. this._isDepthTestDirty = false;
  9777. this._isDepthMaskDirty = false;
  9778. this._isDepthFuncDirty = false;
  9779. this._isCullFaceDirty = false;
  9780. this._isCullDirty = false;
  9781. this._isZOffsetDirty = false;
  9782. this._isFrontFaceDirty = false;
  9783. this.reset();
  9784. }
  9785. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9786. get: function () {
  9787. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9793. get: function () {
  9794. return this._zOffset;
  9795. },
  9796. set: function (value) {
  9797. if (this._zOffset === value) {
  9798. return;
  9799. }
  9800. this._zOffset = value;
  9801. this._isZOffsetDirty = true;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9807. get: function () {
  9808. return this._cullFace;
  9809. },
  9810. set: function (value) {
  9811. if (this._cullFace === value) {
  9812. return;
  9813. }
  9814. this._cullFace = value;
  9815. this._isCullFaceDirty = true;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9821. get: function () {
  9822. return this._cull;
  9823. },
  9824. set: function (value) {
  9825. if (this._cull === value) {
  9826. return;
  9827. }
  9828. this._cull = value;
  9829. this._isCullDirty = true;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9835. get: function () {
  9836. return this._depthFunc;
  9837. },
  9838. set: function (value) {
  9839. if (this._depthFunc === value) {
  9840. return;
  9841. }
  9842. this._depthFunc = value;
  9843. this._isDepthFuncDirty = true;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9849. get: function () {
  9850. return this._depthMask;
  9851. },
  9852. set: function (value) {
  9853. if (this._depthMask === value) {
  9854. return;
  9855. }
  9856. this._depthMask = value;
  9857. this._isDepthMaskDirty = true;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9863. get: function () {
  9864. return this._depthTest;
  9865. },
  9866. set: function (value) {
  9867. if (this._depthTest === value) {
  9868. return;
  9869. }
  9870. this._depthTest = value;
  9871. this._isDepthTestDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9877. get: function () {
  9878. return this._frontFace;
  9879. },
  9880. set: function (value) {
  9881. if (this._frontFace === value) {
  9882. return;
  9883. }
  9884. this._frontFace = value;
  9885. this._isFrontFaceDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. _DepthCullingState.prototype.reset = function () {
  9891. this._depthMask = true;
  9892. this._depthTest = true;
  9893. this._depthFunc = null;
  9894. this._cullFace = null;
  9895. this._cull = null;
  9896. this._zOffset = 0;
  9897. this._frontFace = null;
  9898. this._isDepthTestDirty = true;
  9899. this._isDepthMaskDirty = true;
  9900. this._isDepthFuncDirty = false;
  9901. this._isCullFaceDirty = false;
  9902. this._isCullDirty = false;
  9903. this._isZOffsetDirty = false;
  9904. this._isFrontFaceDirty = false;
  9905. };
  9906. _DepthCullingState.prototype.apply = function (gl) {
  9907. if (!this.isDirty) {
  9908. return;
  9909. }
  9910. // Cull
  9911. if (this._isCullDirty) {
  9912. if (this.cull) {
  9913. gl.enable(gl.CULL_FACE);
  9914. }
  9915. else {
  9916. gl.disable(gl.CULL_FACE);
  9917. }
  9918. this._isCullDirty = false;
  9919. }
  9920. // Cull face
  9921. if (this._isCullFaceDirty) {
  9922. gl.cullFace(this.cullFace);
  9923. this._isCullFaceDirty = false;
  9924. }
  9925. // Depth mask
  9926. if (this._isDepthMaskDirty) {
  9927. gl.depthMask(this.depthMask);
  9928. this._isDepthMaskDirty = false;
  9929. }
  9930. // Depth test
  9931. if (this._isDepthTestDirty) {
  9932. if (this.depthTest) {
  9933. gl.enable(gl.DEPTH_TEST);
  9934. }
  9935. else {
  9936. gl.disable(gl.DEPTH_TEST);
  9937. }
  9938. this._isDepthTestDirty = false;
  9939. }
  9940. // Depth func
  9941. if (this._isDepthFuncDirty) {
  9942. gl.depthFunc(this.depthFunc);
  9943. this._isDepthFuncDirty = false;
  9944. }
  9945. // zOffset
  9946. if (this._isZOffsetDirty) {
  9947. if (this.zOffset) {
  9948. gl.enable(gl.POLYGON_OFFSET_FILL);
  9949. gl.polygonOffset(this.zOffset, 0);
  9950. }
  9951. else {
  9952. gl.disable(gl.POLYGON_OFFSET_FILL);
  9953. }
  9954. this._isZOffsetDirty = false;
  9955. }
  9956. // Front face
  9957. if (this._isFrontFaceDirty) {
  9958. gl.frontFace(this.frontFace);
  9959. this._isFrontFaceDirty = false;
  9960. }
  9961. };
  9962. return _DepthCullingState;
  9963. }());
  9964. BABYLON._DepthCullingState = _DepthCullingState;
  9965. })(BABYLON || (BABYLON = {}));
  9966. //# sourceMappingURL=babylon.depthCullingState.js.map
  9967. var BABYLON;
  9968. (function (BABYLON) {
  9969. var _StencilState = /** @class */ (function () {
  9970. function _StencilState() {
  9971. this._isStencilTestDirty = false;
  9972. this._isStencilMaskDirty = false;
  9973. this._isStencilFuncDirty = false;
  9974. this._isStencilOpDirty = false;
  9975. this.reset();
  9976. }
  9977. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9978. get: function () {
  9979. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9985. get: function () {
  9986. return this._stencilFunc;
  9987. },
  9988. set: function (value) {
  9989. if (this._stencilFunc === value) {
  9990. return;
  9991. }
  9992. this._stencilFunc = value;
  9993. this._isStencilFuncDirty = true;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9999. get: function () {
  10000. return this._stencilFuncRef;
  10001. },
  10002. set: function (value) {
  10003. if (this._stencilFuncRef === value) {
  10004. return;
  10005. }
  10006. this._stencilFuncRef = value;
  10007. this._isStencilFuncDirty = true;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10013. get: function () {
  10014. return this._stencilFuncMask;
  10015. },
  10016. set: function (value) {
  10017. if (this._stencilFuncMask === value) {
  10018. return;
  10019. }
  10020. this._stencilFuncMask = value;
  10021. this._isStencilFuncDirty = true;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10027. get: function () {
  10028. return this._stencilOpStencilFail;
  10029. },
  10030. set: function (value) {
  10031. if (this._stencilOpStencilFail === value) {
  10032. return;
  10033. }
  10034. this._stencilOpStencilFail = value;
  10035. this._isStencilOpDirty = true;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10041. get: function () {
  10042. return this._stencilOpDepthFail;
  10043. },
  10044. set: function (value) {
  10045. if (this._stencilOpDepthFail === value) {
  10046. return;
  10047. }
  10048. this._stencilOpDepthFail = value;
  10049. this._isStencilOpDirty = true;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10055. get: function () {
  10056. return this._stencilOpStencilDepthPass;
  10057. },
  10058. set: function (value) {
  10059. if (this._stencilOpStencilDepthPass === value) {
  10060. return;
  10061. }
  10062. this._stencilOpStencilDepthPass = value;
  10063. this._isStencilOpDirty = true;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10069. get: function () {
  10070. return this._stencilMask;
  10071. },
  10072. set: function (value) {
  10073. if (this._stencilMask === value) {
  10074. return;
  10075. }
  10076. this._stencilMask = value;
  10077. this._isStencilMaskDirty = true;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10083. get: function () {
  10084. return this._stencilTest;
  10085. },
  10086. set: function (value) {
  10087. if (this._stencilTest === value) {
  10088. return;
  10089. }
  10090. this._stencilTest = value;
  10091. this._isStencilTestDirty = true;
  10092. },
  10093. enumerable: true,
  10094. configurable: true
  10095. });
  10096. _StencilState.prototype.reset = function () {
  10097. this._stencilTest = false;
  10098. this._stencilMask = 0xFF;
  10099. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10100. this._stencilFuncRef = 1;
  10101. this._stencilFuncMask = 0xFF;
  10102. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10103. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10104. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10105. this._isStencilTestDirty = true;
  10106. this._isStencilMaskDirty = true;
  10107. this._isStencilFuncDirty = true;
  10108. this._isStencilOpDirty = true;
  10109. };
  10110. _StencilState.prototype.apply = function (gl) {
  10111. if (!this.isDirty) {
  10112. return;
  10113. }
  10114. // Stencil test
  10115. if (this._isStencilTestDirty) {
  10116. if (this.stencilTest) {
  10117. gl.enable(gl.STENCIL_TEST);
  10118. }
  10119. else {
  10120. gl.disable(gl.STENCIL_TEST);
  10121. }
  10122. this._isStencilTestDirty = false;
  10123. }
  10124. // Stencil mask
  10125. if (this._isStencilMaskDirty) {
  10126. gl.stencilMask(this.stencilMask);
  10127. this._isStencilMaskDirty = false;
  10128. }
  10129. // Stencil func
  10130. if (this._isStencilFuncDirty) {
  10131. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10132. this._isStencilFuncDirty = false;
  10133. }
  10134. // Stencil op
  10135. if (this._isStencilOpDirty) {
  10136. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10137. this._isStencilOpDirty = false;
  10138. }
  10139. };
  10140. return _StencilState;
  10141. }());
  10142. BABYLON._StencilState = _StencilState;
  10143. })(BABYLON || (BABYLON = {}));
  10144. //# sourceMappingURL=babylon.stencilState.js.map
  10145. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10146. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10147. s = arguments[i];
  10148. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10149. t[p] = s[p];
  10150. }
  10151. return t;
  10152. };
  10153. var BABYLON;
  10154. (function (BABYLON) {
  10155. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10156. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10157. };
  10158. var compileRawShader = function (gl, source, type) {
  10159. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10160. gl.shaderSource(shader, source);
  10161. gl.compileShader(shader);
  10162. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10163. var log = gl.getShaderInfoLog(shader);
  10164. if (log) {
  10165. throw new Error(log);
  10166. }
  10167. }
  10168. if (!shader) {
  10169. throw new Error("Something went wrong while compile the shader.");
  10170. }
  10171. return shader;
  10172. };
  10173. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10174. var magFilter = gl.NEAREST;
  10175. var minFilter = gl.NEAREST;
  10176. switch (samplingMode) {
  10177. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10178. magFilter = gl.LINEAR;
  10179. if (generateMipMaps) {
  10180. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10181. }
  10182. else {
  10183. minFilter = gl.LINEAR;
  10184. }
  10185. break;
  10186. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10187. magFilter = gl.LINEAR;
  10188. if (generateMipMaps) {
  10189. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10190. }
  10191. else {
  10192. minFilter = gl.LINEAR;
  10193. }
  10194. break;
  10195. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10196. magFilter = gl.NEAREST;
  10197. if (generateMipMaps) {
  10198. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10199. }
  10200. else {
  10201. minFilter = gl.NEAREST;
  10202. }
  10203. break;
  10204. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10205. magFilter = gl.NEAREST;
  10206. if (generateMipMaps) {
  10207. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10208. }
  10209. else {
  10210. minFilter = gl.NEAREST;
  10211. }
  10212. break;
  10213. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10214. magFilter = gl.NEAREST;
  10215. if (generateMipMaps) {
  10216. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10217. }
  10218. else {
  10219. minFilter = gl.LINEAR;
  10220. }
  10221. break;
  10222. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10223. magFilter = gl.NEAREST;
  10224. if (generateMipMaps) {
  10225. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10226. }
  10227. else {
  10228. minFilter = gl.LINEAR;
  10229. }
  10230. break;
  10231. case BABYLON.Texture.NEAREST_LINEAR:
  10232. magFilter = gl.NEAREST;
  10233. minFilter = gl.LINEAR;
  10234. break;
  10235. case BABYLON.Texture.NEAREST_NEAREST:
  10236. magFilter = gl.NEAREST;
  10237. minFilter = gl.NEAREST;
  10238. break;
  10239. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10240. magFilter = gl.LINEAR;
  10241. if (generateMipMaps) {
  10242. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10243. }
  10244. else {
  10245. minFilter = gl.NEAREST;
  10246. }
  10247. break;
  10248. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10249. magFilter = gl.LINEAR;
  10250. if (generateMipMaps) {
  10251. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10252. }
  10253. else {
  10254. minFilter = gl.NEAREST;
  10255. }
  10256. break;
  10257. case BABYLON.Texture.LINEAR_LINEAR:
  10258. magFilter = gl.LINEAR;
  10259. minFilter = gl.LINEAR;
  10260. break;
  10261. case BABYLON.Texture.LINEAR_NEAREST:
  10262. magFilter = gl.LINEAR;
  10263. minFilter = gl.NEAREST;
  10264. break;
  10265. }
  10266. return {
  10267. min: minFilter,
  10268. mag: magFilter
  10269. };
  10270. };
  10271. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10272. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10273. var img;
  10274. var onload = function () {
  10275. loadedImages[index] = img;
  10276. loadedImages._internalCount++;
  10277. if (scene) {
  10278. scene._removePendingData(img);
  10279. }
  10280. if (loadedImages._internalCount === 6) {
  10281. onfinish(loadedImages);
  10282. }
  10283. };
  10284. var onerror = function (message, exception) {
  10285. if (scene) {
  10286. scene._removePendingData(img);
  10287. }
  10288. if (onErrorCallBack) {
  10289. onErrorCallBack(message, exception);
  10290. }
  10291. };
  10292. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10293. if (scene) {
  10294. scene._addPendingData(img);
  10295. }
  10296. };
  10297. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10298. if (onError === void 0) { onError = null; }
  10299. var loadedImages = [];
  10300. loadedImages._internalCount = 0;
  10301. for (var index = 0; index < 6; index++) {
  10302. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10303. }
  10304. };
  10305. var BufferPointer = /** @class */ (function () {
  10306. function BufferPointer() {
  10307. }
  10308. return BufferPointer;
  10309. }());
  10310. var InstancingAttributeInfo = /** @class */ (function () {
  10311. function InstancingAttributeInfo() {
  10312. }
  10313. return InstancingAttributeInfo;
  10314. }());
  10315. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10316. /**
  10317. * Define options used to create a render target texture
  10318. */
  10319. var RenderTargetCreationOptions = /** @class */ (function () {
  10320. function RenderTargetCreationOptions() {
  10321. }
  10322. return RenderTargetCreationOptions;
  10323. }());
  10324. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10325. /**
  10326. * Define options used to create a depth texture
  10327. */
  10328. var DepthTextureCreationOptions = /** @class */ (function () {
  10329. function DepthTextureCreationOptions() {
  10330. }
  10331. return DepthTextureCreationOptions;
  10332. }());
  10333. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10334. /**
  10335. * Regroup several parameters relative to the browser in use
  10336. */
  10337. var EngineCapabilities = /** @class */ (function () {
  10338. function EngineCapabilities() {
  10339. }
  10340. return EngineCapabilities;
  10341. }());
  10342. BABYLON.EngineCapabilities = EngineCapabilities;
  10343. /**
  10344. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10345. */
  10346. var Engine = /** @class */ (function () {
  10347. /**
  10348. * @constructor
  10349. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10350. * @param antialias defines enable antialiasing (default: false)
  10351. * @param options defines further options to be sent to the getContext() function
  10352. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10353. */
  10354. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10355. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10356. var _this = this;
  10357. // Public members
  10358. this.forcePOTTextures = false;
  10359. this.isFullscreen = false;
  10360. this.isPointerLock = false;
  10361. this.cullBackFaces = true;
  10362. this.renderEvenInBackground = true;
  10363. this.preventCacheWipeBetweenFrames = false;
  10364. // To enable/disable IDB support and avoid XHR on .manifest
  10365. this.enableOfflineSupport = false;
  10366. this.scenes = new Array();
  10367. this.postProcesses = new Array();
  10368. // Observables
  10369. /**
  10370. * Observable event triggered each time the rendering canvas is resized
  10371. */
  10372. this.onResizeObservable = new BABYLON.Observable();
  10373. /**
  10374. * Observable event triggered each time the canvas loses focus
  10375. */
  10376. this.onCanvasBlurObservable = new BABYLON.Observable();
  10377. /**
  10378. * Observable event triggered each time the canvas gains focus
  10379. */
  10380. this.onCanvasFocusObservable = new BABYLON.Observable();
  10381. /**
  10382. * Observable event triggered each time the canvas receives pointerout event
  10383. */
  10384. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10385. /**
  10386. * Observable event triggered before each texture is initialized
  10387. */
  10388. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10389. //WebVR
  10390. this._vrDisplay = undefined;
  10391. this._vrSupported = false;
  10392. this._vrExclusivePointerMode = false;
  10393. // Uniform buffers list
  10394. this.disableUniformBuffers = false;
  10395. this._uniformBuffers = new Array();
  10396. // Observables
  10397. /**
  10398. * Observable raised when the engine begins a new frame
  10399. */
  10400. this.onBeginFrameObservable = new BABYLON.Observable();
  10401. /**
  10402. * Observable raised when the engine ends the current frame
  10403. */
  10404. this.onEndFrameObservable = new BABYLON.Observable();
  10405. /**
  10406. * Observable raised when the engine is about to compile a shader
  10407. */
  10408. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10409. /**
  10410. * Observable raised when the engine has jsut compiled a shader
  10411. */
  10412. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10413. this._windowIsBackground = false;
  10414. this._webGLVersion = 1.0;
  10415. this._badOS = false;
  10416. this._badDesktopOS = false;
  10417. /**
  10418. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10419. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10420. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10421. */
  10422. this.disableTextureBindingOptimization = false;
  10423. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10424. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10425. this.onVRRequestPresentStart = new BABYLON.Observable();
  10426. this._colorWrite = true;
  10427. this._drawCalls = new BABYLON.PerfCounter();
  10428. this._textureCollisions = new BABYLON.PerfCounter();
  10429. this._renderingQueueLaunched = false;
  10430. this._activeRenderLoops = new Array();
  10431. // Deterministic lockstepMaxSteps
  10432. this._deterministicLockstep = false;
  10433. this._lockstepMaxSteps = 4;
  10434. // Lost context
  10435. this.onContextLostObservable = new BABYLON.Observable();
  10436. this.onContextRestoredObservable = new BABYLON.Observable();
  10437. this._contextWasLost = false;
  10438. this._doNotHandleContextLost = false;
  10439. // FPS
  10440. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10441. this._fps = 60;
  10442. this._deltaTime = 0;
  10443. /**
  10444. * Turn this value on if you want to pause FPS computation when in background
  10445. */
  10446. this.disablePerformanceMonitorInBackground = false;
  10447. // States
  10448. this._depthCullingState = new BABYLON._DepthCullingState();
  10449. this._stencilState = new BABYLON._StencilState();
  10450. this._alphaState = new BABYLON._AlphaState();
  10451. this._alphaMode = Engine.ALPHA_DISABLE;
  10452. // Cache
  10453. this._internalTexturesCache = new Array();
  10454. this._activeChannel = 0;
  10455. this._currentTextureChannel = -1;
  10456. this._boundTexturesCache = {};
  10457. this._compiledEffects = {};
  10458. this._vertexAttribArraysEnabled = [];
  10459. this._uintIndicesCurrentlySet = false;
  10460. this._currentBoundBuffer = new Array();
  10461. this._currentBufferPointers = new Array();
  10462. this._currentInstanceLocations = new Array();
  10463. this._currentInstanceBuffers = new Array();
  10464. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10465. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10466. this._vaoRecordInProgress = false;
  10467. this._mustWipeVertexAttributes = false;
  10468. this._nextFreeTextureSlots = new Array();
  10469. this._maxSimultaneousTextures = 0;
  10470. this._activeRequests = new Array();
  10471. // Hardware supported Compressed Textures
  10472. this._texturesSupported = new Array();
  10473. this._onVRFullScreenTriggered = function () {
  10474. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10475. //get the old size before we change
  10476. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10477. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10478. //get the width and height, change the render size
  10479. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10480. _this.setHardwareScalingLevel(1);
  10481. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10482. }
  10483. else {
  10484. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10485. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10486. }
  10487. };
  10488. this._boundUniforms = {};
  10489. // Register promises
  10490. BABYLON.PromisePolyfill.Apply();
  10491. var canvas = null;
  10492. Engine.Instances.push(this);
  10493. if (!canvasOrContext) {
  10494. return;
  10495. }
  10496. options = options || {};
  10497. if (canvasOrContext.getContext) {
  10498. canvas = canvasOrContext;
  10499. this._renderingCanvas = canvas;
  10500. if (antialias != null) {
  10501. options.antialias = antialias;
  10502. }
  10503. if (options.deterministicLockstep === undefined) {
  10504. options.deterministicLockstep = false;
  10505. }
  10506. if (options.lockstepMaxSteps === undefined) {
  10507. options.lockstepMaxSteps = 4;
  10508. }
  10509. if (options.preserveDrawingBuffer === undefined) {
  10510. options.preserveDrawingBuffer = false;
  10511. }
  10512. if (options.audioEngine === undefined) {
  10513. options.audioEngine = true;
  10514. }
  10515. if (options.stencil === undefined) {
  10516. options.stencil = true;
  10517. }
  10518. this._deterministicLockstep = options.deterministicLockstep;
  10519. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10520. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10521. // Exceptions
  10522. if (navigator && navigator.userAgent) {
  10523. var ua = navigator.userAgent;
  10524. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10525. var exception = _a[_i];
  10526. var key = exception.key;
  10527. var targets = exception.targets;
  10528. if (ua.indexOf(key) > -1) {
  10529. if (exception.capture && exception.captureConstraint) {
  10530. var capture = exception.capture;
  10531. var constraint = exception.captureConstraint;
  10532. var regex = new RegExp(capture);
  10533. var matches = regex.exec(ua);
  10534. if (matches && matches.length > 0) {
  10535. var capturedValue = parseInt(matches[matches.length - 1]);
  10536. if (capturedValue >= constraint) {
  10537. continue;
  10538. }
  10539. }
  10540. }
  10541. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10542. var target = targets_1[_b];
  10543. switch (target) {
  10544. case "uniformBuffer":
  10545. this.disableUniformBuffers = true;
  10546. break;
  10547. case "textureBindingOptimization":
  10548. this.disableTextureBindingOptimization = true;
  10549. break;
  10550. }
  10551. }
  10552. }
  10553. }
  10554. }
  10555. // GL
  10556. if (!options.disableWebGL2Support) {
  10557. try {
  10558. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10559. if (this._gl) {
  10560. this._webGLVersion = 2.0;
  10561. }
  10562. }
  10563. catch (e) {
  10564. // Do nothing
  10565. }
  10566. }
  10567. if (!this._gl) {
  10568. if (!canvas) {
  10569. throw new Error("The provided canvas is null or undefined.");
  10570. }
  10571. try {
  10572. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10573. }
  10574. catch (e) {
  10575. throw new Error("WebGL not supported");
  10576. }
  10577. }
  10578. if (!this._gl) {
  10579. throw new Error("WebGL not supported");
  10580. }
  10581. this._onCanvasFocus = function () {
  10582. _this.onCanvasFocusObservable.notifyObservers(_this);
  10583. };
  10584. this._onCanvasBlur = function () {
  10585. _this.onCanvasBlurObservable.notifyObservers(_this);
  10586. };
  10587. canvas.addEventListener("focus", this._onCanvasFocus);
  10588. canvas.addEventListener("blur", this._onCanvasBlur);
  10589. this._onBlur = function () {
  10590. if (_this.disablePerformanceMonitorInBackground) {
  10591. _this._performanceMonitor.disable();
  10592. }
  10593. _this._windowIsBackground = true;
  10594. };
  10595. this._onFocus = function () {
  10596. if (_this.disablePerformanceMonitorInBackground) {
  10597. _this._performanceMonitor.enable();
  10598. }
  10599. _this._windowIsBackground = false;
  10600. };
  10601. this._onCanvasPointerOut = function (ev) {
  10602. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10603. };
  10604. window.addEventListener("blur", this._onBlur);
  10605. window.addEventListener("focus", this._onFocus);
  10606. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10607. // Context lost
  10608. if (!this._doNotHandleContextLost) {
  10609. this._onContextLost = function (evt) {
  10610. evt.preventDefault();
  10611. _this._contextWasLost = true;
  10612. BABYLON.Tools.Warn("WebGL context lost.");
  10613. _this.onContextLostObservable.notifyObservers(_this);
  10614. };
  10615. this._onContextRestored = function (evt) {
  10616. // Adding a timeout to avoid race condition at browser level
  10617. setTimeout(function () {
  10618. // Rebuild gl context
  10619. _this._initGLContext();
  10620. // Rebuild effects
  10621. _this._rebuildEffects();
  10622. // Rebuild textures
  10623. _this._rebuildInternalTextures();
  10624. // Rebuild buffers
  10625. _this._rebuildBuffers();
  10626. // Cache
  10627. _this.wipeCaches(true);
  10628. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10629. _this.onContextRestoredObservable.notifyObservers(_this);
  10630. _this._contextWasLost = false;
  10631. }, 0);
  10632. };
  10633. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10634. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10635. }
  10636. }
  10637. else {
  10638. this._gl = canvasOrContext;
  10639. this._renderingCanvas = this._gl.canvas;
  10640. if (this._gl.renderbufferStorageMultisample) {
  10641. this._webGLVersion = 2.0;
  10642. }
  10643. options.stencil = this._gl.getContextAttributes().stencil;
  10644. }
  10645. // Viewport
  10646. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10647. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10648. this.resize();
  10649. this._isStencilEnable = options.stencil ? true : false;
  10650. this._initGLContext();
  10651. if (canvas) {
  10652. // Fullscreen
  10653. this._onFullscreenChange = function () {
  10654. if (document.fullscreen !== undefined) {
  10655. _this.isFullscreen = document.fullscreen;
  10656. }
  10657. else if (document.mozFullScreen !== undefined) {
  10658. _this.isFullscreen = document.mozFullScreen;
  10659. }
  10660. else if (document.webkitIsFullScreen !== undefined) {
  10661. _this.isFullscreen = document.webkitIsFullScreen;
  10662. }
  10663. else if (document.msIsFullScreen !== undefined) {
  10664. _this.isFullscreen = document.msIsFullScreen;
  10665. }
  10666. // Pointer lock
  10667. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10668. canvas.requestPointerLock = canvas.requestPointerLock ||
  10669. canvas.msRequestPointerLock ||
  10670. canvas.mozRequestPointerLock ||
  10671. canvas.webkitRequestPointerLock;
  10672. if (canvas.requestPointerLock) {
  10673. canvas.requestPointerLock();
  10674. }
  10675. }
  10676. };
  10677. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10678. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10679. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10680. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10681. // Pointer lock
  10682. this._onPointerLockChange = function () {
  10683. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10684. document.webkitPointerLockElement === canvas ||
  10685. document.msPointerLockElement === canvas ||
  10686. document.pointerLockElement === canvas);
  10687. };
  10688. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10689. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10690. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10691. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10692. this._onVRDisplayPointerRestricted = function () {
  10693. if (canvas) {
  10694. canvas.requestPointerLock();
  10695. }
  10696. };
  10697. this._onVRDisplayPointerUnrestricted = function () {
  10698. document.exitPointerLock();
  10699. };
  10700. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10701. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10702. }
  10703. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10704. Engine.audioEngine = new BABYLON.AudioEngine();
  10705. }
  10706. // Prepare buffer pointers
  10707. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10708. this._currentBufferPointers[i] = new BufferPointer();
  10709. }
  10710. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10711. // Load WebVR Devices
  10712. if (options.autoEnableWebVR) {
  10713. this.initWebVR();
  10714. }
  10715. // Detect if we are running on a faulty buggy OS.
  10716. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10717. // Detect if we are running on a faulty buggy desktop OS.
  10718. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10719. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10720. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10721. }
  10722. Object.defineProperty(Engine, "LastCreatedEngine", {
  10723. get: function () {
  10724. if (Engine.Instances.length === 0) {
  10725. return null;
  10726. }
  10727. return Engine.Instances[Engine.Instances.length - 1];
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "LastCreatedScene", {
  10733. get: function () {
  10734. var lastCreatedEngine = Engine.LastCreatedEngine;
  10735. if (!lastCreatedEngine) {
  10736. return null;
  10737. }
  10738. if (lastCreatedEngine.scenes.length === 0) {
  10739. return null;
  10740. }
  10741. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. /**
  10747. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10748. */
  10749. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10750. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10751. var engine = Engine.Instances[engineIndex];
  10752. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10753. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10754. }
  10755. }
  10756. };
  10757. Object.defineProperty(Engine, "NEVER", {
  10758. get: function () {
  10759. return Engine._NEVER;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "ALWAYS", {
  10765. get: function () {
  10766. return Engine._ALWAYS;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "LESS", {
  10772. get: function () {
  10773. return Engine._LESS;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "EQUAL", {
  10779. get: function () {
  10780. return Engine._EQUAL;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "LEQUAL", {
  10786. get: function () {
  10787. return Engine._LEQUAL;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "GREATER", {
  10793. get: function () {
  10794. return Engine._GREATER;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "GEQUAL", {
  10800. get: function () {
  10801. return Engine._GEQUAL;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "NOTEQUAL", {
  10807. get: function () {
  10808. return Engine._NOTEQUAL;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "KEEP", {
  10814. get: function () {
  10815. return Engine._KEEP;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "REPLACE", {
  10821. get: function () {
  10822. return Engine._REPLACE;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "INCR", {
  10828. get: function () {
  10829. return Engine._INCR;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "DECR", {
  10835. get: function () {
  10836. return Engine._DECR;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "INVERT", {
  10842. get: function () {
  10843. return Engine._INVERT;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "INCR_WRAP", {
  10849. get: function () {
  10850. return Engine._INCR_WRAP;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "DECR_WRAP", {
  10856. get: function () {
  10857. return Engine._DECR_WRAP;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10863. get: function () {
  10864. return Engine._ALPHA_DISABLE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10870. get: function () {
  10871. return Engine._ALPHA_ONEONE;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "ALPHA_ADD", {
  10877. get: function () {
  10878. return Engine._ALPHA_ADD;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10884. get: function () {
  10885. return Engine._ALPHA_COMBINE;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10891. get: function () {
  10892. return Engine._ALPHA_SUBTRACT;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10898. get: function () {
  10899. return Engine._ALPHA_MULTIPLY;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10905. get: function () {
  10906. return Engine._ALPHA_MAXIMIZED;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10912. get: function () {
  10913. return Engine._ALPHA_PREMULTIPLIED;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10919. get: function () {
  10920. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10926. get: function () {
  10927. return Engine._ALPHA_INTERPOLATE;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10933. get: function () {
  10934. return Engine._ALPHA_SCREENMODE;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10940. get: function () {
  10941. return Engine._DELAYLOADSTATE_NONE;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10947. get: function () {
  10948. return Engine._DELAYLOADSTATE_LOADED;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10954. get: function () {
  10955. return Engine._DELAYLOADSTATE_LOADING;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10961. get: function () {
  10962. return Engine._DELAYLOADSTATE_NOTLOADED;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10968. get: function () {
  10969. return Engine._TEXTUREFORMAT_ALPHA;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10975. get: function () {
  10976. return Engine._TEXTUREFORMAT_LUMINANCE;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10982. /**
  10983. * R32F
  10984. */
  10985. get: function () {
  10986. return Engine._TEXTUREFORMAT_R32F;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10992. /**
  10993. * RG32F
  10994. */
  10995. get: function () {
  10996. return Engine._TEXTUREFORMAT_RG32F;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11002. /**
  11003. * RGB32F
  11004. */
  11005. get: function () {
  11006. return Engine._TEXTUREFORMAT_RGB32F;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11012. /**
  11013. * RGBA32F
  11014. */
  11015. get: function () {
  11016. return Engine._TEXTUREFORMAT_RGBA32F;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11022. get: function () {
  11023. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11029. get: function () {
  11030. return Engine._TEXTUREFORMAT_RGB;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11036. get: function () {
  11037. return Engine._TEXTUREFORMAT_RGBA;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11043. get: function () {
  11044. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11050. get: function () {
  11051. return Engine._TEXTURETYPE_FLOAT;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11057. get: function () {
  11058. return Engine._TEXTURETYPE_HALF_FLOAT;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11064. get: function () {
  11065. return Engine._SCALEMODE_FLOOR;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11071. get: function () {
  11072. return Engine._SCALEMODE_NEAREST;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11078. get: function () {
  11079. return Engine._SCALEMODE_CEILING;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine, "Version", {
  11085. get: function () {
  11086. return "3.2.0-alphaB";
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11092. get: function () {
  11093. return this._vrExclusivePointerMode;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11099. get: function () {
  11100. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11106. get: function () {
  11107. return this._webGLVersion < 2 || this.forcePOTTextures;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine.prototype, "badOS", {
  11113. get: function () {
  11114. return this._badOS;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11120. get: function () {
  11121. return this._badDesktopOS;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11127. get: function () {
  11128. return this._performanceMonitor;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11134. get: function () {
  11135. return this._texturesSupported;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11141. get: function () {
  11142. return this._textureFormatInUse;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine.prototype, "currentViewport", {
  11148. get: function () {
  11149. return this._cachedViewport;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11155. // Empty texture
  11156. get: function () {
  11157. if (!this._emptyTexture) {
  11158. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11159. }
  11160. return this._emptyTexture;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11166. get: function () {
  11167. if (!this._emptyTexture3D) {
  11168. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11169. }
  11170. return this._emptyTexture3D;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11176. get: function () {
  11177. if (!this._emptyCubeTexture) {
  11178. var faceData = new Uint8Array(4);
  11179. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11180. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11181. }
  11182. return this._emptyCubeTexture;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Engine.prototype._rebuildInternalTextures = function () {
  11188. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11189. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11190. var internalTexture = currentState_1[_i];
  11191. internalTexture._rebuild();
  11192. }
  11193. };
  11194. Engine.prototype._rebuildEffects = function () {
  11195. for (var key in this._compiledEffects) {
  11196. var effect = this._compiledEffects[key];
  11197. effect._prepareEffect();
  11198. }
  11199. BABYLON.Effect.ResetCache();
  11200. };
  11201. Engine.prototype._rebuildBuffers = function () {
  11202. // Index / Vertex
  11203. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11204. var scene = _a[_i];
  11205. scene.resetCachedMaterial();
  11206. scene._rebuildGeometries();
  11207. scene._rebuildTextures();
  11208. }
  11209. // Uniforms
  11210. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11211. var uniformBuffer = _c[_b];
  11212. uniformBuffer._rebuild();
  11213. }
  11214. };
  11215. Engine.prototype._initGLContext = function () {
  11216. // Caps
  11217. this._caps = new EngineCapabilities();
  11218. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11219. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11220. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11221. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11222. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11223. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11224. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11225. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11226. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11227. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11228. // Infos
  11229. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11230. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11231. if (rendererInfo != null) {
  11232. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11233. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11234. }
  11235. if (!this._glVendor) {
  11236. this._glVendor = "Unknown vendor";
  11237. }
  11238. if (!this._glRenderer) {
  11239. this._glRenderer = "Unknown renderer";
  11240. }
  11241. // Constants
  11242. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11243. if (this._gl.RGBA16F !== 0x881A) {
  11244. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11245. }
  11246. if (this._gl.RGBA32F !== 0x8814) {
  11247. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11248. }
  11249. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11250. this._gl.DEPTH24_STENCIL8 = 35056;
  11251. }
  11252. // Extensions
  11253. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11254. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11255. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11256. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11257. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11258. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11259. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11260. 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');
  11261. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11262. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11263. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11264. this._caps.highPrecisionShaderSupported = true;
  11265. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11266. if (this._caps.timerQuery) {
  11267. if (this._webGLVersion === 1) {
  11268. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11269. }
  11270. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11271. }
  11272. // Checks if some of the format renders first to allow the use of webgl inspector.
  11273. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11274. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11275. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11276. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11277. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11278. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11279. if (this._webGLVersion > 1) {
  11280. this._gl.HALF_FLOAT_OES = 0x140B;
  11281. }
  11282. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11283. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11284. // Draw buffers
  11285. if (this._webGLVersion > 1) {
  11286. this._caps.drawBuffersExtension = true;
  11287. }
  11288. else {
  11289. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11290. if (drawBuffersExtension !== null) {
  11291. this._caps.drawBuffersExtension = true;
  11292. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11293. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11294. for (var i = 0; i < 16; i++) {
  11295. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11296. }
  11297. }
  11298. else {
  11299. this._caps.drawBuffersExtension = false;
  11300. }
  11301. }
  11302. // Depth Texture
  11303. if (this._webGLVersion > 1) {
  11304. this._caps.depthTextureExtension = true;
  11305. }
  11306. else {
  11307. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11308. if (depthTextureExtension != null) {
  11309. this._caps.depthTextureExtension = true;
  11310. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11311. }
  11312. }
  11313. // Vertex array object
  11314. if (this._webGLVersion > 1) {
  11315. this._caps.vertexArrayObject = true;
  11316. }
  11317. else {
  11318. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11319. if (vertexArrayObjectExtension != null) {
  11320. this._caps.vertexArrayObject = true;
  11321. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11322. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11323. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11324. }
  11325. else {
  11326. this._caps.vertexArrayObject = false;
  11327. }
  11328. }
  11329. // Instances count
  11330. if (this._webGLVersion > 1) {
  11331. this._caps.instancedArrays = true;
  11332. }
  11333. else {
  11334. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11335. if (instanceExtension != null) {
  11336. this._caps.instancedArrays = true;
  11337. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11338. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11339. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11340. }
  11341. else {
  11342. this._caps.instancedArrays = false;
  11343. }
  11344. }
  11345. // Intelligently add supported compressed formats in order to check for.
  11346. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11347. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11348. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11349. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11350. if (this._caps.astc)
  11351. this.texturesSupported.push('-astc.ktx');
  11352. if (this._caps.s3tc)
  11353. this.texturesSupported.push('-dxt.ktx');
  11354. if (this._caps.pvrtc)
  11355. this.texturesSupported.push('-pvrtc.ktx');
  11356. if (this._caps.etc2)
  11357. this.texturesSupported.push('-etc2.ktx');
  11358. if (this._caps.etc1)
  11359. this.texturesSupported.push('-etc1.ktx');
  11360. if (this._gl.getShaderPrecisionFormat) {
  11361. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11362. if (highp) {
  11363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11364. }
  11365. }
  11366. // Depth buffer
  11367. this.setDepthBuffer(true);
  11368. this.setDepthFunctionToLessOrEqual();
  11369. this.setDepthWrite(true);
  11370. // Texture maps
  11371. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11372. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11373. this._nextFreeTextureSlots.push(slot);
  11374. }
  11375. };
  11376. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11377. get: function () {
  11378. return this._webGLVersion;
  11379. },
  11380. enumerable: true,
  11381. configurable: true
  11382. });
  11383. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11384. /**
  11385. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11386. */
  11387. get: function () {
  11388. return this._isStencilEnable;
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Engine.prototype._prepareWorkingCanvas = function () {
  11394. if (this._workingCanvas) {
  11395. return;
  11396. }
  11397. this._workingCanvas = document.createElement("canvas");
  11398. var context = this._workingCanvas.getContext("2d");
  11399. if (context) {
  11400. this._workingContext = context;
  11401. }
  11402. };
  11403. Engine.prototype.resetTextureCache = function () {
  11404. for (var key in this._boundTexturesCache) {
  11405. var boundTexture = this._boundTexturesCache[key];
  11406. if (boundTexture) {
  11407. this._removeDesignatedSlot(boundTexture);
  11408. }
  11409. this._boundTexturesCache[key] = null;
  11410. }
  11411. if (!this.disableTextureBindingOptimization) {
  11412. this._nextFreeTextureSlots = [];
  11413. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11414. this._nextFreeTextureSlots.push(slot);
  11415. }
  11416. }
  11417. this._currentTextureChannel = -1;
  11418. };
  11419. Engine.prototype.isDeterministicLockStep = function () {
  11420. return this._deterministicLockstep;
  11421. };
  11422. Engine.prototype.getLockstepMaxSteps = function () {
  11423. return this._lockstepMaxSteps;
  11424. };
  11425. Engine.prototype.getGlInfo = function () {
  11426. return {
  11427. vendor: this._glVendor,
  11428. renderer: this._glRenderer,
  11429. version: this._glVersion
  11430. };
  11431. };
  11432. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11433. if (useScreen === void 0) { useScreen = false; }
  11434. var viewport = camera.viewport;
  11435. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11436. };
  11437. Engine.prototype.getRenderWidth = function (useScreen) {
  11438. if (useScreen === void 0) { useScreen = false; }
  11439. if (!useScreen && this._currentRenderTarget) {
  11440. return this._currentRenderTarget.width;
  11441. }
  11442. return this._gl.drawingBufferWidth;
  11443. };
  11444. Engine.prototype.getRenderHeight = function (useScreen) {
  11445. if (useScreen === void 0) { useScreen = false; }
  11446. if (!useScreen && this._currentRenderTarget) {
  11447. return this._currentRenderTarget.height;
  11448. }
  11449. return this._gl.drawingBufferHeight;
  11450. };
  11451. Engine.prototype.getRenderingCanvas = function () {
  11452. return this._renderingCanvas;
  11453. };
  11454. Engine.prototype.getRenderingCanvasClientRect = function () {
  11455. if (!this._renderingCanvas) {
  11456. return null;
  11457. }
  11458. return this._renderingCanvas.getBoundingClientRect();
  11459. };
  11460. Engine.prototype.setHardwareScalingLevel = function (level) {
  11461. this._hardwareScalingLevel = level;
  11462. this.resize();
  11463. };
  11464. Engine.prototype.getHardwareScalingLevel = function () {
  11465. return this._hardwareScalingLevel;
  11466. };
  11467. Engine.prototype.getLoadedTexturesCache = function () {
  11468. return this._internalTexturesCache;
  11469. };
  11470. Engine.prototype.getCaps = function () {
  11471. return this._caps;
  11472. };
  11473. Object.defineProperty(Engine.prototype, "drawCalls", {
  11474. /** The number of draw calls submitted last frame */
  11475. get: function () {
  11476. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11477. return 0;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11483. get: function () {
  11484. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11485. return null;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Engine.prototype.getDepthFunction = function () {
  11491. return this._depthCullingState.depthFunc;
  11492. };
  11493. Engine.prototype.setDepthFunction = function (depthFunc) {
  11494. this._depthCullingState.depthFunc = depthFunc;
  11495. };
  11496. Engine.prototype.setDepthFunctionToGreater = function () {
  11497. this._depthCullingState.depthFunc = this._gl.GREATER;
  11498. };
  11499. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11500. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11501. };
  11502. Engine.prototype.setDepthFunctionToLess = function () {
  11503. this._depthCullingState.depthFunc = this._gl.LESS;
  11504. };
  11505. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11506. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11507. };
  11508. Engine.prototype.getStencilBuffer = function () {
  11509. return this._stencilState.stencilTest;
  11510. };
  11511. Engine.prototype.setStencilBuffer = function (enable) {
  11512. this._stencilState.stencilTest = enable;
  11513. };
  11514. Engine.prototype.getStencilMask = function () {
  11515. return this._stencilState.stencilMask;
  11516. };
  11517. Engine.prototype.setStencilMask = function (mask) {
  11518. this._stencilState.stencilMask = mask;
  11519. };
  11520. Engine.prototype.getStencilFunction = function () {
  11521. return this._stencilState.stencilFunc;
  11522. };
  11523. Engine.prototype.getStencilFunctionReference = function () {
  11524. return this._stencilState.stencilFuncRef;
  11525. };
  11526. Engine.prototype.getStencilFunctionMask = function () {
  11527. return this._stencilState.stencilFuncMask;
  11528. };
  11529. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11530. this._stencilState.stencilFunc = stencilFunc;
  11531. };
  11532. Engine.prototype.setStencilFunctionReference = function (reference) {
  11533. this._stencilState.stencilFuncRef = reference;
  11534. };
  11535. Engine.prototype.setStencilFunctionMask = function (mask) {
  11536. this._stencilState.stencilFuncMask = mask;
  11537. };
  11538. Engine.prototype.getStencilOperationFail = function () {
  11539. return this._stencilState.stencilOpStencilFail;
  11540. };
  11541. Engine.prototype.getStencilOperationDepthFail = function () {
  11542. return this._stencilState.stencilOpDepthFail;
  11543. };
  11544. Engine.prototype.getStencilOperationPass = function () {
  11545. return this._stencilState.stencilOpStencilDepthPass;
  11546. };
  11547. Engine.prototype.setStencilOperationFail = function (operation) {
  11548. this._stencilState.stencilOpStencilFail = operation;
  11549. };
  11550. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11551. this._stencilState.stencilOpDepthFail = operation;
  11552. };
  11553. Engine.prototype.setStencilOperationPass = function (operation) {
  11554. this._stencilState.stencilOpStencilDepthPass = operation;
  11555. };
  11556. Engine.prototype.setDitheringState = function (value) {
  11557. if (value) {
  11558. this._gl.enable(this._gl.DITHER);
  11559. }
  11560. else {
  11561. this._gl.disable(this._gl.DITHER);
  11562. }
  11563. };
  11564. Engine.prototype.setRasterizerState = function (value) {
  11565. if (value) {
  11566. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11567. }
  11568. else {
  11569. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11570. }
  11571. };
  11572. /**
  11573. * stop executing a render loop function and remove it from the execution array
  11574. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11575. */
  11576. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11577. if (!renderFunction) {
  11578. this._activeRenderLoops = [];
  11579. return;
  11580. }
  11581. var index = this._activeRenderLoops.indexOf(renderFunction);
  11582. if (index >= 0) {
  11583. this._activeRenderLoops.splice(index, 1);
  11584. }
  11585. };
  11586. Engine.prototype._renderLoop = function () {
  11587. if (!this._contextWasLost) {
  11588. var shouldRender = true;
  11589. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11590. shouldRender = false;
  11591. }
  11592. if (shouldRender) {
  11593. // Start new frame
  11594. this.beginFrame();
  11595. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11596. var renderFunction = this._activeRenderLoops[index];
  11597. renderFunction();
  11598. }
  11599. // Present
  11600. this.endFrame();
  11601. }
  11602. }
  11603. if (this._activeRenderLoops.length > 0) {
  11604. // Register new frame
  11605. var requester = null;
  11606. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11607. requester = this._vrDisplay;
  11608. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11609. }
  11610. else {
  11611. this._renderingQueueLaunched = false;
  11612. }
  11613. };
  11614. /**
  11615. * Register and execute a render loop. The engine can have more than one render function.
  11616. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11617. * @example
  11618. * engine.runRenderLoop(function () {
  11619. * scene.render()
  11620. * })
  11621. */
  11622. Engine.prototype.runRenderLoop = function (renderFunction) {
  11623. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11624. return;
  11625. }
  11626. this._activeRenderLoops.push(renderFunction);
  11627. if (!this._renderingQueueLaunched) {
  11628. this._renderingQueueLaunched = true;
  11629. this._bindedRenderFunction = this._renderLoop.bind(this);
  11630. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11631. }
  11632. };
  11633. /**
  11634. * Toggle full screen mode.
  11635. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11636. * @param {any} options - an options object to be sent to the requestFullscreen function
  11637. */
  11638. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11639. if (this.isFullscreen) {
  11640. BABYLON.Tools.ExitFullscreen();
  11641. }
  11642. else {
  11643. this._pointerLockRequested = requestPointerLock;
  11644. if (this._renderingCanvas) {
  11645. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11646. }
  11647. }
  11648. };
  11649. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11650. if (stencil === void 0) { stencil = false; }
  11651. this.applyStates();
  11652. var mode = 0;
  11653. if (backBuffer && color) {
  11654. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11655. mode |= this._gl.COLOR_BUFFER_BIT;
  11656. }
  11657. if (depth) {
  11658. this._gl.clearDepth(1.0);
  11659. mode |= this._gl.DEPTH_BUFFER_BIT;
  11660. }
  11661. if (stencil) {
  11662. this._gl.clearStencil(0);
  11663. mode |= this._gl.STENCIL_BUFFER_BIT;
  11664. }
  11665. this._gl.clear(mode);
  11666. };
  11667. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11668. var gl = this._gl;
  11669. // Save state
  11670. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11671. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11672. // Change state
  11673. gl.enable(gl.SCISSOR_TEST);
  11674. gl.scissor(x, y, width, height);
  11675. // Clear
  11676. this.clear(clearColor, true, true, true);
  11677. // Restore state
  11678. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11679. if (curScissor === true) {
  11680. gl.enable(gl.SCISSOR_TEST);
  11681. }
  11682. else {
  11683. gl.disable(gl.SCISSOR_TEST);
  11684. }
  11685. };
  11686. /**
  11687. * Set the WebGL's viewport
  11688. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11689. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11690. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11691. */
  11692. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11693. var width = requiredWidth || this.getRenderWidth();
  11694. var height = requiredHeight || this.getRenderHeight();
  11695. var x = viewport.x || 0;
  11696. var y = viewport.y || 0;
  11697. this._cachedViewport = viewport;
  11698. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11699. };
  11700. /**
  11701. * Directly set the WebGL Viewport
  11702. * The x, y, width & height are directly passed to the WebGL call
  11703. * @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.
  11704. */
  11705. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11706. var currentViewport = this._cachedViewport;
  11707. this._cachedViewport = null;
  11708. this._gl.viewport(x, y, width, height);
  11709. return currentViewport;
  11710. };
  11711. Engine.prototype.beginFrame = function () {
  11712. this.onBeginFrameObservable.notifyObservers(this);
  11713. this._measureFps();
  11714. };
  11715. Engine.prototype.endFrame = function () {
  11716. //force a flush in case we are using a bad OS.
  11717. if (this._badOS) {
  11718. this.flushFramebuffer();
  11719. }
  11720. //submit frame to the vr device, if enabled
  11721. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11722. // TODO: We should only submit the frame if we read frameData successfully.
  11723. this._vrDisplay.submitFrame();
  11724. }
  11725. this.onEndFrameObservable.notifyObservers(this);
  11726. };
  11727. /**
  11728. * resize the view according to the canvas' size.
  11729. * @example
  11730. * window.addEventListener("resize", function () {
  11731. * engine.resize();
  11732. * });
  11733. */
  11734. Engine.prototype.resize = function () {
  11735. // We're not resizing the size of the canvas while in VR mode & presenting
  11736. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11737. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11738. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11739. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11740. }
  11741. };
  11742. /**
  11743. * force a specific size of the canvas
  11744. * @param {number} width - the new canvas' width
  11745. * @param {number} height - the new canvas' height
  11746. */
  11747. Engine.prototype.setSize = function (width, height) {
  11748. if (!this._renderingCanvas) {
  11749. return;
  11750. }
  11751. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11752. return;
  11753. }
  11754. this._renderingCanvas.width = width;
  11755. this._renderingCanvas.height = height;
  11756. for (var index = 0; index < this.scenes.length; index++) {
  11757. var scene = this.scenes[index];
  11758. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11759. var cam = scene.cameras[camIndex];
  11760. cam._currentRenderId = 0;
  11761. }
  11762. }
  11763. if (this.onResizeObservable.hasObservers) {
  11764. this.onResizeObservable.notifyObservers(this);
  11765. }
  11766. };
  11767. // WebVR functions
  11768. Engine.prototype.isVRDevicePresent = function () {
  11769. return !!this._vrDisplay;
  11770. };
  11771. Engine.prototype.getVRDevice = function () {
  11772. return this._vrDisplay;
  11773. };
  11774. /**
  11775. * Initializes a webVR display and starts listening to display change events.
  11776. * The onVRDisplayChangedObservable will be notified upon these changes.
  11777. * @returns The onVRDisplayChangedObservable.
  11778. */
  11779. Engine.prototype.initWebVR = function () {
  11780. this.initWebVRAsync();
  11781. return this.onVRDisplayChangedObservable;
  11782. };
  11783. /**
  11784. * Initializes a webVR display and starts listening to display change events.
  11785. * The onVRDisplayChangedObservable will be notified upon these changes.
  11786. * @returns A promise containing a VRDisplay and if vr is supported.
  11787. */
  11788. Engine.prototype.initWebVRAsync = function () {
  11789. var _this = this;
  11790. var notifyObservers = function () {
  11791. var eventArgs = {
  11792. vrDisplay: _this._vrDisplay,
  11793. vrSupported: _this._vrSupported
  11794. };
  11795. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11796. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11797. };
  11798. if (!this._onVrDisplayConnect) {
  11799. this._onVrDisplayConnect = function (event) {
  11800. _this._vrDisplay = event.display;
  11801. notifyObservers();
  11802. };
  11803. this._onVrDisplayDisconnect = function () {
  11804. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11805. _this._vrDisplay = undefined;
  11806. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11807. notifyObservers();
  11808. };
  11809. this._onVrDisplayPresentChange = function () {
  11810. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11811. };
  11812. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11813. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11814. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11815. }
  11816. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11817. this._webVRInitPromise.then(notifyObservers);
  11818. return this._webVRInitPromise;
  11819. };
  11820. Engine.prototype.enableVR = function () {
  11821. var _this = this;
  11822. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11823. var onResolved = function () {
  11824. _this.onVRRequestPresentComplete.notifyObservers(true);
  11825. _this._onVRFullScreenTriggered();
  11826. };
  11827. var onRejected = function () {
  11828. _this.onVRRequestPresentComplete.notifyObservers(false);
  11829. };
  11830. this.onVRRequestPresentStart.notifyObservers(this);
  11831. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11832. }
  11833. };
  11834. Engine.prototype.disableVR = function () {
  11835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11836. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11837. }
  11838. };
  11839. Engine.prototype._getVRDisplaysAsync = function () {
  11840. var _this = this;
  11841. return new Promise(function (res, rej) {
  11842. if (navigator.getVRDisplays) {
  11843. navigator.getVRDisplays().then(function (devices) {
  11844. _this._vrSupported = true;
  11845. // note that devices may actually be an empty array. This is fine;
  11846. // we expect this._vrDisplay to be undefined in this case.
  11847. _this._vrDisplay = devices[0];
  11848. res({
  11849. vrDisplay: _this._vrDisplay,
  11850. vrSupported: _this._vrSupported
  11851. });
  11852. });
  11853. }
  11854. else {
  11855. _this._vrDisplay = undefined;
  11856. _this._vrSupported = false;
  11857. res({
  11858. vrDisplay: _this._vrDisplay,
  11859. vrSupported: _this._vrSupported
  11860. });
  11861. }
  11862. });
  11863. };
  11864. /**
  11865. * Binds the frame buffer to the specified texture.
  11866. * @param texture The texture to render to or null for the default canvas
  11867. * @param faceIndex The face of the texture to render to in case of cube texture
  11868. * @param requiredWidth The width of the target to render to
  11869. * @param requiredHeight The height of the target to render to
  11870. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11871. * @param depthStencilTexture The depth stencil texture to use to render
  11872. */
  11873. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11874. if (this._currentRenderTarget) {
  11875. this.unBindFramebuffer(this._currentRenderTarget);
  11876. }
  11877. this._currentRenderTarget = texture;
  11878. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11879. var gl = this._gl;
  11880. if (texture.isCube) {
  11881. if (faceIndex === undefined) {
  11882. faceIndex = 0;
  11883. }
  11884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11885. if (depthStencilTexture) {
  11886. if (depthStencilTexture._generateStencilBuffer) {
  11887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11888. }
  11889. else {
  11890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11891. }
  11892. }
  11893. }
  11894. if (this._cachedViewport && !forceFullscreenViewport) {
  11895. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11896. }
  11897. else {
  11898. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11899. }
  11900. this.wipeCaches();
  11901. };
  11902. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11903. if (this._currentFramebuffer !== framebuffer) {
  11904. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11905. this._currentFramebuffer = framebuffer;
  11906. }
  11907. };
  11908. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11909. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11910. this._currentRenderTarget = null;
  11911. // If MSAA, we need to bitblt back to main texture
  11912. var gl = this._gl;
  11913. if (texture._MSAAFramebuffer) {
  11914. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11915. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11916. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11917. }
  11918. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11919. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11920. gl.generateMipmap(gl.TEXTURE_2D);
  11921. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11922. }
  11923. if (onBeforeUnbind) {
  11924. if (texture._MSAAFramebuffer) {
  11925. // Bind the correct framebuffer
  11926. this.bindUnboundFramebuffer(texture._framebuffer);
  11927. }
  11928. onBeforeUnbind();
  11929. }
  11930. this.bindUnboundFramebuffer(null);
  11931. };
  11932. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11933. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11934. this._currentRenderTarget = null;
  11935. // If MSAA, we need to bitblt back to main texture
  11936. var gl = this._gl;
  11937. if (textures[0]._MSAAFramebuffer) {
  11938. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11939. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11940. var attachments = textures[0]._attachments;
  11941. if (!attachments) {
  11942. attachments = new Array(textures.length);
  11943. textures[0]._attachments = attachments;
  11944. }
  11945. for (var i = 0; i < textures.length; i++) {
  11946. var texture = textures[i];
  11947. for (var j = 0; j < attachments.length; j++) {
  11948. attachments[j] = gl.NONE;
  11949. }
  11950. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11951. gl.readBuffer(attachments[i]);
  11952. gl.drawBuffers(attachments);
  11953. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11954. }
  11955. for (var i = 0; i < attachments.length; i++) {
  11956. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11957. }
  11958. gl.drawBuffers(attachments);
  11959. }
  11960. for (var i = 0; i < textures.length; i++) {
  11961. var texture = textures[i];
  11962. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11963. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11964. gl.generateMipmap(gl.TEXTURE_2D);
  11965. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11966. }
  11967. }
  11968. if (onBeforeUnbind) {
  11969. if (textures[0]._MSAAFramebuffer) {
  11970. // Bind the correct framebuffer
  11971. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11972. }
  11973. onBeforeUnbind();
  11974. }
  11975. this.bindUnboundFramebuffer(null);
  11976. };
  11977. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11978. if (texture.generateMipMaps) {
  11979. var gl = this._gl;
  11980. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11981. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11983. }
  11984. };
  11985. Engine.prototype.flushFramebuffer = function () {
  11986. this._gl.flush();
  11987. };
  11988. Engine.prototype.restoreDefaultFramebuffer = function () {
  11989. if (this._currentRenderTarget) {
  11990. this.unBindFramebuffer(this._currentRenderTarget);
  11991. }
  11992. else {
  11993. this.bindUnboundFramebuffer(null);
  11994. }
  11995. if (this._cachedViewport) {
  11996. this.setViewport(this._cachedViewport);
  11997. }
  11998. this.wipeCaches();
  11999. };
  12000. // UBOs
  12001. Engine.prototype.createUniformBuffer = function (elements) {
  12002. var ubo = this._gl.createBuffer();
  12003. if (!ubo) {
  12004. throw new Error("Unable to create uniform buffer");
  12005. }
  12006. this.bindUniformBuffer(ubo);
  12007. if (elements instanceof Float32Array) {
  12008. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12009. }
  12010. else {
  12011. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12012. }
  12013. this.bindUniformBuffer(null);
  12014. ubo.references = 1;
  12015. return ubo;
  12016. };
  12017. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12018. var ubo = this._gl.createBuffer();
  12019. if (!ubo) {
  12020. throw new Error("Unable to create dynamic uniform buffer");
  12021. }
  12022. this.bindUniformBuffer(ubo);
  12023. if (elements instanceof Float32Array) {
  12024. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12025. }
  12026. else {
  12027. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12028. }
  12029. this.bindUniformBuffer(null);
  12030. ubo.references = 1;
  12031. return ubo;
  12032. };
  12033. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12034. this.bindUniformBuffer(uniformBuffer);
  12035. if (offset === undefined) {
  12036. offset = 0;
  12037. }
  12038. if (count === undefined) {
  12039. if (elements instanceof Float32Array) {
  12040. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12041. }
  12042. else {
  12043. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12044. }
  12045. }
  12046. else {
  12047. if (elements instanceof Float32Array) {
  12048. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12049. }
  12050. else {
  12051. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12052. }
  12053. }
  12054. this.bindUniformBuffer(null);
  12055. };
  12056. // VBOs
  12057. Engine.prototype._resetVertexBufferBinding = function () {
  12058. this.bindArrayBuffer(null);
  12059. this._cachedVertexBuffers = null;
  12060. };
  12061. Engine.prototype.createVertexBuffer = function (vertices) {
  12062. var vbo = this._gl.createBuffer();
  12063. if (!vbo) {
  12064. throw new Error("Unable to create vertex buffer");
  12065. }
  12066. this.bindArrayBuffer(vbo);
  12067. if (vertices instanceof Float32Array) {
  12068. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12069. }
  12070. else {
  12071. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12072. }
  12073. this._resetVertexBufferBinding();
  12074. vbo.references = 1;
  12075. return vbo;
  12076. };
  12077. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12078. var vbo = this._gl.createBuffer();
  12079. if (!vbo) {
  12080. throw new Error("Unable to create dynamic vertex buffer");
  12081. }
  12082. this.bindArrayBuffer(vbo);
  12083. if (vertices instanceof Float32Array) {
  12084. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12085. }
  12086. else {
  12087. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12088. }
  12089. this._resetVertexBufferBinding();
  12090. vbo.references = 1;
  12091. return vbo;
  12092. };
  12093. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12094. if (offset === void 0) { offset = 0; }
  12095. // Force cache update
  12096. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12097. this.bindIndexBuffer(indexBuffer);
  12098. var arrayBuffer;
  12099. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12100. arrayBuffer = indices;
  12101. }
  12102. else {
  12103. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12104. }
  12105. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12106. this._resetIndexBufferBinding();
  12107. };
  12108. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12109. this.bindArrayBuffer(vertexBuffer);
  12110. if (offset === undefined) {
  12111. offset = 0;
  12112. }
  12113. if (count === undefined) {
  12114. if (vertices instanceof Float32Array) {
  12115. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12116. }
  12117. else {
  12118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12119. }
  12120. }
  12121. else {
  12122. if (vertices instanceof Float32Array) {
  12123. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12124. }
  12125. else {
  12126. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12127. }
  12128. }
  12129. this._resetVertexBufferBinding();
  12130. };
  12131. Engine.prototype._resetIndexBufferBinding = function () {
  12132. this.bindIndexBuffer(null);
  12133. this._cachedIndexBuffer = null;
  12134. };
  12135. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12136. var vbo = this._gl.createBuffer();
  12137. if (!vbo) {
  12138. throw new Error("Unable to create index buffer");
  12139. }
  12140. this.bindIndexBuffer(vbo);
  12141. // Check for 32 bits indices
  12142. var arrayBuffer;
  12143. var need32Bits = false;
  12144. if (indices instanceof Uint16Array) {
  12145. arrayBuffer = indices;
  12146. }
  12147. else {
  12148. //check 32 bit support
  12149. if (this._caps.uintIndices) {
  12150. if (indices instanceof Uint32Array) {
  12151. arrayBuffer = indices;
  12152. need32Bits = true;
  12153. }
  12154. else {
  12155. //number[] or Int32Array, check if 32 bit is necessary
  12156. for (var index = 0; index < indices.length; index++) {
  12157. if (indices[index] > 65535) {
  12158. need32Bits = true;
  12159. break;
  12160. }
  12161. }
  12162. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12163. }
  12164. }
  12165. else {
  12166. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12167. arrayBuffer = new Uint16Array(indices);
  12168. }
  12169. }
  12170. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12171. this._resetIndexBufferBinding();
  12172. vbo.references = 1;
  12173. vbo.is32Bits = need32Bits;
  12174. return vbo;
  12175. };
  12176. Engine.prototype.bindArrayBuffer = function (buffer) {
  12177. if (!this._vaoRecordInProgress) {
  12178. this._unbindVertexArrayObject();
  12179. }
  12180. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12181. };
  12182. Engine.prototype.bindUniformBuffer = function (buffer) {
  12183. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12184. };
  12185. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12186. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12187. };
  12188. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12189. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12190. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12191. };
  12192. ;
  12193. Engine.prototype.bindIndexBuffer = function (buffer) {
  12194. if (!this._vaoRecordInProgress) {
  12195. this._unbindVertexArrayObject();
  12196. }
  12197. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12198. };
  12199. Engine.prototype.bindBuffer = function (buffer, target) {
  12200. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12201. this._gl.bindBuffer(target, buffer);
  12202. this._currentBoundBuffer[target] = buffer;
  12203. }
  12204. };
  12205. Engine.prototype.updateArrayBuffer = function (data) {
  12206. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12207. };
  12208. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12209. var pointer = this._currentBufferPointers[indx];
  12210. var changed = false;
  12211. if (!pointer.active) {
  12212. changed = true;
  12213. pointer.active = true;
  12214. pointer.index = indx;
  12215. pointer.size = size;
  12216. pointer.type = type;
  12217. pointer.normalized = normalized;
  12218. pointer.stride = stride;
  12219. pointer.offset = offset;
  12220. pointer.buffer = buffer;
  12221. }
  12222. else {
  12223. if (pointer.buffer !== buffer) {
  12224. pointer.buffer = buffer;
  12225. changed = true;
  12226. }
  12227. if (pointer.size !== size) {
  12228. pointer.size = size;
  12229. changed = true;
  12230. }
  12231. if (pointer.type !== type) {
  12232. pointer.type = type;
  12233. changed = true;
  12234. }
  12235. if (pointer.normalized !== normalized) {
  12236. pointer.normalized = normalized;
  12237. changed = true;
  12238. }
  12239. if (pointer.stride !== stride) {
  12240. pointer.stride = stride;
  12241. changed = true;
  12242. }
  12243. if (pointer.offset !== offset) {
  12244. pointer.offset = offset;
  12245. changed = true;
  12246. }
  12247. }
  12248. if (changed || this._vaoRecordInProgress) {
  12249. this.bindArrayBuffer(buffer);
  12250. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12251. }
  12252. };
  12253. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12254. if (indexBuffer == null) {
  12255. return;
  12256. }
  12257. if (this._cachedIndexBuffer !== indexBuffer) {
  12258. this._cachedIndexBuffer = indexBuffer;
  12259. this.bindIndexBuffer(indexBuffer);
  12260. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12261. }
  12262. };
  12263. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12264. var attributes = effect.getAttributesNames();
  12265. if (!this._vaoRecordInProgress) {
  12266. this._unbindVertexArrayObject();
  12267. }
  12268. this.unbindAllAttributes();
  12269. for (var index = 0; index < attributes.length; index++) {
  12270. var order = effect.getAttributeLocation(index);
  12271. if (order >= 0) {
  12272. var vertexBuffer = vertexBuffers[attributes[index]];
  12273. if (!vertexBuffer) {
  12274. continue;
  12275. }
  12276. this._gl.enableVertexAttribArray(order);
  12277. if (!this._vaoRecordInProgress) {
  12278. this._vertexAttribArraysEnabled[order] = true;
  12279. }
  12280. var buffer = vertexBuffer.getBuffer();
  12281. if (buffer) {
  12282. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12283. if (vertexBuffer.getIsInstanced()) {
  12284. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12285. if (!this._vaoRecordInProgress) {
  12286. this._currentInstanceLocations.push(order);
  12287. this._currentInstanceBuffers.push(buffer);
  12288. }
  12289. }
  12290. }
  12291. }
  12292. }
  12293. };
  12294. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12295. var vao = this._gl.createVertexArray();
  12296. this._vaoRecordInProgress = true;
  12297. this._gl.bindVertexArray(vao);
  12298. this._mustWipeVertexAttributes = true;
  12299. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12300. this.bindIndexBuffer(indexBuffer);
  12301. this._vaoRecordInProgress = false;
  12302. this._gl.bindVertexArray(null);
  12303. return vao;
  12304. };
  12305. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12306. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12307. this._cachedVertexArrayObject = vertexArrayObject;
  12308. this._gl.bindVertexArray(vertexArrayObject);
  12309. this._cachedVertexBuffers = null;
  12310. this._cachedIndexBuffer = null;
  12311. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12312. this._mustWipeVertexAttributes = true;
  12313. }
  12314. };
  12315. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12316. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12317. this._cachedVertexBuffers = vertexBuffer;
  12318. this._cachedEffectForVertexBuffers = effect;
  12319. var attributesCount = effect.getAttributesCount();
  12320. this._unbindVertexArrayObject();
  12321. this.unbindAllAttributes();
  12322. var offset = 0;
  12323. for (var index = 0; index < attributesCount; index++) {
  12324. if (index < vertexDeclaration.length) {
  12325. var order = effect.getAttributeLocation(index);
  12326. if (order >= 0) {
  12327. this._gl.enableVertexAttribArray(order);
  12328. this._vertexAttribArraysEnabled[order] = true;
  12329. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12330. }
  12331. offset += vertexDeclaration[index] * 4;
  12332. }
  12333. }
  12334. }
  12335. this._bindIndexBufferWithCache(indexBuffer);
  12336. };
  12337. Engine.prototype._unbindVertexArrayObject = function () {
  12338. if (!this._cachedVertexArrayObject) {
  12339. return;
  12340. }
  12341. this._cachedVertexArrayObject = null;
  12342. this._gl.bindVertexArray(null);
  12343. };
  12344. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12345. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12346. this._cachedVertexBuffers = vertexBuffers;
  12347. this._cachedEffectForVertexBuffers = effect;
  12348. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12349. }
  12350. this._bindIndexBufferWithCache(indexBuffer);
  12351. };
  12352. Engine.prototype.unbindInstanceAttributes = function () {
  12353. var boundBuffer;
  12354. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12355. var instancesBuffer = this._currentInstanceBuffers[i];
  12356. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12357. boundBuffer = instancesBuffer;
  12358. this.bindArrayBuffer(instancesBuffer);
  12359. }
  12360. var offsetLocation = this._currentInstanceLocations[i];
  12361. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12362. }
  12363. this._currentInstanceBuffers.length = 0;
  12364. this._currentInstanceLocations.length = 0;
  12365. };
  12366. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12367. this._gl.deleteVertexArray(vao);
  12368. };
  12369. Engine.prototype._releaseBuffer = function (buffer) {
  12370. buffer.references--;
  12371. if (buffer.references === 0) {
  12372. this._gl.deleteBuffer(buffer);
  12373. return true;
  12374. }
  12375. return false;
  12376. };
  12377. Engine.prototype.createInstancesBuffer = function (capacity) {
  12378. var buffer = this._gl.createBuffer();
  12379. if (!buffer) {
  12380. throw new Error("Unable to create instance buffer");
  12381. }
  12382. buffer.capacity = capacity;
  12383. this.bindArrayBuffer(buffer);
  12384. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12385. return buffer;
  12386. };
  12387. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12388. this._gl.deleteBuffer(buffer);
  12389. };
  12390. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12391. this.bindArrayBuffer(instancesBuffer);
  12392. if (data) {
  12393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12394. }
  12395. if (offsetLocations[0].index !== undefined) {
  12396. var stride = 0;
  12397. for (var i = 0; i < offsetLocations.length; i++) {
  12398. var ai = offsetLocations[i];
  12399. stride += ai.attributeSize * 4;
  12400. }
  12401. for (var i = 0; i < offsetLocations.length; i++) {
  12402. var ai = offsetLocations[i];
  12403. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12404. this._gl.enableVertexAttribArray(ai.index);
  12405. this._vertexAttribArraysEnabled[ai.index] = true;
  12406. }
  12407. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12408. this._gl.vertexAttribDivisor(ai.index, 1);
  12409. this._currentInstanceLocations.push(ai.index);
  12410. this._currentInstanceBuffers.push(instancesBuffer);
  12411. }
  12412. }
  12413. else {
  12414. for (var index = 0; index < 4; index++) {
  12415. var offsetLocation = offsetLocations[index];
  12416. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12417. this._gl.enableVertexAttribArray(offsetLocation);
  12418. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12419. }
  12420. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12421. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12422. this._currentInstanceLocations.push(offsetLocation);
  12423. this._currentInstanceBuffers.push(instancesBuffer);
  12424. }
  12425. }
  12426. };
  12427. Engine.prototype.applyStates = function () {
  12428. this._depthCullingState.apply(this._gl);
  12429. this._stencilState.apply(this._gl);
  12430. this._alphaState.apply(this._gl);
  12431. };
  12432. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12433. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12434. };
  12435. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12436. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12437. };
  12438. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12439. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12440. };
  12441. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12442. // Apply states
  12443. this.applyStates();
  12444. this._drawCalls.addCount(1, false);
  12445. // Render
  12446. var drawMode = this.DrawMode(fillMode);
  12447. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12448. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12449. if (instancesCount) {
  12450. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12451. }
  12452. else {
  12453. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12454. }
  12455. };
  12456. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12457. // Apply states
  12458. this.applyStates();
  12459. this._drawCalls.addCount(1, false);
  12460. var drawMode = this.DrawMode(fillMode);
  12461. if (instancesCount) {
  12462. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12463. }
  12464. else {
  12465. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12466. }
  12467. };
  12468. Engine.prototype.DrawMode = function (fillMode) {
  12469. switch (fillMode) {
  12470. // Triangle views
  12471. case BABYLON.Material.TriangleFillMode:
  12472. return this._gl.TRIANGLES;
  12473. case BABYLON.Material.PointFillMode:
  12474. return this._gl.POINTS;
  12475. case BABYLON.Material.WireFrameFillMode:
  12476. return this._gl.LINES;
  12477. // Draw modes
  12478. case BABYLON.Material.PointListDrawMode:
  12479. return this._gl.POINTS;
  12480. case BABYLON.Material.LineListDrawMode:
  12481. return this._gl.LINES;
  12482. case BABYLON.Material.LineLoopDrawMode:
  12483. return this._gl.LINE_LOOP;
  12484. case BABYLON.Material.LineStripDrawMode:
  12485. return this._gl.LINE_STRIP;
  12486. case BABYLON.Material.TriangleStripDrawMode:
  12487. return this._gl.TRIANGLE_STRIP;
  12488. case BABYLON.Material.TriangleFanDrawMode:
  12489. return this._gl.TRIANGLE_FAN;
  12490. default:
  12491. return this._gl.TRIANGLES;
  12492. }
  12493. };
  12494. // Shaders
  12495. Engine.prototype._releaseEffect = function (effect) {
  12496. if (this._compiledEffects[effect._key]) {
  12497. delete this._compiledEffects[effect._key];
  12498. this._deleteProgram(effect.getProgram());
  12499. }
  12500. };
  12501. Engine.prototype._deleteProgram = function (program) {
  12502. if (program) {
  12503. program.__SPECTOR_rebuildProgram = null;
  12504. if (program.transformFeedback) {
  12505. this.deleteTransformFeedback(program.transformFeedback);
  12506. program.transformFeedback = null;
  12507. }
  12508. this._gl.deleteProgram(program);
  12509. }
  12510. };
  12511. /**
  12512. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12513. * @param samplers An array of string used to represent textures
  12514. */
  12515. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12516. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12517. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12518. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12519. if (this._compiledEffects[name]) {
  12520. var compiledEffect = this._compiledEffects[name];
  12521. if (onCompiled && compiledEffect.isReady()) {
  12522. onCompiled(compiledEffect);
  12523. }
  12524. return compiledEffect;
  12525. }
  12526. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12527. effect._key = name;
  12528. this._compiledEffects[name] = effect;
  12529. return effect;
  12530. };
  12531. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12532. if (uniformsNames === void 0) { uniformsNames = []; }
  12533. if (samplers === void 0) { samplers = []; }
  12534. if (defines === void 0) { defines = ""; }
  12535. return this.createEffect({
  12536. vertex: "particles",
  12537. fragmentElement: fragmentName
  12538. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12539. };
  12540. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12541. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12542. context = context || this._gl;
  12543. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12544. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12545. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12546. };
  12547. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12548. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12549. context = context || this._gl;
  12550. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12551. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12552. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12553. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12554. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12555. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12556. return program;
  12557. };
  12558. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12559. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12560. var shaderProgram = context.createProgram();
  12561. if (!shaderProgram) {
  12562. throw new Error("Unable to create program");
  12563. }
  12564. context.attachShader(shaderProgram, vertexShader);
  12565. context.attachShader(shaderProgram, fragmentShader);
  12566. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12567. var transformFeedback = this.createTransformFeedback();
  12568. this.bindTransformFeedback(transformFeedback);
  12569. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12570. shaderProgram.transformFeedback = transformFeedback;
  12571. }
  12572. context.linkProgram(shaderProgram);
  12573. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12574. this.bindTransformFeedback(null);
  12575. }
  12576. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12577. if (!linked) {
  12578. context.validateProgram(shaderProgram);
  12579. var error = context.getProgramInfoLog(shaderProgram);
  12580. if (error) {
  12581. throw new Error(error);
  12582. }
  12583. }
  12584. context.deleteShader(vertexShader);
  12585. context.deleteShader(fragmentShader);
  12586. return shaderProgram;
  12587. };
  12588. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12589. var results = new Array();
  12590. for (var index = 0; index < uniformsNames.length; index++) {
  12591. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12592. }
  12593. return results;
  12594. };
  12595. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12596. var results = [];
  12597. for (var index = 0; index < attributesNames.length; index++) {
  12598. try {
  12599. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12600. }
  12601. catch (e) {
  12602. results.push(-1);
  12603. }
  12604. }
  12605. return results;
  12606. };
  12607. Engine.prototype.enableEffect = function (effect) {
  12608. if (!effect) {
  12609. return;
  12610. }
  12611. // Use program
  12612. this.bindSamplers(effect);
  12613. this._currentEffect = effect;
  12614. if (effect.onBind) {
  12615. effect.onBind(effect);
  12616. }
  12617. effect.onBindObservable.notifyObservers(effect);
  12618. };
  12619. Engine.prototype.setIntArray = function (uniform, array) {
  12620. if (!uniform)
  12621. return;
  12622. this._gl.uniform1iv(uniform, array);
  12623. };
  12624. Engine.prototype.setIntArray2 = function (uniform, array) {
  12625. if (!uniform || array.length % 2 !== 0)
  12626. return;
  12627. this._gl.uniform2iv(uniform, array);
  12628. };
  12629. Engine.prototype.setIntArray3 = function (uniform, array) {
  12630. if (!uniform || array.length % 3 !== 0)
  12631. return;
  12632. this._gl.uniform3iv(uniform, array);
  12633. };
  12634. Engine.prototype.setIntArray4 = function (uniform, array) {
  12635. if (!uniform || array.length % 4 !== 0)
  12636. return;
  12637. this._gl.uniform4iv(uniform, array);
  12638. };
  12639. Engine.prototype.setFloatArray = function (uniform, array) {
  12640. if (!uniform)
  12641. return;
  12642. this._gl.uniform1fv(uniform, array);
  12643. };
  12644. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12645. if (!uniform || array.length % 2 !== 0)
  12646. return;
  12647. this._gl.uniform2fv(uniform, array);
  12648. };
  12649. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12650. if (!uniform || array.length % 3 !== 0)
  12651. return;
  12652. this._gl.uniform3fv(uniform, array);
  12653. };
  12654. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12655. if (!uniform || array.length % 4 !== 0)
  12656. return;
  12657. this._gl.uniform4fv(uniform, array);
  12658. };
  12659. Engine.prototype.setArray = function (uniform, array) {
  12660. if (!uniform)
  12661. return;
  12662. this._gl.uniform1fv(uniform, array);
  12663. };
  12664. Engine.prototype.setArray2 = function (uniform, array) {
  12665. if (!uniform || array.length % 2 !== 0)
  12666. return;
  12667. this._gl.uniform2fv(uniform, array);
  12668. };
  12669. Engine.prototype.setArray3 = function (uniform, array) {
  12670. if (!uniform || array.length % 3 !== 0)
  12671. return;
  12672. this._gl.uniform3fv(uniform, array);
  12673. };
  12674. Engine.prototype.setArray4 = function (uniform, array) {
  12675. if (!uniform || array.length % 4 !== 0)
  12676. return;
  12677. this._gl.uniform4fv(uniform, array);
  12678. };
  12679. Engine.prototype.setMatrices = function (uniform, matrices) {
  12680. if (!uniform)
  12681. return;
  12682. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12683. };
  12684. Engine.prototype.setMatrix = function (uniform, matrix) {
  12685. if (!uniform)
  12686. return;
  12687. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12688. };
  12689. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12690. if (!uniform)
  12691. return;
  12692. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12693. };
  12694. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12695. if (!uniform)
  12696. return;
  12697. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12698. };
  12699. Engine.prototype.setInt = function (uniform, value) {
  12700. if (!uniform)
  12701. return;
  12702. this._gl.uniform1i(uniform, value);
  12703. };
  12704. Engine.prototype.setFloat = function (uniform, value) {
  12705. if (!uniform)
  12706. return;
  12707. this._gl.uniform1f(uniform, value);
  12708. };
  12709. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12710. if (!uniform)
  12711. return;
  12712. this._gl.uniform2f(uniform, x, y);
  12713. };
  12714. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12715. if (!uniform)
  12716. return;
  12717. this._gl.uniform3f(uniform, x, y, z);
  12718. };
  12719. Engine.prototype.setBool = function (uniform, bool) {
  12720. if (!uniform)
  12721. return;
  12722. this._gl.uniform1i(uniform, bool);
  12723. };
  12724. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12725. if (!uniform)
  12726. return;
  12727. this._gl.uniform4f(uniform, x, y, z, w);
  12728. };
  12729. Engine.prototype.setColor3 = function (uniform, color3) {
  12730. if (!uniform)
  12731. return;
  12732. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12733. };
  12734. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12735. if (!uniform)
  12736. return;
  12737. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12738. };
  12739. /**
  12740. * Sets a Color4 on a uniform variable
  12741. * @param uniform defines the uniform location
  12742. * @param color4 defines the value to be set
  12743. */
  12744. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12745. if (!uniform)
  12746. return;
  12747. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12748. };
  12749. // States
  12750. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12751. if (zOffset === void 0) { zOffset = 0; }
  12752. if (reverseSide === void 0) { reverseSide = false; }
  12753. // Culling
  12754. if (this._depthCullingState.cull !== culling || force) {
  12755. this._depthCullingState.cull = culling;
  12756. }
  12757. // Cull face
  12758. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12759. if (this._depthCullingState.cullFace !== cullFace || force) {
  12760. this._depthCullingState.cullFace = cullFace;
  12761. }
  12762. // Z offset
  12763. this.setZOffset(zOffset);
  12764. // Front face
  12765. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12766. if (this._depthCullingState.frontFace !== frontFace || force) {
  12767. this._depthCullingState.frontFace = frontFace;
  12768. }
  12769. };
  12770. Engine.prototype.setZOffset = function (value) {
  12771. this._depthCullingState.zOffset = value;
  12772. };
  12773. Engine.prototype.getZOffset = function () {
  12774. return this._depthCullingState.zOffset;
  12775. };
  12776. Engine.prototype.setDepthBuffer = function (enable) {
  12777. this._depthCullingState.depthTest = enable;
  12778. };
  12779. Engine.prototype.getDepthWrite = function () {
  12780. return this._depthCullingState.depthMask;
  12781. };
  12782. Engine.prototype.setDepthWrite = function (enable) {
  12783. this._depthCullingState.depthMask = enable;
  12784. };
  12785. Engine.prototype.setColorWrite = function (enable) {
  12786. this._gl.colorMask(enable, enable, enable, enable);
  12787. this._colorWrite = enable;
  12788. };
  12789. Engine.prototype.getColorWrite = function () {
  12790. return this._colorWrite;
  12791. };
  12792. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12793. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12794. };
  12795. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12796. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12797. if (this._alphaMode === mode) {
  12798. return;
  12799. }
  12800. switch (mode) {
  12801. case Engine.ALPHA_DISABLE:
  12802. this._alphaState.alphaBlend = false;
  12803. break;
  12804. case Engine.ALPHA_PREMULTIPLIED:
  12805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12806. this._alphaState.alphaBlend = true;
  12807. break;
  12808. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12810. this._alphaState.alphaBlend = true;
  12811. break;
  12812. case Engine.ALPHA_COMBINE:
  12813. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12814. this._alphaState.alphaBlend = true;
  12815. break;
  12816. case Engine.ALPHA_ONEONE:
  12817. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12818. this._alphaState.alphaBlend = true;
  12819. break;
  12820. case Engine.ALPHA_ADD:
  12821. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12822. this._alphaState.alphaBlend = true;
  12823. break;
  12824. case Engine.ALPHA_SUBTRACT:
  12825. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12826. this._alphaState.alphaBlend = true;
  12827. break;
  12828. case Engine.ALPHA_MULTIPLY:
  12829. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12830. this._alphaState.alphaBlend = true;
  12831. break;
  12832. case Engine.ALPHA_MAXIMIZED:
  12833. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12834. this._alphaState.alphaBlend = true;
  12835. break;
  12836. case Engine.ALPHA_INTERPOLATE:
  12837. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12838. this._alphaState.alphaBlend = true;
  12839. break;
  12840. case Engine.ALPHA_SCREENMODE:
  12841. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12842. this._alphaState.alphaBlend = true;
  12843. break;
  12844. }
  12845. if (!noDepthWriteChange) {
  12846. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12847. }
  12848. this._alphaMode = mode;
  12849. };
  12850. Engine.prototype.getAlphaMode = function () {
  12851. return this._alphaMode;
  12852. };
  12853. // Textures
  12854. Engine.prototype.wipeCaches = function (bruteForce) {
  12855. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12856. return;
  12857. }
  12858. this._currentEffect = null;
  12859. // 6/8/2017: deltakosh: Should not be required anymore.
  12860. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12861. if (bruteForce) {
  12862. this.resetTextureCache();
  12863. this._currentProgram = null;
  12864. this._stencilState.reset();
  12865. this._depthCullingState.reset();
  12866. this.setDepthFunctionToLessOrEqual();
  12867. this._alphaState.reset();
  12868. }
  12869. this._resetVertexBufferBinding();
  12870. this._cachedIndexBuffer = null;
  12871. this._cachedEffectForVertexBuffers = null;
  12872. this._unbindVertexArrayObject();
  12873. this.bindIndexBuffer(null);
  12874. };
  12875. /**
  12876. * Set the compressed texture format to use, based on the formats you have, and the formats
  12877. * supported by the hardware / browser.
  12878. *
  12879. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12880. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12881. * to API arguments needed to compressed textures. This puts the burden on the container
  12882. * generator to house the arcane code for determining these for current & future formats.
  12883. *
  12884. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12885. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12886. *
  12887. * Note: The result of this call is not taken into account when a texture is base64.
  12888. *
  12889. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12890. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12891. *
  12892. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12893. * @returns The extension selected.
  12894. */
  12895. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12896. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12897. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12898. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12899. return this._textureFormatInUse = this._texturesSupported[i];
  12900. }
  12901. }
  12902. }
  12903. // actively set format to nothing, to allow this to be called more than once
  12904. // and possibly fail the 2nd time
  12905. this._textureFormatInUse = null;
  12906. return null;
  12907. };
  12908. Engine.prototype._createTexture = function () {
  12909. var texture = this._gl.createTexture();
  12910. if (!texture) {
  12911. throw new Error("Unable to create texture");
  12912. }
  12913. return texture;
  12914. };
  12915. /**
  12916. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12917. * @param {string} urlArg- This contains one of the following:
  12918. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12919. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12920. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12921. *
  12922. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12923. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12924. * @param {Scene} scene- Needed for loading to the correct scene.
  12925. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12926. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12927. * @param {callback} onError- Optional callback to be called upon failure.
  12928. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12929. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12930. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12931. *
  12932. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12933. */
  12934. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12935. var _this = this;
  12936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12937. if (onLoad === void 0) { onLoad = null; }
  12938. if (onError === void 0) { onError = null; }
  12939. if (buffer === void 0) { buffer = null; }
  12940. if (fallBack === void 0) { fallBack = null; }
  12941. if (format === void 0) { format = null; }
  12942. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12943. var fromData = url.substr(0, 5) === "data:";
  12944. var fromBlob = url.substr(0, 5) === "blob:";
  12945. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12946. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12947. // establish the file extension, if possible
  12948. var lastDot = url.lastIndexOf('.');
  12949. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12950. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12951. var isTGA = (extension.indexOf(".tga") === 0);
  12952. // determine if a ktx file should be substituted
  12953. var isKTX = false;
  12954. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12955. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12956. isKTX = true;
  12957. }
  12958. if (scene) {
  12959. scene._addPendingData(texture);
  12960. }
  12961. texture.url = url;
  12962. texture.generateMipMaps = !noMipmap;
  12963. texture.samplingMode = samplingMode;
  12964. texture.invertY = invertY;
  12965. if (!this._doNotHandleContextLost) {
  12966. // Keep a link to the buffer only if we plan to handle context lost
  12967. texture._buffer = buffer;
  12968. }
  12969. var onLoadObserver = null;
  12970. if (onLoad && !fallBack) {
  12971. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12972. }
  12973. if (!fallBack)
  12974. this._internalTexturesCache.push(texture);
  12975. var onerror = function (message, exception) {
  12976. if (scene) {
  12977. scene._removePendingData(texture);
  12978. }
  12979. if (onLoadObserver) {
  12980. texture.onLoadedObservable.remove(onLoadObserver);
  12981. }
  12982. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12983. if (isKTX) {
  12984. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12985. }
  12986. else if (BABYLON.Tools.UseFallbackTexture) {
  12987. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12988. }
  12989. if (onError) {
  12990. onError(message || "Unknown error", exception);
  12991. }
  12992. };
  12993. var callback = null;
  12994. // processing for non-image formats
  12995. if (isKTX || isTGA || isDDS) {
  12996. if (isKTX) {
  12997. callback = function (data) {
  12998. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12999. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13000. ktx.uploadLevels(_this._gl, !noMipmap);
  13001. return false;
  13002. }, samplingMode);
  13003. };
  13004. }
  13005. else if (isTGA) {
  13006. callback = function (arrayBuffer) {
  13007. var data = new Uint8Array(arrayBuffer);
  13008. var header = BABYLON.TGATools.GetTGAHeader(data);
  13009. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13010. BABYLON.TGATools.UploadContent(_this._gl, data);
  13011. return false;
  13012. }, samplingMode);
  13013. };
  13014. }
  13015. else if (isDDS) {
  13016. callback = function (data) {
  13017. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13018. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13019. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13020. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13021. return false;
  13022. }, samplingMode);
  13023. };
  13024. }
  13025. if (!buffer) {
  13026. this._loadFile(url, function (data) {
  13027. if (callback) {
  13028. callback(data);
  13029. }
  13030. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13031. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13032. });
  13033. }
  13034. else {
  13035. if (callback) {
  13036. callback(buffer);
  13037. }
  13038. }
  13039. // image format processing
  13040. }
  13041. else {
  13042. var onload = function (img) {
  13043. if (fromBlob && !_this._doNotHandleContextLost) {
  13044. // We need to store the image if we need to rebuild the texture
  13045. // in case of a webgl context lost
  13046. texture._buffer = img;
  13047. }
  13048. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13049. var gl = _this._gl;
  13050. var isPot = (img.width === potWidth && img.height === potHeight);
  13051. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13052. if (isPot) {
  13053. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13054. return false;
  13055. }
  13056. // Using shaders to rescale because canvas.drawImage is lossy
  13057. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13058. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13059. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13064. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13065. _this._releaseTexture(source);
  13066. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13067. continuationCallback();
  13068. });
  13069. return true;
  13070. }, samplingMode);
  13071. };
  13072. if (!fromData || isBase64)
  13073. if (buffer instanceof HTMLImageElement) {
  13074. onload(buffer);
  13075. }
  13076. else {
  13077. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13078. }
  13079. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13080. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13081. else
  13082. onload(buffer);
  13083. }
  13084. return texture;
  13085. };
  13086. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13087. var _this = this;
  13088. var rtt = this.createRenderTargetTexture({
  13089. width: destination.width,
  13090. height: destination.height,
  13091. }, {
  13092. generateMipMaps: false,
  13093. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13094. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13095. generateDepthBuffer: false,
  13096. generateStencilBuffer: false
  13097. });
  13098. if (!this._rescalePostProcess) {
  13099. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13100. }
  13101. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13102. _this._rescalePostProcess.onApply = function (effect) {
  13103. effect._bindTexture("textureSampler", source);
  13104. };
  13105. var hostingScene = scene;
  13106. if (!hostingScene) {
  13107. hostingScene = _this.scenes[_this.scenes.length - 1];
  13108. }
  13109. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13110. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13111. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13112. _this.unBindFramebuffer(rtt);
  13113. _this._releaseTexture(rtt);
  13114. if (onComplete) {
  13115. onComplete();
  13116. }
  13117. });
  13118. };
  13119. Engine.prototype._getInternalFormat = function (format) {
  13120. var internalFormat = this._gl.RGBA;
  13121. switch (format) {
  13122. case Engine.TEXTUREFORMAT_ALPHA:
  13123. internalFormat = this._gl.ALPHA;
  13124. break;
  13125. case Engine.TEXTUREFORMAT_LUMINANCE:
  13126. internalFormat = this._gl.LUMINANCE;
  13127. break;
  13128. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13129. internalFormat = this._gl.LUMINANCE_ALPHA;
  13130. break;
  13131. case Engine.TEXTUREFORMAT_RGB:
  13132. case Engine.TEXTUREFORMAT_RGB32F:
  13133. internalFormat = this._gl.RGB;
  13134. break;
  13135. case Engine.TEXTUREFORMAT_RGBA:
  13136. case Engine.TEXTUREFORMAT_RGBA32F:
  13137. internalFormat = this._gl.RGBA;
  13138. break;
  13139. case Engine.TEXTUREFORMAT_R32F:
  13140. internalFormat = this._gl.RED;
  13141. break;
  13142. case Engine.TEXTUREFORMAT_RG32F:
  13143. internalFormat = this._gl.RG;
  13144. break;
  13145. }
  13146. return internalFormat;
  13147. };
  13148. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13149. if (compression === void 0) { compression = null; }
  13150. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13151. if (!texture) {
  13152. return;
  13153. }
  13154. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13155. var internalFormat = this._getInternalFormat(format);
  13156. var textureType = this._getWebGLTextureType(type);
  13157. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13158. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13159. if (!this._doNotHandleContextLost) {
  13160. texture._bufferView = data;
  13161. texture.format = format;
  13162. texture.type = type;
  13163. texture.invertY = invertY;
  13164. texture._compression = compression;
  13165. }
  13166. if (texture.width % 4 !== 0) {
  13167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13168. }
  13169. if (compression && data) {
  13170. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13171. }
  13172. else {
  13173. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13174. }
  13175. if (texture.generateMipMaps) {
  13176. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13177. }
  13178. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13179. // this.resetTextureCache();
  13180. texture.isReady = true;
  13181. };
  13182. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13183. if (compression === void 0) { compression = null; }
  13184. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13185. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13186. texture.baseWidth = width;
  13187. texture.baseHeight = height;
  13188. texture.width = width;
  13189. texture.height = height;
  13190. texture.format = format;
  13191. texture.generateMipMaps = generateMipMaps;
  13192. texture.samplingMode = samplingMode;
  13193. texture.invertY = invertY;
  13194. texture._compression = compression;
  13195. texture.type = type;
  13196. if (!this._doNotHandleContextLost) {
  13197. texture._bufferView = data;
  13198. }
  13199. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13201. // Filters
  13202. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13205. if (generateMipMaps) {
  13206. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13207. }
  13208. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13209. this._internalTexturesCache.push(texture);
  13210. return texture;
  13211. };
  13212. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13213. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13214. texture.baseWidth = width;
  13215. texture.baseHeight = height;
  13216. if (generateMipMaps) {
  13217. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13218. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13219. }
  13220. // this.resetTextureCache();
  13221. texture.width = width;
  13222. texture.height = height;
  13223. texture.isReady = false;
  13224. texture.generateMipMaps = generateMipMaps;
  13225. texture.samplingMode = samplingMode;
  13226. this.updateTextureSamplingMode(samplingMode, texture);
  13227. this._internalTexturesCache.push(texture);
  13228. return texture;
  13229. };
  13230. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13231. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13232. if (texture.isCube) {
  13233. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13234. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13235. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13236. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13237. }
  13238. else if (texture.is3D) {
  13239. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13240. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13241. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13242. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13243. }
  13244. else {
  13245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13246. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13249. }
  13250. texture.samplingMode = samplingMode;
  13251. };
  13252. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13253. if (premulAlpha === void 0) { premulAlpha = false; }
  13254. if (!texture) {
  13255. return;
  13256. }
  13257. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13258. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13259. if (premulAlpha) {
  13260. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13261. }
  13262. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13263. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13264. if (texture.generateMipMaps) {
  13265. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13266. }
  13267. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13268. if (premulAlpha) {
  13269. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13270. }
  13271. texture.isReady = true;
  13272. };
  13273. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13274. if (!texture || texture._isDisabled) {
  13275. return;
  13276. }
  13277. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13278. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13279. try {
  13280. // Testing video texture support
  13281. if (this._videoTextureSupported === undefined) {
  13282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13283. if (this._gl.getError() !== 0) {
  13284. this._videoTextureSupported = false;
  13285. }
  13286. else {
  13287. this._videoTextureSupported = true;
  13288. }
  13289. }
  13290. // Copy video through the current working canvas if video texture is not supported
  13291. if (!this._videoTextureSupported) {
  13292. if (!texture._workingCanvas) {
  13293. texture._workingCanvas = document.createElement("canvas");
  13294. var context = texture._workingCanvas.getContext("2d");
  13295. if (!context) {
  13296. throw new Error("Unable to get 2d context");
  13297. }
  13298. texture._workingContext = context;
  13299. texture._workingCanvas.width = texture.width;
  13300. texture._workingCanvas.height = texture.height;
  13301. }
  13302. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13303. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13304. }
  13305. else {
  13306. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13307. }
  13308. if (texture.generateMipMaps) {
  13309. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13310. }
  13311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13312. // this.resetTextureCache();
  13313. texture.isReady = true;
  13314. }
  13315. catch (ex) {
  13316. // Something unexpected
  13317. // Let's disable the texture
  13318. texture._isDisabled = true;
  13319. }
  13320. };
  13321. /**
  13322. * Updates a depth texture Comparison Mode and Function.
  13323. * If the comparison Function is equal to 0, the mode will be set to none.
  13324. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13325. * @param texture The texture to set the comparison function for
  13326. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13327. */
  13328. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13329. if (this.webGLVersion === 1) {
  13330. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13331. return;
  13332. }
  13333. var gl = this._gl;
  13334. if (texture.isCube) {
  13335. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13336. if (comparisonFunction === 0) {
  13337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13339. }
  13340. else {
  13341. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13343. }
  13344. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13345. }
  13346. else {
  13347. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13348. if (comparisonFunction === 0) {
  13349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13351. }
  13352. else {
  13353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13355. }
  13356. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13357. }
  13358. texture._comparisonFunction = comparisonFunction;
  13359. };
  13360. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13361. var width = size.width || size;
  13362. var height = size.height || size;
  13363. internalTexture.baseWidth = width;
  13364. internalTexture.baseHeight = height;
  13365. internalTexture.width = width;
  13366. internalTexture.height = height;
  13367. internalTexture.isReady = true;
  13368. internalTexture.samples = 1;
  13369. internalTexture.generateMipMaps = false;
  13370. internalTexture._generateDepthBuffer = true;
  13371. internalTexture._generateStencilBuffer = generateStencil;
  13372. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13373. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13374. internalTexture._comparisonFunction = comparisonFunction;
  13375. var gl = this._gl;
  13376. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13377. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13378. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13379. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13380. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13381. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13382. if (comparisonFunction === 0) {
  13383. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13384. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13385. }
  13386. else {
  13387. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13388. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13389. }
  13390. };
  13391. /**
  13392. * Creates a depth stencil texture.
  13393. * This is only available in WebGL 2 or with the depth texture extension available.
  13394. * @param size The size of face edge in the texture.
  13395. * @param options The options defining the texture.
  13396. * @returns The texture
  13397. */
  13398. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13399. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13400. if (!this._caps.depthTextureExtension) {
  13401. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13402. return internalTexture;
  13403. }
  13404. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13405. var gl = this._gl;
  13406. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13407. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13408. if (this.webGLVersion > 1) {
  13409. if (internalOptions.generateStencil) {
  13410. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13411. }
  13412. else {
  13413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13414. }
  13415. }
  13416. else {
  13417. if (internalOptions.generateStencil) {
  13418. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13419. }
  13420. else {
  13421. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13422. }
  13423. }
  13424. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13425. return internalTexture;
  13426. };
  13427. /**
  13428. * Creates a depth stencil cube texture.
  13429. * This is only available in WebGL 2.
  13430. * @param size The size of face edge in the cube texture.
  13431. * @param options The options defining the cube texture.
  13432. * @returns The cube texture
  13433. */
  13434. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13435. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13436. internalTexture.isCube = true;
  13437. if (this.webGLVersion === 1) {
  13438. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13439. return internalTexture;
  13440. }
  13441. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13442. var gl = this._gl;
  13443. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13444. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13445. // Create the depth/stencil buffer
  13446. for (var face = 0; face < 6; face++) {
  13447. if (internalOptions.generateStencil) {
  13448. 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);
  13449. }
  13450. else {
  13451. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13452. }
  13453. }
  13454. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13455. return internalTexture;
  13456. };
  13457. /**
  13458. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13459. * @param renderTarget The render target to set the frame buffer for
  13460. */
  13461. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13462. // Create the framebuffer
  13463. var internalTexture = renderTarget.getInternalTexture();
  13464. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13465. return;
  13466. }
  13467. var gl = this._gl;
  13468. var depthStencilTexture = renderTarget.depthStencilTexture;
  13469. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13470. if (depthStencilTexture.isCube) {
  13471. if (depthStencilTexture._generateStencilBuffer) {
  13472. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13473. }
  13474. else {
  13475. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13476. }
  13477. }
  13478. else {
  13479. if (depthStencilTexture._generateStencilBuffer) {
  13480. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13481. }
  13482. else {
  13483. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13484. }
  13485. }
  13486. this.bindUnboundFramebuffer(null);
  13487. };
  13488. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13489. var fullOptions = new RenderTargetCreationOptions();
  13490. if (options !== undefined && typeof options === "object") {
  13491. fullOptions.generateMipMaps = options.generateMipMaps;
  13492. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13493. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13494. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13495. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13496. }
  13497. else {
  13498. fullOptions.generateMipMaps = options;
  13499. fullOptions.generateDepthBuffer = true;
  13500. fullOptions.generateStencilBuffer = false;
  13501. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13502. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13503. }
  13504. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13505. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13506. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13507. }
  13508. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13509. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13510. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13511. }
  13512. var gl = this._gl;
  13513. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13514. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13515. var width = size.width || size;
  13516. var height = size.height || size;
  13517. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13518. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13519. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13520. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13521. }
  13522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13526. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13527. // Create the framebuffer
  13528. var framebuffer = gl.createFramebuffer();
  13529. this.bindUnboundFramebuffer(framebuffer);
  13530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13531. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13532. if (fullOptions.generateMipMaps) {
  13533. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13534. }
  13535. // Unbind
  13536. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13537. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13538. this.bindUnboundFramebuffer(null);
  13539. texture._framebuffer = framebuffer;
  13540. texture.baseWidth = width;
  13541. texture.baseHeight = height;
  13542. texture.width = width;
  13543. texture.height = height;
  13544. texture.isReady = true;
  13545. texture.samples = 1;
  13546. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13547. texture.samplingMode = fullOptions.samplingMode;
  13548. texture.type = fullOptions.type;
  13549. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13550. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13551. // this.resetTextureCache();
  13552. this._internalTexturesCache.push(texture);
  13553. return texture;
  13554. };
  13555. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13556. var generateMipMaps = false;
  13557. var generateDepthBuffer = true;
  13558. var generateStencilBuffer = false;
  13559. var generateDepthTexture = false;
  13560. var textureCount = 1;
  13561. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13562. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13563. var types = [], samplingModes = [];
  13564. if (options !== undefined) {
  13565. generateMipMaps = options.generateMipMaps;
  13566. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13567. generateStencilBuffer = options.generateStencilBuffer;
  13568. generateDepthTexture = options.generateDepthTexture;
  13569. textureCount = options.textureCount || 1;
  13570. if (options.types) {
  13571. types = options.types;
  13572. }
  13573. if (options.samplingModes) {
  13574. samplingModes = options.samplingModes;
  13575. }
  13576. }
  13577. var gl = this._gl;
  13578. // Create the framebuffer
  13579. var framebuffer = gl.createFramebuffer();
  13580. this.bindUnboundFramebuffer(framebuffer);
  13581. var width = size.width || size;
  13582. var height = size.height || size;
  13583. var textures = [];
  13584. var attachments = [];
  13585. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13586. for (var i = 0; i < textureCount; i++) {
  13587. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13588. var type = types[i] || defaultType;
  13589. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13590. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13591. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13592. }
  13593. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13594. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13595. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13596. }
  13597. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13598. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13599. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13600. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13601. }
  13602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13603. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13604. textures.push(texture);
  13605. attachments.push(attachment);
  13606. gl.activeTexture(gl["TEXTURE" + i]);
  13607. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13612. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13613. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13614. if (generateMipMaps) {
  13615. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13616. }
  13617. // Unbind
  13618. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13619. texture._framebuffer = framebuffer;
  13620. texture._depthStencilBuffer = depthStencilBuffer;
  13621. texture.baseWidth = width;
  13622. texture.baseHeight = height;
  13623. texture.width = width;
  13624. texture.height = height;
  13625. texture.isReady = true;
  13626. texture.samples = 1;
  13627. texture.generateMipMaps = generateMipMaps;
  13628. texture.samplingMode = samplingMode;
  13629. texture.type = type;
  13630. texture._generateDepthBuffer = generateDepthBuffer;
  13631. texture._generateStencilBuffer = generateStencilBuffer;
  13632. texture._attachments = attachments;
  13633. this._internalTexturesCache.push(texture);
  13634. }
  13635. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13636. // Depth texture
  13637. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13638. gl.activeTexture(gl.TEXTURE0);
  13639. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13640. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13644. 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);
  13645. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13646. depthTexture._framebuffer = framebuffer;
  13647. depthTexture.baseWidth = width;
  13648. depthTexture.baseHeight = height;
  13649. depthTexture.width = width;
  13650. depthTexture.height = height;
  13651. depthTexture.isReady = true;
  13652. depthTexture.samples = 1;
  13653. depthTexture.generateMipMaps = generateMipMaps;
  13654. depthTexture.samplingMode = gl.NEAREST;
  13655. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13656. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13657. textures.push(depthTexture);
  13658. this._internalTexturesCache.push(depthTexture);
  13659. }
  13660. gl.drawBuffers(attachments);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. this.resetTextureCache();
  13664. return textures;
  13665. };
  13666. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13667. if (samples === void 0) { samples = 1; }
  13668. var depthStencilBuffer = null;
  13669. var gl = this._gl;
  13670. // Create the depth/stencil buffer
  13671. if (generateStencilBuffer) {
  13672. depthStencilBuffer = gl.createRenderbuffer();
  13673. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13674. if (samples > 1) {
  13675. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13676. }
  13677. else {
  13678. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13679. }
  13680. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13681. }
  13682. else if (generateDepthBuffer) {
  13683. depthStencilBuffer = gl.createRenderbuffer();
  13684. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13685. if (samples > 1) {
  13686. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13687. }
  13688. else {
  13689. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13690. }
  13691. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13692. }
  13693. return depthStencilBuffer;
  13694. };
  13695. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13696. if (this.webGLVersion < 2 || !texture) {
  13697. return 1;
  13698. }
  13699. if (texture.samples === samples) {
  13700. return samples;
  13701. }
  13702. var gl = this._gl;
  13703. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13704. // Dispose previous render buffers
  13705. if (texture._depthStencilBuffer) {
  13706. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13707. texture._depthStencilBuffer = null;
  13708. }
  13709. if (texture._MSAAFramebuffer) {
  13710. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13711. texture._MSAAFramebuffer = null;
  13712. }
  13713. if (texture._MSAARenderBuffer) {
  13714. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13715. texture._MSAARenderBuffer = null;
  13716. }
  13717. if (samples > 1) {
  13718. var framebuffer = gl.createFramebuffer();
  13719. if (!framebuffer) {
  13720. throw new Error("Unable to create multi sampled framebuffer");
  13721. }
  13722. texture._MSAAFramebuffer = framebuffer;
  13723. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13724. var colorRenderbuffer = gl.createRenderbuffer();
  13725. if (!colorRenderbuffer) {
  13726. throw new Error("Unable to create multi sampled framebuffer");
  13727. }
  13728. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13729. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13730. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13731. texture._MSAARenderBuffer = colorRenderbuffer;
  13732. }
  13733. else {
  13734. this.bindUnboundFramebuffer(texture._framebuffer);
  13735. }
  13736. texture.samples = samples;
  13737. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13738. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13739. this.bindUnboundFramebuffer(null);
  13740. return samples;
  13741. };
  13742. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13743. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13744. return 1;
  13745. }
  13746. if (textures[0].samples === samples) {
  13747. return samples;
  13748. }
  13749. var gl = this._gl;
  13750. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13751. // Dispose previous render buffers
  13752. if (textures[0]._depthStencilBuffer) {
  13753. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13754. textures[0]._depthStencilBuffer = null;
  13755. }
  13756. if (textures[0]._MSAAFramebuffer) {
  13757. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13758. textures[0]._MSAAFramebuffer = null;
  13759. }
  13760. for (var i = 0; i < textures.length; i++) {
  13761. if (textures[i]._MSAARenderBuffer) {
  13762. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13763. textures[i]._MSAARenderBuffer = null;
  13764. }
  13765. }
  13766. if (samples > 1) {
  13767. var framebuffer = gl.createFramebuffer();
  13768. if (!framebuffer) {
  13769. throw new Error("Unable to create multi sampled framebuffer");
  13770. }
  13771. this.bindUnboundFramebuffer(framebuffer);
  13772. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13773. var attachments = [];
  13774. for (var i = 0; i < textures.length; i++) {
  13775. var texture = textures[i];
  13776. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13777. var colorRenderbuffer = gl.createRenderbuffer();
  13778. if (!colorRenderbuffer) {
  13779. throw new Error("Unable to create multi sampled framebuffer");
  13780. }
  13781. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13782. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13784. texture._MSAAFramebuffer = framebuffer;
  13785. texture._MSAARenderBuffer = colorRenderbuffer;
  13786. texture.samples = samples;
  13787. texture._depthStencilBuffer = depthStencilBuffer;
  13788. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13789. attachments.push(attachment);
  13790. }
  13791. gl.drawBuffers(attachments);
  13792. }
  13793. else {
  13794. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13795. }
  13796. this.bindUnboundFramebuffer(null);
  13797. return samples;
  13798. };
  13799. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13800. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13801. };
  13802. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13803. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13804. };
  13805. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13806. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13807. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13808. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13809. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13810. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13811. }
  13812. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13813. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13814. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13815. }
  13816. var gl = this._gl;
  13817. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13818. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13819. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13820. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13821. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13822. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13823. }
  13824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13828. for (var face = 0; face < 6; face++) {
  13829. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13830. }
  13831. // Create the framebuffer
  13832. var framebuffer = gl.createFramebuffer();
  13833. this.bindUnboundFramebuffer(framebuffer);
  13834. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13835. // MipMaps
  13836. if (fullOptions.generateMipMaps) {
  13837. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13838. }
  13839. // Unbind
  13840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. this.bindUnboundFramebuffer(null);
  13843. texture._framebuffer = framebuffer;
  13844. texture.width = size;
  13845. texture.height = size;
  13846. texture.isReady = true;
  13847. texture.isCube = true;
  13848. texture.samples = 1;
  13849. texture.generateMipMaps = fullOptions.generateMipMaps;
  13850. texture.samplingMode = fullOptions.samplingMode;
  13851. texture.type = fullOptions.type;
  13852. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13853. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13854. this._internalTexturesCache.push(texture);
  13855. return texture;
  13856. };
  13857. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13858. var _this = this;
  13859. if (onLoad === void 0) { onLoad = null; }
  13860. if (onError === void 0) { onError = null; }
  13861. if (forcedExtension === void 0) { forcedExtension = null; }
  13862. var callback = function (loadData) {
  13863. if (!loadData) {
  13864. if (onLoad) {
  13865. onLoad(null);
  13866. }
  13867. return;
  13868. }
  13869. var texture = loadData.texture;
  13870. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13871. texture._lodGenerationScale = scale;
  13872. texture._lodGenerationOffset = offset;
  13873. if (_this._caps.textureLOD) {
  13874. // Do not add extra process if texture lod is supported.
  13875. if (onLoad) {
  13876. onLoad(texture);
  13877. }
  13878. return;
  13879. }
  13880. var mipSlices = 3;
  13881. var gl = _this._gl;
  13882. var width = loadData.width;
  13883. if (!width) {
  13884. return;
  13885. }
  13886. var textures = [];
  13887. for (var i = 0; i < mipSlices; i++) {
  13888. //compute LOD from even spacing in smoothness (matching shader calculation)
  13889. var smoothness = i / (mipSlices - 1);
  13890. var roughness = 1 - smoothness;
  13891. var minLODIndex = offset; // roughness = 0
  13892. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13893. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13894. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13895. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13896. glTextureFromLod.isCube = true;
  13897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13902. if (loadData.isDDS) {
  13903. var info = loadData.info;
  13904. var data = loadData.data;
  13905. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13906. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13907. }
  13908. else {
  13909. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13910. }
  13911. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13912. // Wrap in a base texture for easy binding.
  13913. var lodTexture = new BABYLON.BaseTexture(scene);
  13914. lodTexture.isCube = true;
  13915. lodTexture._texture = glTextureFromLod;
  13916. glTextureFromLod.isReady = true;
  13917. textures.push(lodTexture);
  13918. }
  13919. texture._lodTextureHigh = textures[2];
  13920. texture._lodTextureMid = textures[1];
  13921. texture._lodTextureLow = textures[0];
  13922. if (onLoad) {
  13923. onLoad(texture);
  13924. }
  13925. };
  13926. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13927. };
  13928. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13929. var _this = this;
  13930. if (onLoad === void 0) { onLoad = null; }
  13931. if (onError === void 0) { onError = null; }
  13932. if (forcedExtension === void 0) { forcedExtension = null; }
  13933. var gl = this._gl;
  13934. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13935. texture.isCube = true;
  13936. texture.url = rootUrl;
  13937. texture.generateMipMaps = !noMipmap;
  13938. if (!this._doNotHandleContextLost) {
  13939. texture._extension = forcedExtension;
  13940. texture._files = files;
  13941. }
  13942. var isKTX = false;
  13943. var isDDS = false;
  13944. var lastDot = rootUrl.lastIndexOf('.');
  13945. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13946. if (this._textureFormatInUse) {
  13947. extension = this._textureFormatInUse;
  13948. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13949. isKTX = true;
  13950. }
  13951. else {
  13952. isDDS = (extension === ".dds");
  13953. }
  13954. var onerror = function (request, exception) {
  13955. if (onError && request) {
  13956. onError(request.status + " " + request.statusText, exception);
  13957. }
  13958. };
  13959. if (isKTX) {
  13960. this._loadFile(rootUrl, function (data) {
  13961. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13962. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13963. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13965. ktx.uploadLevels(_this._gl, !noMipmap);
  13966. _this.setCubeMapTextureParams(gl, loadMipmap);
  13967. texture.width = ktx.pixelWidth;
  13968. texture.height = ktx.pixelHeight;
  13969. texture.isReady = true;
  13970. }, undefined, undefined, true, onerror);
  13971. }
  13972. else if (isDDS) {
  13973. if (files && files.length === 6) {
  13974. this._cascadeLoadFiles(scene, function (imgs) {
  13975. var info;
  13976. var loadMipmap = false;
  13977. var width = 0;
  13978. for (var index = 0; index < imgs.length; index++) {
  13979. var data = imgs[index];
  13980. info = BABYLON.DDSTools.GetDDSInfo(data);
  13981. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13982. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13983. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13984. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13985. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13986. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13987. }
  13988. texture.width = info.width;
  13989. texture.height = info.height;
  13990. texture.type = info.textureType;
  13991. width = info.width;
  13992. }
  13993. _this.setCubeMapTextureParams(gl, loadMipmap);
  13994. texture.isReady = true;
  13995. if (onLoad) {
  13996. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13997. }
  13998. }, files, onError);
  13999. }
  14000. else {
  14001. this._loadFile(rootUrl, function (data) {
  14002. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14003. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14005. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14006. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14007. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14008. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14009. }
  14010. _this.setCubeMapTextureParams(gl, loadMipmap);
  14011. texture.width = info.width;
  14012. texture.height = info.height;
  14013. texture.isReady = true;
  14014. texture.type = info.textureType;
  14015. if (onLoad) {
  14016. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14017. }
  14018. }, undefined, undefined, true, onerror);
  14019. }
  14020. }
  14021. else {
  14022. if (!files) {
  14023. throw new Error("Cannot load cubemap because files were not defined");
  14024. }
  14025. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14026. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14027. var height = width;
  14028. _this._prepareWorkingCanvas();
  14029. if (!_this._workingCanvas || !_this._workingContext) {
  14030. return;
  14031. }
  14032. _this._workingCanvas.width = width;
  14033. _this._workingCanvas.height = height;
  14034. var faces = [
  14035. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14036. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14037. ];
  14038. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14039. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14040. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14041. for (var index = 0; index < faces.length; index++) {
  14042. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14043. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14044. }
  14045. if (!noMipmap) {
  14046. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14047. }
  14048. _this.setCubeMapTextureParams(gl, !noMipmap);
  14049. texture.width = width;
  14050. texture.height = height;
  14051. texture.isReady = true;
  14052. if (format) {
  14053. texture.format = format;
  14054. }
  14055. texture.onLoadedObservable.notifyObservers(texture);
  14056. texture.onLoadedObservable.clear();
  14057. if (onLoad) {
  14058. onLoad();
  14059. }
  14060. }, files, onError);
  14061. }
  14062. this._internalTexturesCache.push(texture);
  14063. return texture;
  14064. };
  14065. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14071. // this.resetTextureCache();
  14072. };
  14073. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14074. if (compression === void 0) { compression = null; }
  14075. if (level === void 0) { level = 0; }
  14076. texture._bufferViewArray = data;
  14077. texture.format = format;
  14078. texture.type = type;
  14079. texture.invertY = invertY;
  14080. texture._compression = compression;
  14081. var gl = this._gl;
  14082. var textureType = this._getWebGLTextureType(type);
  14083. var internalFormat = this._getInternalFormat(format);
  14084. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14085. var needConversion = false;
  14086. if (internalFormat === gl.RGB) {
  14087. internalFormat = gl.RGBA;
  14088. needConversion = true;
  14089. }
  14090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14092. if (texture.width % 4 !== 0) {
  14093. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14094. }
  14095. // Data are known to be in +X +Y +Z -X -Y -Z
  14096. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14097. var faceData = data[faceIndex];
  14098. if (compression) {
  14099. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14100. }
  14101. else {
  14102. if (needConversion) {
  14103. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14104. }
  14105. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14106. }
  14107. }
  14108. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14109. if (isPot && texture.generateMipMaps && level === 0) {
  14110. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14113. // this.resetTextureCache();
  14114. texture.isReady = true;
  14115. };
  14116. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14117. if (compression === void 0) { compression = null; }
  14118. var gl = this._gl;
  14119. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14120. texture.isCube = true;
  14121. texture.generateMipMaps = generateMipMaps;
  14122. texture.format = format;
  14123. texture.type = type;
  14124. if (!this._doNotHandleContextLost) {
  14125. texture._bufferViewArray = data;
  14126. }
  14127. var textureType = this._getWebGLTextureType(type);
  14128. var internalFormat = this._getInternalFormat(format);
  14129. if (internalFormat === gl.RGB) {
  14130. internalFormat = gl.RGBA;
  14131. }
  14132. var width = size;
  14133. var height = width;
  14134. texture.width = width;
  14135. texture.height = height;
  14136. // Double check on POT to generate Mips.
  14137. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14138. if (!isPot) {
  14139. generateMipMaps = false;
  14140. }
  14141. // Upload data if needed. The texture won't be ready until then.
  14142. if (data) {
  14143. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14144. }
  14145. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14146. // Filters
  14147. if (data && generateMipMaps) {
  14148. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14149. }
  14150. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14153. }
  14154. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14157. }
  14158. else {
  14159. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14162. }
  14163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14165. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14166. return texture;
  14167. };
  14168. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14169. var _this = this;
  14170. if (onLoad === void 0) { onLoad = null; }
  14171. if (onError === void 0) { onError = null; }
  14172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14173. if (invertY === void 0) { invertY = false; }
  14174. var gl = this._gl;
  14175. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14176. scene._addPendingData(texture);
  14177. texture.url = url;
  14178. this._internalTexturesCache.push(texture);
  14179. var onerror = function (request, exception) {
  14180. scene._removePendingData(texture);
  14181. if (onError && request) {
  14182. onError(request.status + " " + request.statusText, exception);
  14183. }
  14184. };
  14185. var internalCallback = function (data) {
  14186. var width = texture.width;
  14187. var faceDataArrays = callback(data);
  14188. if (!faceDataArrays) {
  14189. return;
  14190. }
  14191. if (mipmmapGenerator) {
  14192. var textureType = _this._getWebGLTextureType(type);
  14193. var internalFormat = _this._getInternalFormat(format);
  14194. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14195. var needConversion = false;
  14196. if (internalFormat === gl.RGB) {
  14197. internalFormat = gl.RGBA;
  14198. needConversion = true;
  14199. }
  14200. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14201. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14202. var mipData = mipmmapGenerator(faceDataArrays);
  14203. for (var level = 0; level < mipData.length; level++) {
  14204. var mipSize = width >> level;
  14205. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14206. var mipFaceData = mipData[level][faceIndex];
  14207. if (needConversion) {
  14208. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14209. }
  14210. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14211. }
  14212. }
  14213. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14214. }
  14215. else {
  14216. texture.generateMipMaps = !noMipmap;
  14217. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14218. }
  14219. texture.isReady = true;
  14220. // this.resetTextureCache();
  14221. scene._removePendingData(texture);
  14222. if (onLoad) {
  14223. onLoad();
  14224. }
  14225. };
  14226. this._loadFile(url, function (data) {
  14227. internalCallback(data);
  14228. }, undefined, scene.database, true, onerror);
  14229. return texture;
  14230. };
  14231. ;
  14232. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14233. if (compression === void 0) { compression = null; }
  14234. var internalFormat = this._getInternalFormat(format);
  14235. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14236. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14237. if (!this._doNotHandleContextLost) {
  14238. texture._bufferView = data;
  14239. texture.format = format;
  14240. texture.invertY = invertY;
  14241. texture._compression = compression;
  14242. }
  14243. if (texture.width % 4 !== 0) {
  14244. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14245. }
  14246. if (compression && data) {
  14247. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14248. }
  14249. else {
  14250. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14251. }
  14252. if (texture.generateMipMaps) {
  14253. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14254. }
  14255. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14256. // this.resetTextureCache();
  14257. texture.isReady = true;
  14258. };
  14259. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14260. if (compression === void 0) { compression = null; }
  14261. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14262. texture.baseWidth = width;
  14263. texture.baseHeight = height;
  14264. texture.baseDepth = depth;
  14265. texture.width = width;
  14266. texture.height = height;
  14267. texture.depth = depth;
  14268. texture.format = format;
  14269. texture.generateMipMaps = generateMipMaps;
  14270. texture.samplingMode = samplingMode;
  14271. texture.is3D = true;
  14272. if (!this._doNotHandleContextLost) {
  14273. texture._bufferView = data;
  14274. }
  14275. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14276. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14277. // Filters
  14278. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14279. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14281. if (generateMipMaps) {
  14282. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14283. }
  14284. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14285. this._internalTexturesCache.push(texture);
  14286. return texture;
  14287. };
  14288. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14289. var gl = this._gl;
  14290. if (!gl) {
  14291. return;
  14292. }
  14293. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14296. if (!noMipmap && !isCompressed) {
  14297. gl.generateMipmap(gl.TEXTURE_2D);
  14298. }
  14299. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14300. // this.resetTextureCache();
  14301. if (scene) {
  14302. scene._removePendingData(texture);
  14303. }
  14304. texture.onLoadedObservable.notifyObservers(texture);
  14305. texture.onLoadedObservable.clear();
  14306. };
  14307. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14308. var _this = this;
  14309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14310. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14311. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14312. var gl = this._gl;
  14313. if (!gl) {
  14314. return;
  14315. }
  14316. if (!texture._webGLTexture) {
  14317. // this.resetTextureCache();
  14318. if (scene) {
  14319. scene._removePendingData(texture);
  14320. }
  14321. return;
  14322. }
  14323. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14325. texture.baseWidth = width;
  14326. texture.baseHeight = height;
  14327. texture.width = potWidth;
  14328. texture.height = potHeight;
  14329. texture.isReady = true;
  14330. if (processFunction(potWidth, potHeight, function () {
  14331. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14332. })) {
  14333. // Returning as texture needs extra async steps
  14334. return;
  14335. }
  14336. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14337. };
  14338. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14339. // Create new RGBA data container.
  14340. var rgbaData;
  14341. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14342. rgbaData = new Float32Array(width * height * 4);
  14343. }
  14344. else {
  14345. rgbaData = new Uint32Array(width * height * 4);
  14346. }
  14347. // Convert each pixel.
  14348. for (var x = 0; x < width; x++) {
  14349. for (var y = 0; y < height; y++) {
  14350. var index = (y * width + x) * 3;
  14351. var newIndex = (y * width + x) * 4;
  14352. // Map Old Value to new value.
  14353. rgbaData[newIndex + 0] = rgbData[index + 0];
  14354. rgbaData[newIndex + 1] = rgbData[index + 1];
  14355. rgbaData[newIndex + 2] = rgbData[index + 2];
  14356. // Add fully opaque alpha channel.
  14357. rgbaData[newIndex + 3] = 1;
  14358. }
  14359. }
  14360. return rgbaData;
  14361. };
  14362. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14363. var gl = this._gl;
  14364. if (texture._framebuffer) {
  14365. gl.deleteFramebuffer(texture._framebuffer);
  14366. texture._framebuffer = null;
  14367. }
  14368. if (texture._depthStencilBuffer) {
  14369. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14370. texture._depthStencilBuffer = null;
  14371. }
  14372. if (texture._MSAAFramebuffer) {
  14373. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14374. texture._MSAAFramebuffer = null;
  14375. }
  14376. if (texture._MSAARenderBuffer) {
  14377. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14378. texture._MSAARenderBuffer = null;
  14379. }
  14380. };
  14381. Engine.prototype._releaseTexture = function (texture) {
  14382. var gl = this._gl;
  14383. this._releaseFramebufferObjects(texture);
  14384. gl.deleteTexture(texture._webGLTexture);
  14385. // Unbind channels
  14386. this.unbindAllTextures();
  14387. var index = this._internalTexturesCache.indexOf(texture);
  14388. if (index !== -1) {
  14389. this._internalTexturesCache.splice(index, 1);
  14390. }
  14391. // Integrated fixed lod samplers.
  14392. if (texture._lodTextureHigh) {
  14393. texture._lodTextureHigh.dispose();
  14394. }
  14395. if (texture._lodTextureMid) {
  14396. texture._lodTextureMid.dispose();
  14397. }
  14398. if (texture._lodTextureLow) {
  14399. texture._lodTextureLow.dispose();
  14400. }
  14401. };
  14402. Engine.prototype.setProgram = function (program) {
  14403. if (this._currentProgram !== program) {
  14404. this._gl.useProgram(program);
  14405. this._currentProgram = program;
  14406. }
  14407. };
  14408. Engine.prototype.bindSamplers = function (effect) {
  14409. this.setProgram(effect.getProgram());
  14410. var samplers = effect.getSamplers();
  14411. for (var index = 0; index < samplers.length; index++) {
  14412. var uniform = effect.getUniform(samplers[index]);
  14413. if (uniform) {
  14414. this._boundUniforms[index] = uniform;
  14415. }
  14416. }
  14417. this._currentEffect = null;
  14418. };
  14419. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14420. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14421. return;
  14422. }
  14423. // Remove
  14424. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14425. // Bind last to it
  14426. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14427. // Bind to dummy
  14428. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14429. };
  14430. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14431. if (!internalTexture) {
  14432. return -1;
  14433. }
  14434. internalTexture._initialSlot = channel;
  14435. if (this.disableTextureBindingOptimization) {
  14436. if (channel !== internalTexture._designatedSlot) {
  14437. this._textureCollisions.addCount(1, false);
  14438. }
  14439. }
  14440. else {
  14441. if (channel !== internalTexture._designatedSlot) {
  14442. if (internalTexture._designatedSlot > -1) {
  14443. return internalTexture._designatedSlot;
  14444. }
  14445. else {
  14446. // No slot for this texture, let's pick a new one (if we find a free slot)
  14447. if (this._nextFreeTextureSlots.length) {
  14448. return this._nextFreeTextureSlots[0];
  14449. }
  14450. // We need to recycle the oldest bound texture, sorry.
  14451. this._textureCollisions.addCount(1, false);
  14452. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14453. }
  14454. }
  14455. }
  14456. return channel;
  14457. };
  14458. Engine.prototype._linkTrackers = function (previous, next) {
  14459. previous.next = next;
  14460. next.previous = previous;
  14461. };
  14462. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14463. var currentSlot = internalTexture._designatedSlot;
  14464. if (currentSlot === -1) {
  14465. return -1;
  14466. }
  14467. internalTexture._designatedSlot = -1;
  14468. if (this.disableTextureBindingOptimization) {
  14469. return -1;
  14470. }
  14471. // Remove from bound list
  14472. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14473. // Free the slot
  14474. this._boundTexturesCache[currentSlot] = null;
  14475. this._nextFreeTextureSlots.push(currentSlot);
  14476. return currentSlot;
  14477. };
  14478. Engine.prototype._activateCurrentTexture = function () {
  14479. if (this._currentTextureChannel !== this._activeChannel) {
  14480. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14481. this._currentTextureChannel = this._activeChannel;
  14482. }
  14483. };
  14484. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14485. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14486. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14487. this._activeChannel = texture._designatedSlot;
  14488. }
  14489. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14490. var isTextureForRendering = texture && texture._initialSlot > -1;
  14491. if (currentTextureBound !== texture) {
  14492. if (currentTextureBound) {
  14493. this._removeDesignatedSlot(currentTextureBound);
  14494. }
  14495. this._activateCurrentTexture();
  14496. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14497. this._boundTexturesCache[this._activeChannel] = texture;
  14498. if (texture) {
  14499. if (!this.disableTextureBindingOptimization) {
  14500. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14501. if (slotIndex > -1) {
  14502. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14503. }
  14504. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14505. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14506. }
  14507. texture._designatedSlot = this._activeChannel;
  14508. }
  14509. }
  14510. else if (forTextureDataUpdate) {
  14511. this._activateCurrentTexture();
  14512. }
  14513. if (isTextureForRendering && !forTextureDataUpdate) {
  14514. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14515. }
  14516. };
  14517. Engine.prototype._bindTexture = function (channel, texture) {
  14518. if (channel < 0) {
  14519. return;
  14520. }
  14521. if (texture) {
  14522. channel = this._getCorrectTextureChannel(channel, texture);
  14523. }
  14524. this._activeChannel = channel;
  14525. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14526. };
  14527. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14528. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14529. };
  14530. Engine.prototype.unbindAllTextures = function () {
  14531. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14532. this._activeChannel = channel;
  14533. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14534. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14535. if (this.webGLVersion > 1) {
  14536. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14537. }
  14538. }
  14539. };
  14540. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14541. if (channel < 0) {
  14542. return;
  14543. }
  14544. if (uniform) {
  14545. this._boundUniforms[channel] = uniform;
  14546. }
  14547. this._setTexture(channel, texture);
  14548. };
  14549. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14550. var uniform = this._boundUniforms[sourceSlot];
  14551. if (uniform._currentState === destination) {
  14552. return;
  14553. }
  14554. this._gl.uniform1i(uniform, destination);
  14555. uniform._currentState = destination;
  14556. };
  14557. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14558. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14559. // Not ready?
  14560. if (!texture) {
  14561. if (this._boundTexturesCache[channel] != null) {
  14562. this._activeChannel = channel;
  14563. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14564. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14565. if (this.webGLVersion > 1) {
  14566. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14567. }
  14568. }
  14569. return false;
  14570. }
  14571. // Video
  14572. if (texture.video) {
  14573. this._activeChannel = channel;
  14574. texture.update();
  14575. }
  14576. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14577. texture.delayLoad();
  14578. return false;
  14579. }
  14580. var internalTexture;
  14581. if (texture.isReady()) {
  14582. internalTexture = texture.getInternalTexture();
  14583. }
  14584. else if (texture.isCube) {
  14585. internalTexture = this.emptyCubeTexture;
  14586. }
  14587. else if (texture.is3D) {
  14588. internalTexture = this.emptyTexture3D;
  14589. }
  14590. else {
  14591. internalTexture = this.emptyTexture;
  14592. }
  14593. if (!isPartOfTextureArray) {
  14594. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14595. }
  14596. if (this._boundTexturesCache[channel] === internalTexture) {
  14597. this._moveBoundTextureOnTop(internalTexture);
  14598. if (!isPartOfTextureArray) {
  14599. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14600. }
  14601. return false;
  14602. }
  14603. this._activeChannel = channel;
  14604. if (internalTexture && internalTexture.is3D) {
  14605. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14606. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14607. internalTexture._cachedWrapU = texture.wrapU;
  14608. switch (texture.wrapU) {
  14609. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14610. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14611. break;
  14612. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14613. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14614. break;
  14615. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14616. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14617. break;
  14618. }
  14619. }
  14620. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14621. internalTexture._cachedWrapV = texture.wrapV;
  14622. switch (texture.wrapV) {
  14623. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14624. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14625. break;
  14626. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14627. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14628. break;
  14629. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14630. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14631. break;
  14632. }
  14633. }
  14634. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14635. internalTexture._cachedWrapR = texture.wrapR;
  14636. switch (texture.wrapR) {
  14637. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14638. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14639. break;
  14640. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14641. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14642. break;
  14643. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14644. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14645. break;
  14646. }
  14647. }
  14648. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14649. }
  14650. else if (internalTexture && internalTexture.isCube) {
  14651. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14652. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14653. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14654. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14655. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14656. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14658. }
  14659. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14660. }
  14661. else {
  14662. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14663. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14664. internalTexture._cachedWrapU = texture.wrapU;
  14665. switch (texture.wrapU) {
  14666. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14668. break;
  14669. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14671. break;
  14672. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14673. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14674. break;
  14675. }
  14676. }
  14677. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14678. internalTexture._cachedWrapV = texture.wrapV;
  14679. switch (texture.wrapV) {
  14680. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14682. break;
  14683. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14685. break;
  14686. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14687. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14688. break;
  14689. }
  14690. }
  14691. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14692. }
  14693. return true;
  14694. };
  14695. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14696. if (channel < 0 || !uniform) {
  14697. return;
  14698. }
  14699. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14700. this._textureUnits = new Int32Array(textures.length);
  14701. }
  14702. for (var i = 0; i < textures.length; i++) {
  14703. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14704. }
  14705. this._gl.uniform1iv(uniform, this._textureUnits);
  14706. for (var index = 0; index < textures.length; index++) {
  14707. this._setTexture(this._textureUnits[index], textures[index], true);
  14708. }
  14709. };
  14710. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14711. var internalTexture = texture.getInternalTexture();
  14712. if (!internalTexture) {
  14713. return;
  14714. }
  14715. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14716. var value = texture.anisotropicFilteringLevel;
  14717. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14718. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14719. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14720. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14721. }
  14722. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14723. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14724. internalTexture._cachedAnisotropicFilteringLevel = value;
  14725. }
  14726. };
  14727. Engine.prototype.readPixels = function (x, y, width, height) {
  14728. var data = new Uint8Array(height * width * 4);
  14729. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14730. return data;
  14731. };
  14732. /**
  14733. * Add an externaly attached data from its key.
  14734. * This method call will fail and return false, if such key already exists.
  14735. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14736. * @param key the unique key that identifies the data
  14737. * @param data the data object to associate to the key for this Engine instance
  14738. * @return true if no such key were already present and the data was added successfully, false otherwise
  14739. */
  14740. Engine.prototype.addExternalData = function (key, data) {
  14741. if (!this._externalData) {
  14742. this._externalData = new BABYLON.StringDictionary();
  14743. }
  14744. return this._externalData.add(key, data);
  14745. };
  14746. /**
  14747. * Get an externaly attached data from its key
  14748. * @param key the unique key that identifies the data
  14749. * @return the associated data, if present (can be null), or undefined if not present
  14750. */
  14751. Engine.prototype.getExternalData = function (key) {
  14752. if (!this._externalData) {
  14753. this._externalData = new BABYLON.StringDictionary();
  14754. }
  14755. return this._externalData.get(key);
  14756. };
  14757. /**
  14758. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14759. * @param key the unique key that identifies the data
  14760. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14761. * @return the associated data, can be null if the factory returned null.
  14762. */
  14763. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14764. if (!this._externalData) {
  14765. this._externalData = new BABYLON.StringDictionary();
  14766. }
  14767. return this._externalData.getOrAddWithFactory(key, factory);
  14768. };
  14769. /**
  14770. * Remove an externaly attached data from the Engine instance
  14771. * @param key the unique key that identifies the data
  14772. * @return true if the data was successfully removed, false if it doesn't exist
  14773. */
  14774. Engine.prototype.removeExternalData = function (key) {
  14775. if (!this._externalData) {
  14776. this._externalData = new BABYLON.StringDictionary();
  14777. }
  14778. return this._externalData.remove(key);
  14779. };
  14780. Engine.prototype.unbindAllAttributes = function () {
  14781. if (this._mustWipeVertexAttributes) {
  14782. this._mustWipeVertexAttributes = false;
  14783. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14784. this._gl.disableVertexAttribArray(i);
  14785. this._vertexAttribArraysEnabled[i] = false;
  14786. this._currentBufferPointers[i].active = false;
  14787. }
  14788. return;
  14789. }
  14790. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14791. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14792. continue;
  14793. }
  14794. this._gl.disableVertexAttribArray(i);
  14795. this._vertexAttribArraysEnabled[i] = false;
  14796. this._currentBufferPointers[i].active = false;
  14797. }
  14798. };
  14799. Engine.prototype.releaseEffects = function () {
  14800. for (var name in this._compiledEffects) {
  14801. this._deleteProgram(this._compiledEffects[name]._program);
  14802. }
  14803. this._compiledEffects = {};
  14804. };
  14805. // Dispose
  14806. Engine.prototype.dispose = function () {
  14807. this.hideLoadingUI();
  14808. this.stopRenderLoop();
  14809. // Release postProcesses
  14810. while (this.postProcesses.length) {
  14811. this.postProcesses[0].dispose();
  14812. }
  14813. // Empty texture
  14814. if (this._emptyTexture) {
  14815. this._releaseTexture(this._emptyTexture);
  14816. this._emptyTexture = null;
  14817. }
  14818. if (this._emptyCubeTexture) {
  14819. this._releaseTexture(this._emptyCubeTexture);
  14820. this._emptyCubeTexture = null;
  14821. }
  14822. // Rescale PP
  14823. if (this._rescalePostProcess) {
  14824. this._rescalePostProcess.dispose();
  14825. }
  14826. // Release scenes
  14827. while (this.scenes.length) {
  14828. this.scenes[0].dispose();
  14829. }
  14830. // Release audio engine
  14831. if (Engine.audioEngine) {
  14832. Engine.audioEngine.dispose();
  14833. }
  14834. // Release effects
  14835. this.releaseEffects();
  14836. // Unbind
  14837. this.unbindAllAttributes();
  14838. if (this._dummyFramebuffer) {
  14839. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14840. }
  14841. //WebVR
  14842. this.disableVR();
  14843. // Events
  14844. if (BABYLON.Tools.IsWindowObjectExist()) {
  14845. window.removeEventListener("blur", this._onBlur);
  14846. window.removeEventListener("focus", this._onFocus);
  14847. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14848. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14849. if (this._renderingCanvas) {
  14850. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14851. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14852. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14853. if (!this._doNotHandleContextLost) {
  14854. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14855. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14856. }
  14857. }
  14858. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14859. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14860. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14861. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14862. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14863. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14864. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14865. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14866. if (this._onVrDisplayConnect) {
  14867. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14868. if (this._onVrDisplayDisconnect) {
  14869. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14870. }
  14871. if (this._onVrDisplayPresentChange) {
  14872. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14873. }
  14874. this._onVrDisplayConnect = null;
  14875. this._onVrDisplayDisconnect = null;
  14876. }
  14877. }
  14878. // Remove from Instances
  14879. var index = Engine.Instances.indexOf(this);
  14880. if (index >= 0) {
  14881. Engine.Instances.splice(index, 1);
  14882. }
  14883. this._workingCanvas = null;
  14884. this._workingContext = null;
  14885. this._currentBufferPointers = [];
  14886. this._renderingCanvas = null;
  14887. this._currentProgram = null;
  14888. this._bindedRenderFunction = null;
  14889. this.onResizeObservable.clear();
  14890. this.onCanvasBlurObservable.clear();
  14891. this.onCanvasFocusObservable.clear();
  14892. this.onCanvasPointerOutObservable.clear();
  14893. this.onBeginFrameObservable.clear();
  14894. this.onEndFrameObservable.clear();
  14895. BABYLON.Effect.ResetCache();
  14896. // Abort active requests
  14897. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14898. var request = _a[_i];
  14899. request.abort();
  14900. }
  14901. };
  14902. // Loading screen
  14903. Engine.prototype.displayLoadingUI = function () {
  14904. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14905. return;
  14906. }
  14907. var loadingScreen = this.loadingScreen;
  14908. if (loadingScreen) {
  14909. loadingScreen.displayLoadingUI();
  14910. }
  14911. };
  14912. Engine.prototype.hideLoadingUI = function () {
  14913. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14914. return;
  14915. }
  14916. var loadingScreen = this.loadingScreen;
  14917. if (loadingScreen) {
  14918. loadingScreen.hideLoadingUI();
  14919. }
  14920. };
  14921. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14922. get: function () {
  14923. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14924. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14925. return this._loadingScreen;
  14926. },
  14927. set: function (loadingScreen) {
  14928. this._loadingScreen = loadingScreen;
  14929. },
  14930. enumerable: true,
  14931. configurable: true
  14932. });
  14933. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14934. set: function (text) {
  14935. this.loadingScreen.loadingUIText = text;
  14936. },
  14937. enumerable: true,
  14938. configurable: true
  14939. });
  14940. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14941. set: function (color) {
  14942. this.loadingScreen.loadingUIBackgroundColor = color;
  14943. },
  14944. enumerable: true,
  14945. configurable: true
  14946. });
  14947. Engine.prototype.attachContextLostEvent = function (callback) {
  14948. if (this._renderingCanvas) {
  14949. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14950. }
  14951. };
  14952. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14953. if (this._renderingCanvas) {
  14954. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14955. }
  14956. };
  14957. Engine.prototype.getVertexShaderSource = function (program) {
  14958. var shaders = this._gl.getAttachedShaders(program);
  14959. if (!shaders) {
  14960. return null;
  14961. }
  14962. return this._gl.getShaderSource(shaders[0]);
  14963. };
  14964. Engine.prototype.getFragmentShaderSource = function (program) {
  14965. var shaders = this._gl.getAttachedShaders(program);
  14966. if (!shaders) {
  14967. return null;
  14968. }
  14969. return this._gl.getShaderSource(shaders[1]);
  14970. };
  14971. Engine.prototype.getError = function () {
  14972. return this._gl.getError();
  14973. };
  14974. // FPS
  14975. Engine.prototype.getFps = function () {
  14976. return this._fps;
  14977. };
  14978. Engine.prototype.getDeltaTime = function () {
  14979. return this._deltaTime;
  14980. };
  14981. Engine.prototype._measureFps = function () {
  14982. this._performanceMonitor.sampleFrame();
  14983. this._fps = this._performanceMonitor.averageFPS;
  14984. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14985. };
  14986. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14987. if (faceIndex === void 0) { faceIndex = -1; }
  14988. var gl = this._gl;
  14989. if (!this._dummyFramebuffer) {
  14990. var dummy = gl.createFramebuffer();
  14991. if (!dummy) {
  14992. throw new Error("Unable to create dummy framebuffer");
  14993. }
  14994. this._dummyFramebuffer = dummy;
  14995. }
  14996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14997. if (faceIndex > -1) {
  14998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14999. }
  15000. else {
  15001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15002. }
  15003. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15004. var buffer;
  15005. switch (readType) {
  15006. case gl.UNSIGNED_BYTE:
  15007. buffer = new Uint8Array(4 * width * height);
  15008. readType = gl.UNSIGNED_BYTE;
  15009. break;
  15010. default:
  15011. buffer = new Float32Array(4 * width * height);
  15012. readType = gl.FLOAT;
  15013. break;
  15014. }
  15015. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15016. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15017. return buffer;
  15018. };
  15019. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15020. if (this._webGLVersion > 1) {
  15021. return this._caps.colorBufferFloat;
  15022. }
  15023. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15024. };
  15025. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15026. if (this._webGLVersion > 1) {
  15027. return this._caps.colorBufferFloat;
  15028. }
  15029. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15030. };
  15031. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15032. Engine.prototype._canRenderToFramebuffer = function (type) {
  15033. var gl = this._gl;
  15034. //clear existing errors
  15035. while (gl.getError() !== gl.NO_ERROR) { }
  15036. var successful = true;
  15037. var texture = gl.createTexture();
  15038. gl.bindTexture(gl.TEXTURE_2D, texture);
  15039. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15042. var fb = gl.createFramebuffer();
  15043. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15044. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15045. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15046. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15047. successful = successful && (gl.getError() === gl.NO_ERROR);
  15048. //try render by clearing frame buffer's color buffer
  15049. if (successful) {
  15050. gl.clear(gl.COLOR_BUFFER_BIT);
  15051. successful = successful && (gl.getError() === gl.NO_ERROR);
  15052. }
  15053. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15054. if (successful) {
  15055. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15056. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15057. var readFormat = gl.RGBA;
  15058. var readType = gl.UNSIGNED_BYTE;
  15059. var buffer = new Uint8Array(4);
  15060. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15061. successful = successful && (gl.getError() === gl.NO_ERROR);
  15062. }
  15063. //clean up
  15064. gl.deleteTexture(texture);
  15065. gl.deleteFramebuffer(fb);
  15066. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15067. //clear accumulated errors
  15068. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15069. return successful;
  15070. };
  15071. Engine.prototype._getWebGLTextureType = function (type) {
  15072. if (type === Engine.TEXTURETYPE_FLOAT) {
  15073. return this._gl.FLOAT;
  15074. }
  15075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15076. // Add Half Float Constant.
  15077. return this._gl.HALF_FLOAT_OES;
  15078. }
  15079. return this._gl.UNSIGNED_BYTE;
  15080. };
  15081. ;
  15082. /** @ignore */
  15083. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15084. if (this._webGLVersion === 1) {
  15085. return this._gl.RGBA;
  15086. }
  15087. if (type === Engine.TEXTURETYPE_FLOAT) {
  15088. if (format) {
  15089. switch (format) {
  15090. case Engine.TEXTUREFORMAT_R32F:
  15091. return this._gl.R32F;
  15092. case Engine.TEXTUREFORMAT_RG32F:
  15093. return this._gl.RG32F;
  15094. case Engine.TEXTUREFORMAT_RGB32F:
  15095. return this._gl.RGB32F;
  15096. }
  15097. }
  15098. return this._gl.RGBA32F;
  15099. }
  15100. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15101. return this._gl.RGBA16F;
  15102. }
  15103. return this._gl.RGBA;
  15104. };
  15105. ;
  15106. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15107. if (type === Engine.TEXTURETYPE_FLOAT) {
  15108. return this._gl.RGBA32F;
  15109. }
  15110. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15111. return this._gl.RGBA16F;
  15112. }
  15113. return this._gl.RGBA8;
  15114. };
  15115. ;
  15116. Engine.prototype.createQuery = function () {
  15117. return this._gl.createQuery();
  15118. };
  15119. Engine.prototype.deleteQuery = function (query) {
  15120. this._gl.deleteQuery(query);
  15121. return this;
  15122. };
  15123. Engine.prototype.isQueryResultAvailable = function (query) {
  15124. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15125. };
  15126. Engine.prototype.getQueryResult = function (query) {
  15127. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15128. };
  15129. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15130. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15131. this._gl.beginQuery(glAlgorithm, query);
  15132. return this;
  15133. };
  15134. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15135. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15136. this._gl.endQuery(glAlgorithm);
  15137. return this;
  15138. };
  15139. /* Time queries */
  15140. Engine.prototype._createTimeQuery = function () {
  15141. var timerQuery = this._caps.timerQuery;
  15142. if (timerQuery.createQueryEXT) {
  15143. return timerQuery.createQueryEXT();
  15144. }
  15145. return this.createQuery();
  15146. };
  15147. Engine.prototype._deleteTimeQuery = function (query) {
  15148. var timerQuery = this._caps.timerQuery;
  15149. if (timerQuery.deleteQueryEXT) {
  15150. timerQuery.deleteQueryEXT(query);
  15151. return;
  15152. }
  15153. this.deleteQuery(query);
  15154. };
  15155. Engine.prototype._getTimeQueryResult = function (query) {
  15156. var timerQuery = this._caps.timerQuery;
  15157. if (timerQuery.getQueryObjectEXT) {
  15158. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15159. }
  15160. return this.getQueryResult(query);
  15161. };
  15162. Engine.prototype._getTimeQueryAvailability = function (query) {
  15163. var timerQuery = this._caps.timerQuery;
  15164. if (timerQuery.getQueryObjectEXT) {
  15165. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15166. }
  15167. return this.isQueryResultAvailable(query);
  15168. };
  15169. Engine.prototype.startTimeQuery = function () {
  15170. var timerQuery = this._caps.timerQuery;
  15171. if (!timerQuery) {
  15172. return null;
  15173. }
  15174. var token = new BABYLON._TimeToken();
  15175. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15176. if (this._caps.canUseTimestampForTimerQuery) {
  15177. token._startTimeQuery = this._createTimeQuery();
  15178. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15179. }
  15180. else {
  15181. if (this._currentNonTimestampToken) {
  15182. return this._currentNonTimestampToken;
  15183. }
  15184. token._timeElapsedQuery = this._createTimeQuery();
  15185. if (timerQuery.beginQueryEXT) {
  15186. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15187. }
  15188. else {
  15189. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15190. }
  15191. this._currentNonTimestampToken = token;
  15192. }
  15193. return token;
  15194. };
  15195. Engine.prototype.endTimeQuery = function (token) {
  15196. var timerQuery = this._caps.timerQuery;
  15197. if (!timerQuery || !token) {
  15198. return -1;
  15199. }
  15200. if (this._caps.canUseTimestampForTimerQuery) {
  15201. if (!token._startTimeQuery) {
  15202. return -1;
  15203. }
  15204. if (!token._endTimeQuery) {
  15205. token._endTimeQuery = this._createTimeQuery();
  15206. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15207. }
  15208. }
  15209. else if (!token._timeElapsedQueryEnded) {
  15210. if (!token._timeElapsedQuery) {
  15211. return -1;
  15212. }
  15213. if (timerQuery.endQueryEXT) {
  15214. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15215. }
  15216. else {
  15217. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15218. }
  15219. token._timeElapsedQueryEnded = true;
  15220. }
  15221. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15222. var available = false;
  15223. if (token._endTimeQuery) {
  15224. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15225. }
  15226. else if (token._timeElapsedQuery) {
  15227. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15228. }
  15229. if (available && !disjoint) {
  15230. var result = 0;
  15231. if (this._caps.canUseTimestampForTimerQuery) {
  15232. if (!token._startTimeQuery || !token._endTimeQuery) {
  15233. return -1;
  15234. }
  15235. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15236. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15237. result = timeEnd - timeStart;
  15238. this._deleteTimeQuery(token._startTimeQuery);
  15239. this._deleteTimeQuery(token._endTimeQuery);
  15240. token._startTimeQuery = null;
  15241. token._endTimeQuery = null;
  15242. }
  15243. else {
  15244. if (!token._timeElapsedQuery) {
  15245. return -1;
  15246. }
  15247. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15248. this._deleteTimeQuery(token._timeElapsedQuery);
  15249. token._timeElapsedQuery = null;
  15250. token._timeElapsedQueryEnded = false;
  15251. this._currentNonTimestampToken = null;
  15252. }
  15253. return result;
  15254. }
  15255. return -1;
  15256. };
  15257. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15258. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15259. };
  15260. // Transform feedback
  15261. Engine.prototype.createTransformFeedback = function () {
  15262. return this._gl.createTransformFeedback();
  15263. };
  15264. Engine.prototype.deleteTransformFeedback = function (value) {
  15265. this._gl.deleteTransformFeedback(value);
  15266. };
  15267. Engine.prototype.bindTransformFeedback = function (value) {
  15268. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15269. };
  15270. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15271. if (usePoints === void 0) { usePoints = true; }
  15272. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15273. };
  15274. Engine.prototype.endTransformFeedback = function () {
  15275. this._gl.endTransformFeedback();
  15276. };
  15277. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15278. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15279. };
  15280. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15281. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15282. };
  15283. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15284. var _this = this;
  15285. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15286. this._activeRequests.push(request);
  15287. request.onCompleteObservable.add(function (request) {
  15288. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15289. });
  15290. return request;
  15291. };
  15292. /** @ignore */
  15293. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15294. var _this = this;
  15295. return new Promise(function (resolve, reject) {
  15296. _this._loadFile(url, function (data) {
  15297. resolve(data);
  15298. }, undefined, database, useArrayBuffer, function (request, exception) {
  15299. reject(exception);
  15300. });
  15301. });
  15302. };
  15303. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15304. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15305. var onload = function (data) {
  15306. loadedFiles[index] = data;
  15307. loadedFiles._internalCount++;
  15308. if (loadedFiles._internalCount === 6) {
  15309. onfinish(loadedFiles);
  15310. }
  15311. };
  15312. var onerror = function (request, exception) {
  15313. if (onErrorCallBack && request) {
  15314. onErrorCallBack(request.status + " " + request.statusText, exception);
  15315. }
  15316. };
  15317. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15318. };
  15319. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15320. if (onError === void 0) { onError = null; }
  15321. var loadedFiles = [];
  15322. loadedFiles._internalCount = 0;
  15323. for (var index = 0; index < 6; index++) {
  15324. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15325. }
  15326. };
  15327. // Statics
  15328. Engine.isSupported = function () {
  15329. try {
  15330. var tempcanvas = document.createElement("canvas");
  15331. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15332. return gl != null && !!window.WebGLRenderingContext;
  15333. }
  15334. catch (e) {
  15335. return false;
  15336. }
  15337. };
  15338. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15339. Engine.ExceptionList = [
  15340. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15341. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15342. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15343. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15344. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15345. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15346. ];
  15347. Engine.Instances = new Array();
  15348. // Const statics
  15349. Engine._ALPHA_DISABLE = 0;
  15350. Engine._ALPHA_ADD = 1;
  15351. Engine._ALPHA_COMBINE = 2;
  15352. Engine._ALPHA_SUBTRACT = 3;
  15353. Engine._ALPHA_MULTIPLY = 4;
  15354. Engine._ALPHA_MAXIMIZED = 5;
  15355. Engine._ALPHA_ONEONE = 6;
  15356. Engine._ALPHA_PREMULTIPLIED = 7;
  15357. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15358. Engine._ALPHA_INTERPOLATE = 9;
  15359. Engine._ALPHA_SCREENMODE = 10;
  15360. Engine._DELAYLOADSTATE_NONE = 0;
  15361. Engine._DELAYLOADSTATE_LOADED = 1;
  15362. Engine._DELAYLOADSTATE_LOADING = 2;
  15363. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15364. Engine._TEXTUREFORMAT_ALPHA = 0;
  15365. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15366. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15367. Engine._TEXTUREFORMAT_RGB = 4;
  15368. Engine._TEXTUREFORMAT_RGBA = 5;
  15369. Engine._TEXTUREFORMAT_R32F = 6;
  15370. Engine._TEXTUREFORMAT_RG32F = 7;
  15371. Engine._TEXTUREFORMAT_RGB32F = 8;
  15372. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15373. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15374. Engine._TEXTURETYPE_FLOAT = 1;
  15375. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15376. // Depht or Stencil test Constants.
  15377. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15378. 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.
  15379. 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.
  15380. 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.
  15381. 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.
  15382. 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.
  15383. 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.
  15384. 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.
  15385. // Stencil Actions Constants.
  15386. Engine._KEEP = 0x1E00;
  15387. Engine._REPLACE = 0x1E01;
  15388. Engine._INCR = 0x1E02;
  15389. Engine._DECR = 0x1E03;
  15390. Engine._INVERT = 0x150A;
  15391. Engine._INCR_WRAP = 0x8507;
  15392. Engine._DECR_WRAP = 0x8508;
  15393. // Texture rescaling mode
  15394. Engine._SCALEMODE_FLOOR = 1;
  15395. Engine._SCALEMODE_NEAREST = 2;
  15396. Engine._SCALEMODE_CEILING = 3;
  15397. // Updatable statics so stick with vars here
  15398. Engine.CollisionsEpsilon = 0.001;
  15399. Engine.CodeRepository = "src/";
  15400. Engine.ShadersRepository = "src/Shaders/";
  15401. return Engine;
  15402. }());
  15403. BABYLON.Engine = Engine;
  15404. })(BABYLON || (BABYLON = {}));
  15405. //# sourceMappingURL=babylon.engine.js.map
  15406. var BABYLON;
  15407. (function (BABYLON) {
  15408. /**
  15409. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15410. */
  15411. var Node = /** @class */ (function () {
  15412. /**
  15413. * Creates a new Node
  15414. * @param {string} name - the name and id to be given to this node
  15415. * @param {BABYLON.Scene} the scene this node will be added to
  15416. */
  15417. function Node(name, scene) {
  15418. if (scene === void 0) { scene = null; }
  15419. /**
  15420. * Gets or sets a string used to store user defined state for the node
  15421. */
  15422. this.state = "";
  15423. /**
  15424. * Gets or sets an object used to store user defined information for the node
  15425. */
  15426. this.metadata = null;
  15427. /**
  15428. * Gets or sets a boolean used to define if the node must be serialized
  15429. */
  15430. this.doNotSerialize = false;
  15431. /** @ignore */
  15432. this._isDisposed = false;
  15433. /**
  15434. * Gets a list of {BABYLON.Animation} associated with the node
  15435. */
  15436. this.animations = new Array();
  15437. this._ranges = {};
  15438. this._isEnabled = true;
  15439. this._isReady = true;
  15440. /** @ignore */
  15441. this._currentRenderId = -1;
  15442. this._parentRenderId = -1;
  15443. this._animationPropertiesOverride = null;
  15444. /**
  15445. * An event triggered when the mesh is disposed
  15446. * @type {BABYLON.Observable}
  15447. */
  15448. this.onDisposeObservable = new BABYLON.Observable();
  15449. // Behaviors
  15450. this._behaviors = new Array();
  15451. this.name = name;
  15452. this.id = name;
  15453. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15454. this.uniqueId = this._scene.getUniqueId();
  15455. this._initCache();
  15456. }
  15457. /**
  15458. * Gets a boolean indicating if the node has been disposed
  15459. * @returns true if the node was disposed
  15460. */
  15461. Node.prototype.isDisposed = function () {
  15462. return this._isDisposed;
  15463. };
  15464. Object.defineProperty(Node.prototype, "parent", {
  15465. get: function () {
  15466. return this._parentNode;
  15467. },
  15468. /**
  15469. * Gets or sets the parent of the node
  15470. */
  15471. set: function (parent) {
  15472. if (this._parentNode === parent) {
  15473. return;
  15474. }
  15475. // Remove self from list of children of parent
  15476. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15477. var index = this._parentNode._children.indexOf(this);
  15478. if (index !== -1) {
  15479. this._parentNode._children.splice(index, 1);
  15480. }
  15481. }
  15482. // Store new parent
  15483. this._parentNode = parent;
  15484. // Add as child to new parent
  15485. if (this._parentNode) {
  15486. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15487. this._parentNode._children = new Array();
  15488. }
  15489. this._parentNode._children.push(this);
  15490. }
  15491. },
  15492. enumerable: true,
  15493. configurable: true
  15494. });
  15495. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15496. /**
  15497. * Gets or sets the animation properties override
  15498. */
  15499. get: function () {
  15500. return this._animationPropertiesOverride;
  15501. },
  15502. set: function (value) {
  15503. this._animationPropertiesOverride = value;
  15504. },
  15505. enumerable: true,
  15506. configurable: true
  15507. });
  15508. /**
  15509. * Gets a string idenfifying the name of the class
  15510. * @returns "Node" string
  15511. */
  15512. Node.prototype.getClassName = function () {
  15513. return "Node";
  15514. };
  15515. Object.defineProperty(Node.prototype, "onDispose", {
  15516. /**
  15517. * Sets a callback that will be raised when the node will be disposed
  15518. */
  15519. set: function (callback) {
  15520. if (this._onDisposeObserver) {
  15521. this.onDisposeObservable.remove(this._onDisposeObserver);
  15522. }
  15523. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. /**
  15529. * Gets the scene of the node
  15530. * @returns a {BABYLON.Scene}
  15531. */
  15532. Node.prototype.getScene = function () {
  15533. return this._scene;
  15534. };
  15535. /**
  15536. * Gets the engine of the node
  15537. * @returns a {BABYLON.Engine}
  15538. */
  15539. Node.prototype.getEngine = function () {
  15540. return this._scene.getEngine();
  15541. };
  15542. /**
  15543. * Attach a behavior to the node
  15544. * @see http://doc.babylonjs.com/features/behaviour
  15545. * @param behavior defines the behavior to attach
  15546. * @returns the current Node
  15547. */
  15548. Node.prototype.addBehavior = function (behavior) {
  15549. var _this = this;
  15550. var index = this._behaviors.indexOf(behavior);
  15551. if (index !== -1) {
  15552. return this;
  15553. }
  15554. behavior.init();
  15555. if (this._scene.isLoading) {
  15556. // We defer the attach when the scene will be loaded
  15557. var observer = this._scene.onDataLoadedObservable.add(function () {
  15558. behavior.attach(_this);
  15559. setTimeout(function () {
  15560. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15561. _this._scene.onDataLoadedObservable.remove(observer);
  15562. }, 0);
  15563. });
  15564. }
  15565. else {
  15566. behavior.attach(this);
  15567. }
  15568. this._behaviors.push(behavior);
  15569. return this;
  15570. };
  15571. /**
  15572. * Remove an attached behavior
  15573. * @see http://doc.babylonjs.com/features/behaviour
  15574. * @param behavior defines the behavior to attach
  15575. * @returns the current Node
  15576. */
  15577. Node.prototype.removeBehavior = function (behavior) {
  15578. var index = this._behaviors.indexOf(behavior);
  15579. if (index === -1) {
  15580. return this;
  15581. }
  15582. this._behaviors[index].detach();
  15583. this._behaviors.splice(index, 1);
  15584. return this;
  15585. };
  15586. Object.defineProperty(Node.prototype, "behaviors", {
  15587. /**
  15588. * Gets the list of attached behaviors
  15589. * @see http://doc.babylonjs.com/features/behaviour
  15590. */
  15591. get: function () {
  15592. return this._behaviors;
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. /**
  15598. * Gets an attached behavior by name
  15599. * @param name defines the name of the behavior to look for
  15600. * @see http://doc.babylonjs.com/features/behaviour
  15601. * @returns null if behavior was not found else the requested behavior
  15602. */
  15603. Node.prototype.getBehaviorByName = function (name) {
  15604. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15605. var behavior = _a[_i];
  15606. if (behavior.name === name) {
  15607. return behavior;
  15608. }
  15609. }
  15610. return null;
  15611. };
  15612. /**
  15613. * Returns the world matrix of the node
  15614. * @returns a matrix containing the node's world matrix
  15615. */
  15616. Node.prototype.getWorldMatrix = function () {
  15617. return BABYLON.Matrix.Identity();
  15618. };
  15619. // override it in derived class if you add new variables to the cache
  15620. // and call the parent class method
  15621. /** @ignore */
  15622. Node.prototype._initCache = function () {
  15623. this._cache = {};
  15624. this._cache.parent = undefined;
  15625. };
  15626. /** @ignore */
  15627. Node.prototype.updateCache = function (force) {
  15628. if (!force && this.isSynchronized())
  15629. return;
  15630. this._cache.parent = this.parent;
  15631. this._updateCache();
  15632. };
  15633. // override it in derived class if you add new variables to the cache
  15634. // and call the parent class method if !ignoreParentClass
  15635. /** @ignore */
  15636. Node.prototype._updateCache = function (ignoreParentClass) {
  15637. };
  15638. // override it in derived class if you add new variables to the cache
  15639. /** @ignore */
  15640. Node.prototype._isSynchronized = function () {
  15641. return true;
  15642. };
  15643. /** @ignore */
  15644. Node.prototype._markSyncedWithParent = function () {
  15645. if (this.parent) {
  15646. this._parentRenderId = this.parent._currentRenderId;
  15647. }
  15648. };
  15649. /** @ignore */
  15650. Node.prototype.isSynchronizedWithParent = function () {
  15651. if (!this.parent) {
  15652. return true;
  15653. }
  15654. if (this._parentRenderId !== this.parent._currentRenderId) {
  15655. return false;
  15656. }
  15657. return this.parent.isSynchronized();
  15658. };
  15659. /** @ignore */
  15660. Node.prototype.isSynchronized = function (updateCache) {
  15661. var check = this.hasNewParent();
  15662. check = check || !this.isSynchronizedWithParent();
  15663. check = check || !this._isSynchronized();
  15664. if (updateCache)
  15665. this.updateCache(true);
  15666. return !check;
  15667. };
  15668. /** @ignore */
  15669. Node.prototype.hasNewParent = function (update) {
  15670. if (this._cache.parent === this.parent)
  15671. return false;
  15672. if (update)
  15673. this._cache.parent = this.parent;
  15674. return true;
  15675. };
  15676. /**
  15677. * Is this node ready to be used/rendered
  15678. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15679. * @return true if the node is ready
  15680. */
  15681. Node.prototype.isReady = function (completeCheck) {
  15682. if (completeCheck === void 0) { completeCheck = false; }
  15683. return this._isReady;
  15684. };
  15685. /**
  15686. * Is this node enabled?
  15687. * 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
  15688. * @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
  15689. * @return whether this node (and its parent) is enabled
  15690. * @see setEnabled
  15691. */
  15692. Node.prototype.isEnabled = function (checkAncestors) {
  15693. if (checkAncestors === void 0) { checkAncestors = true; }
  15694. if (checkAncestors === false) {
  15695. return this._isEnabled;
  15696. }
  15697. if (this._isEnabled === false) {
  15698. return false;
  15699. }
  15700. if (this.parent !== undefined && this.parent !== null) {
  15701. return this.parent.isEnabled(checkAncestors);
  15702. }
  15703. return true;
  15704. };
  15705. /**
  15706. * Set the enabled state of this node
  15707. * @param value defines the new enabled state
  15708. * @see isEnabled
  15709. */
  15710. Node.prototype.setEnabled = function (value) {
  15711. this._isEnabled = value;
  15712. };
  15713. /**
  15714. * Is this node a descendant of the given node?
  15715. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15716. * @param ancestor defines the parent node to inspect
  15717. * @see parent
  15718. * @returns a boolean indicating if this node is a descendant of the given node
  15719. */
  15720. Node.prototype.isDescendantOf = function (ancestor) {
  15721. if (this.parent) {
  15722. if (this.parent === ancestor) {
  15723. return true;
  15724. }
  15725. return this.parent.isDescendantOf(ancestor);
  15726. }
  15727. return false;
  15728. };
  15729. /** @ignore */
  15730. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15731. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15732. if (!this._children) {
  15733. return;
  15734. }
  15735. for (var index = 0; index < this._children.length; index++) {
  15736. var item = this._children[index];
  15737. if (!predicate || predicate(item)) {
  15738. results.push(item);
  15739. }
  15740. if (!directDescendantsOnly) {
  15741. item._getDescendants(results, false, predicate);
  15742. }
  15743. }
  15744. };
  15745. /**
  15746. * Will return all nodes that have this node as ascendant
  15747. * @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
  15748. * @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
  15749. * @return all children nodes of all types
  15750. */
  15751. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15752. var results = new Array();
  15753. this._getDescendants(results, directDescendantsOnly, predicate);
  15754. return results;
  15755. };
  15756. /**
  15757. * Get all child-meshes of this node
  15758. * @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
  15759. * @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
  15760. * @returns an array of {BABYLON.AbstractMesh}
  15761. */
  15762. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15763. var results = [];
  15764. this._getDescendants(results, directDescendantsOnly, function (node) {
  15765. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15766. });
  15767. return results;
  15768. };
  15769. /**
  15770. * Get all child-transformNodes of this node
  15771. * @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
  15772. * @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
  15773. * @returns an array of {BABYLON.TransformNode}
  15774. */
  15775. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15776. var results = [];
  15777. this._getDescendants(results, directDescendantsOnly, function (node) {
  15778. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15779. });
  15780. return results;
  15781. };
  15782. /**
  15783. * Get all direct children of this node
  15784. * @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
  15785. * @returns an array of {BABYLON.Node}
  15786. */
  15787. Node.prototype.getChildren = function (predicate) {
  15788. return this.getDescendants(true, predicate);
  15789. };
  15790. /** @ignore */
  15791. Node.prototype._setReady = function (state) {
  15792. if (state === this._isReady) {
  15793. return;
  15794. }
  15795. if (!state) {
  15796. this._isReady = false;
  15797. return;
  15798. }
  15799. this._isReady = true;
  15800. if (this.onReady) {
  15801. this.onReady(this);
  15802. }
  15803. };
  15804. /**
  15805. * Get an animation by name
  15806. * @param name defines the name of the animation to look for
  15807. * @returns null if not found else the requested animation
  15808. */
  15809. Node.prototype.getAnimationByName = function (name) {
  15810. for (var i = 0; i < this.animations.length; i++) {
  15811. var animation = this.animations[i];
  15812. if (animation.name === name) {
  15813. return animation;
  15814. }
  15815. }
  15816. return null;
  15817. };
  15818. /**
  15819. * Creates an animation range for this node
  15820. * @param name defines the name of the range
  15821. * @param from defines the starting key
  15822. * @param to defines the end key
  15823. */
  15824. Node.prototype.createAnimationRange = function (name, from, to) {
  15825. // check name not already in use
  15826. if (!this._ranges[name]) {
  15827. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15828. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15829. if (this.animations[i]) {
  15830. this.animations[i].createRange(name, from, to);
  15831. }
  15832. }
  15833. }
  15834. };
  15835. /**
  15836. * Delete a specific animation range
  15837. * @param name defines the name of the range to delete
  15838. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15839. */
  15840. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15841. if (deleteFrames === void 0) { deleteFrames = true; }
  15842. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15843. if (this.animations[i]) {
  15844. this.animations[i].deleteRange(name, deleteFrames);
  15845. }
  15846. }
  15847. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15848. };
  15849. /**
  15850. * Get an animation range by name
  15851. * @param name defines the name of the animation range to look for
  15852. * @returns null if not found else the requested animation range
  15853. */
  15854. Node.prototype.getAnimationRange = function (name) {
  15855. return this._ranges[name];
  15856. };
  15857. /**
  15858. * Will start the animation sequence
  15859. * @param name defines the range frames for animation sequence
  15860. * @param loop defines if the animation should loop (false by default)
  15861. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15862. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15863. * @returns the object created for this animation. If range does not exist, it will return null
  15864. */
  15865. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15866. var range = this.getAnimationRange(name);
  15867. if (!range) {
  15868. return null;
  15869. }
  15870. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15871. };
  15872. /**
  15873. * Serialize animation ranges into a JSON compatible object
  15874. * @returns serialization object
  15875. */
  15876. Node.prototype.serializeAnimationRanges = function () {
  15877. var serializationRanges = [];
  15878. for (var name in this._ranges) {
  15879. var localRange = this._ranges[name];
  15880. if (!localRange) {
  15881. continue;
  15882. }
  15883. var range = {};
  15884. range.name = name;
  15885. range.from = localRange.from;
  15886. range.to = localRange.to;
  15887. serializationRanges.push(range);
  15888. }
  15889. return serializationRanges;
  15890. };
  15891. /**
  15892. * Computes the world matrix of the node
  15893. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15894. * @returns the world matrix
  15895. */
  15896. Node.prototype.computeWorldMatrix = function (force) {
  15897. return BABYLON.Matrix.Identity();
  15898. };
  15899. /**
  15900. * Releases resources associated with this node.
  15901. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15902. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15903. */
  15904. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15905. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15906. if (!doNotRecurse) {
  15907. var nodes = this.getDescendants(true);
  15908. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15909. var node = nodes_1[_i];
  15910. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15911. }
  15912. }
  15913. else {
  15914. var transformNodes = this.getChildTransformNodes(true);
  15915. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15916. var transformNode = transformNodes_1[_a];
  15917. transformNode.parent = null;
  15918. transformNode.computeWorldMatrix(true);
  15919. }
  15920. }
  15921. this.parent = null;
  15922. // Callback
  15923. this.onDisposeObservable.notifyObservers(this);
  15924. this.onDisposeObservable.clear();
  15925. // Behaviors
  15926. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15927. var behavior = _c[_b];
  15928. behavior.detach();
  15929. }
  15930. this._behaviors = [];
  15931. this._isDisposed = true;
  15932. };
  15933. /**
  15934. * Parse animation range data from a serialization object and store them into a given node
  15935. * @param node defines where to store the animation ranges
  15936. * @param parsedNode defines the serialization object to read data from
  15937. * @param scene defines the hosting scene
  15938. */
  15939. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15940. if (parsedNode.ranges) {
  15941. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15942. var data = parsedNode.ranges[index];
  15943. node.createAnimationRange(data.name, data.from, data.to);
  15944. }
  15945. }
  15946. };
  15947. __decorate([
  15948. BABYLON.serialize()
  15949. ], Node.prototype, "name", void 0);
  15950. __decorate([
  15951. BABYLON.serialize()
  15952. ], Node.prototype, "id", void 0);
  15953. __decorate([
  15954. BABYLON.serialize()
  15955. ], Node.prototype, "uniqueId", void 0);
  15956. __decorate([
  15957. BABYLON.serialize()
  15958. ], Node.prototype, "state", void 0);
  15959. __decorate([
  15960. BABYLON.serialize()
  15961. ], Node.prototype, "metadata", void 0);
  15962. return Node;
  15963. }());
  15964. BABYLON.Node = Node;
  15965. })(BABYLON || (BABYLON = {}));
  15966. //# sourceMappingURL=babylon.node.js.map
  15967. var BABYLON;
  15968. (function (BABYLON) {
  15969. var BoundingSphere = /** @class */ (function () {
  15970. function BoundingSphere(minimum, maximum) {
  15971. this.minimum = minimum;
  15972. this.maximum = maximum;
  15973. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15974. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15975. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15976. this.radius = distance * 0.5;
  15977. this.centerWorld = BABYLON.Vector3.Zero();
  15978. this._update(BABYLON.Matrix.Identity());
  15979. }
  15980. // Methods
  15981. BoundingSphere.prototype._update = function (world) {
  15982. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15983. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15984. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15985. };
  15986. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15987. for (var i = 0; i < 6; i++) {
  15988. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15989. return false;
  15990. }
  15991. return true;
  15992. };
  15993. BoundingSphere.prototype.intersectsPoint = function (point) {
  15994. var x = this.centerWorld.x - point.x;
  15995. var y = this.centerWorld.y - point.y;
  15996. var z = this.centerWorld.z - point.z;
  15997. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15998. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15999. return false;
  16000. return true;
  16001. };
  16002. // Statics
  16003. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16004. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16005. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16006. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16007. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16008. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16009. return false;
  16010. return true;
  16011. };
  16012. return BoundingSphere;
  16013. }());
  16014. BABYLON.BoundingSphere = BoundingSphere;
  16015. })(BABYLON || (BABYLON = {}));
  16016. //# sourceMappingURL=babylon.boundingSphere.js.map
  16017. var BABYLON;
  16018. (function (BABYLON) {
  16019. var BoundingBox = /** @class */ (function () {
  16020. function BoundingBox(minimum, maximum) {
  16021. this.minimum = minimum;
  16022. this.maximum = maximum;
  16023. this.vectors = new Array();
  16024. this.vectorsWorld = new Array();
  16025. // Bounding vectors
  16026. this.vectors.push(this.minimum.clone());
  16027. this.vectors.push(this.maximum.clone());
  16028. this.vectors.push(this.minimum.clone());
  16029. this.vectors[2].x = this.maximum.x;
  16030. this.vectors.push(this.minimum.clone());
  16031. this.vectors[3].y = this.maximum.y;
  16032. this.vectors.push(this.minimum.clone());
  16033. this.vectors[4].z = this.maximum.z;
  16034. this.vectors.push(this.maximum.clone());
  16035. this.vectors[5].z = this.minimum.z;
  16036. this.vectors.push(this.maximum.clone());
  16037. this.vectors[6].x = this.minimum.x;
  16038. this.vectors.push(this.maximum.clone());
  16039. this.vectors[7].y = this.minimum.y;
  16040. // OBB
  16041. this.center = this.maximum.add(this.minimum).scale(0.5);
  16042. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16043. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16044. // World
  16045. for (var index = 0; index < this.vectors.length; index++) {
  16046. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16047. }
  16048. this.minimumWorld = BABYLON.Vector3.Zero();
  16049. this.maximumWorld = BABYLON.Vector3.Zero();
  16050. this.centerWorld = BABYLON.Vector3.Zero();
  16051. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16052. this._update(BABYLON.Matrix.Identity());
  16053. }
  16054. // Methods
  16055. BoundingBox.prototype.getWorldMatrix = function () {
  16056. return this._worldMatrix;
  16057. };
  16058. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16059. this._worldMatrix.copyFrom(matrix);
  16060. return this;
  16061. };
  16062. BoundingBox.prototype._update = function (world) {
  16063. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16064. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16065. for (var index = 0; index < this.vectors.length; index++) {
  16066. var v = this.vectorsWorld[index];
  16067. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16068. if (v.x < this.minimumWorld.x)
  16069. this.minimumWorld.x = v.x;
  16070. if (v.y < this.minimumWorld.y)
  16071. this.minimumWorld.y = v.y;
  16072. if (v.z < this.minimumWorld.z)
  16073. this.minimumWorld.z = v.z;
  16074. if (v.x > this.maximumWorld.x)
  16075. this.maximumWorld.x = v.x;
  16076. if (v.y > this.maximumWorld.y)
  16077. this.maximumWorld.y = v.y;
  16078. if (v.z > this.maximumWorld.z)
  16079. this.maximumWorld.z = v.z;
  16080. }
  16081. // Extend
  16082. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16083. this.extendSizeWorld.scaleInPlace(0.5);
  16084. // OBB
  16085. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16086. this.centerWorld.scaleInPlace(0.5);
  16087. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16088. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16089. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16090. this._worldMatrix = world;
  16091. };
  16092. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16093. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16094. };
  16095. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16096. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16097. };
  16098. BoundingBox.prototype.intersectsPoint = function (point) {
  16099. var delta = -BABYLON.Epsilon;
  16100. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16101. return false;
  16102. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16103. return false;
  16104. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16105. return false;
  16106. return true;
  16107. };
  16108. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16109. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16110. };
  16111. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16112. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16113. return false;
  16114. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16115. return false;
  16116. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16117. return false;
  16118. return true;
  16119. };
  16120. // Statics
  16121. BoundingBox.Intersects = function (box0, box1) {
  16122. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16123. return false;
  16124. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16125. return false;
  16126. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16127. return false;
  16128. return true;
  16129. };
  16130. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16131. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16132. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16133. return (num <= (sphereRadius * sphereRadius));
  16134. };
  16135. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16136. for (var p = 0; p < 6; p++) {
  16137. for (var i = 0; i < 8; i++) {
  16138. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16139. return false;
  16140. }
  16141. }
  16142. }
  16143. return true;
  16144. };
  16145. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16146. for (var p = 0; p < 6; p++) {
  16147. var inCount = 8;
  16148. for (var i = 0; i < 8; i++) {
  16149. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16150. --inCount;
  16151. }
  16152. else {
  16153. break;
  16154. }
  16155. }
  16156. if (inCount === 0)
  16157. return false;
  16158. }
  16159. return true;
  16160. };
  16161. return BoundingBox;
  16162. }());
  16163. BABYLON.BoundingBox = BoundingBox;
  16164. })(BABYLON || (BABYLON = {}));
  16165. //# sourceMappingURL=babylon.boundingBox.js.map
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var computeBoxExtents = function (axis, box) {
  16169. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16170. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16171. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16172. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16173. var r = r0 + r1 + r2;
  16174. return {
  16175. min: p - r,
  16176. max: p + r
  16177. };
  16178. };
  16179. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16180. var axisOverlap = function (axis, box0, box1) {
  16181. var result0 = computeBoxExtents(axis, box0);
  16182. var result1 = computeBoxExtents(axis, box1);
  16183. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16184. };
  16185. var BoundingInfo = /** @class */ (function () {
  16186. function BoundingInfo(minimum, maximum) {
  16187. this.minimum = minimum;
  16188. this.maximum = maximum;
  16189. this._isLocked = false;
  16190. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16191. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16192. }
  16193. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16194. get: function () {
  16195. return this._isLocked;
  16196. },
  16197. set: function (value) {
  16198. this._isLocked = value;
  16199. },
  16200. enumerable: true,
  16201. configurable: true
  16202. });
  16203. // Methods
  16204. BoundingInfo.prototype.update = function (world) {
  16205. if (this._isLocked) {
  16206. return;
  16207. }
  16208. this.boundingBox._update(world);
  16209. this.boundingSphere._update(world);
  16210. };
  16211. /**
  16212. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16213. * @param center New center of the bounding info
  16214. * @param extend New extend of the bounding info
  16215. */
  16216. BoundingInfo.prototype.centerOn = function (center, extend) {
  16217. this.minimum = center.subtract(extend);
  16218. this.maximum = center.add(extend);
  16219. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16220. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16221. return this;
  16222. };
  16223. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16224. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16225. return false;
  16226. return this.boundingBox.isInFrustum(frustumPlanes);
  16227. };
  16228. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16229. /**
  16230. * Gets the world distance between the min and max points of the bounding box
  16231. */
  16232. get: function () {
  16233. var boundingBox = this.boundingBox;
  16234. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16235. return size.length();
  16236. },
  16237. enumerable: true,
  16238. configurable: true
  16239. });
  16240. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16241. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16242. };
  16243. BoundingInfo.prototype._checkCollision = function (collider) {
  16244. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16245. };
  16246. BoundingInfo.prototype.intersectsPoint = function (point) {
  16247. if (!this.boundingSphere.centerWorld) {
  16248. return false;
  16249. }
  16250. if (!this.boundingSphere.intersectsPoint(point)) {
  16251. return false;
  16252. }
  16253. if (!this.boundingBox.intersectsPoint(point)) {
  16254. return false;
  16255. }
  16256. return true;
  16257. };
  16258. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16259. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16260. return false;
  16261. }
  16262. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16263. return false;
  16264. }
  16265. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16266. return false;
  16267. }
  16268. if (!precise) {
  16269. return true;
  16270. }
  16271. var box0 = this.boundingBox;
  16272. var box1 = boundingInfo.boundingBox;
  16273. if (!axisOverlap(box0.directions[0], box0, box1))
  16274. return false;
  16275. if (!axisOverlap(box0.directions[1], box0, box1))
  16276. return false;
  16277. if (!axisOverlap(box0.directions[2], box0, box1))
  16278. return false;
  16279. if (!axisOverlap(box1.directions[0], box0, box1))
  16280. return false;
  16281. if (!axisOverlap(box1.directions[1], box0, box1))
  16282. return false;
  16283. if (!axisOverlap(box1.directions[2], box0, box1))
  16284. return false;
  16285. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16286. return false;
  16287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16288. return false;
  16289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16290. return false;
  16291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16292. return false;
  16293. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16294. return false;
  16295. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16296. return false;
  16297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16298. return false;
  16299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16300. return false;
  16301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16302. return false;
  16303. return true;
  16304. };
  16305. return BoundingInfo;
  16306. }());
  16307. BABYLON.BoundingInfo = BoundingInfo;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.boundingInfo.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var TransformNode = /** @class */ (function (_super) {
  16313. __extends(TransformNode, _super);
  16314. function TransformNode(name, scene, isPure) {
  16315. if (scene === void 0) { scene = null; }
  16316. if (isPure === void 0) { isPure = true; }
  16317. var _this = _super.call(this, name, scene) || this;
  16318. // Properties
  16319. _this._rotation = BABYLON.Vector3.Zero();
  16320. _this._scaling = BABYLON.Vector3.One();
  16321. _this._isDirty = false;
  16322. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16323. _this.scalingDeterminant = 1;
  16324. _this.infiniteDistance = false;
  16325. _this.position = BABYLON.Vector3.Zero();
  16326. _this._localWorld = BABYLON.Matrix.Zero();
  16327. _this._worldMatrix = BABYLON.Matrix.Zero();
  16328. _this._worldMatrixDeterminant = 0;
  16329. _this._absolutePosition = BABYLON.Vector3.Zero();
  16330. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16331. _this._postMultiplyPivotMatrix = false;
  16332. _this._isWorldMatrixFrozen = false;
  16333. /**
  16334. * An event triggered after the world matrix is updated
  16335. * @type {BABYLON.Observable}
  16336. */
  16337. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16338. _this._nonUniformScaling = false;
  16339. if (isPure) {
  16340. _this.getScene().addTransformNode(_this);
  16341. }
  16342. return _this;
  16343. }
  16344. /**
  16345. * Gets a string idenfifying the name of the class
  16346. * @returns "TransformNode" string
  16347. */
  16348. TransformNode.prototype.getClassName = function () {
  16349. return "TransformNode";
  16350. };
  16351. Object.defineProperty(TransformNode.prototype, "rotation", {
  16352. /**
  16353. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16354. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16355. * Default : (0.0, 0.0, 0.0)
  16356. */
  16357. get: function () {
  16358. return this._rotation;
  16359. },
  16360. set: function (newRotation) {
  16361. this._rotation = newRotation;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(TransformNode.prototype, "scaling", {
  16367. /**
  16368. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16369. * Default : (1.0, 1.0, 1.0)
  16370. */
  16371. get: function () {
  16372. return this._scaling;
  16373. },
  16374. /**
  16375. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16376. * Default : (1.0, 1.0, 1.0)
  16377. */
  16378. set: function (newScaling) {
  16379. this._scaling = newScaling;
  16380. },
  16381. enumerable: true,
  16382. configurable: true
  16383. });
  16384. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16385. /**
  16386. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16387. * It's null by default.
  16388. * 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)
  16389. */
  16390. get: function () {
  16391. return this._rotationQuaternion;
  16392. },
  16393. set: function (quaternion) {
  16394. this._rotationQuaternion = quaternion;
  16395. //reset the rotation vector.
  16396. if (quaternion && this.rotation.length()) {
  16397. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16398. }
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. /**
  16404. * Returns the latest update of the World matrix
  16405. * Returns a Matrix.
  16406. */
  16407. TransformNode.prototype.getWorldMatrix = function () {
  16408. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16409. this.computeWorldMatrix();
  16410. }
  16411. return this._worldMatrix;
  16412. };
  16413. /**
  16414. * Returns the latest update of the World matrix determinant.
  16415. */
  16416. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16417. return this._worldMatrixDeterminant;
  16418. };
  16419. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16420. /**
  16421. * Returns directly the latest state of the mesh World matrix.
  16422. * A Matrix is returned.
  16423. */
  16424. get: function () {
  16425. return this._worldMatrix;
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. /**
  16431. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16432. * Returns the AbstractMesh.
  16433. */
  16434. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16435. this._poseMatrix.copyFrom(matrix);
  16436. return this;
  16437. };
  16438. /**
  16439. * Returns the mesh Pose matrix.
  16440. * Returned object : Matrix
  16441. */
  16442. TransformNode.prototype.getPoseMatrix = function () {
  16443. return this._poseMatrix;
  16444. };
  16445. TransformNode.prototype._isSynchronized = function () {
  16446. if (this._isDirty) {
  16447. return false;
  16448. }
  16449. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16450. return false;
  16451. if (this._cache.pivotMatrixUpdated) {
  16452. return false;
  16453. }
  16454. if (this.infiniteDistance) {
  16455. return false;
  16456. }
  16457. if (!this._cache.position.equals(this.position))
  16458. return false;
  16459. if (this.rotationQuaternion) {
  16460. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16461. return false;
  16462. }
  16463. if (!this._cache.rotation.equals(this.rotation))
  16464. return false;
  16465. if (!this._cache.scaling.equals(this.scaling))
  16466. return false;
  16467. return true;
  16468. };
  16469. TransformNode.prototype._initCache = function () {
  16470. _super.prototype._initCache.call(this);
  16471. this._cache.localMatrixUpdated = false;
  16472. this._cache.position = BABYLON.Vector3.Zero();
  16473. this._cache.scaling = BABYLON.Vector3.Zero();
  16474. this._cache.rotation = BABYLON.Vector3.Zero();
  16475. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16476. this._cache.billboardMode = -1;
  16477. };
  16478. TransformNode.prototype.markAsDirty = function (property) {
  16479. if (property === "rotation") {
  16480. this.rotationQuaternion = null;
  16481. }
  16482. this._currentRenderId = Number.MAX_VALUE;
  16483. this._isDirty = true;
  16484. return this;
  16485. };
  16486. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16487. /**
  16488. * Returns the current mesh absolute position.
  16489. * Retuns a Vector3.
  16490. */
  16491. get: function () {
  16492. return this._absolutePosition;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. /**
  16498. * Sets a new matrix to apply before all other transformation
  16499. * @param matrix defines the transform matrix
  16500. * @returns the current TransformNode
  16501. */
  16502. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16503. return this.setPivotMatrix(matrix, false);
  16504. };
  16505. /**
  16506. * Sets a new pivot matrix to the current node
  16507. * @param matrix defines the new pivot matrix to use
  16508. * @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
  16509. * @returns the current TransformNode
  16510. */
  16511. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16512. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16513. this._pivotMatrix = matrix.clone();
  16514. this._cache.pivotMatrixUpdated = true;
  16515. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16516. if (this._postMultiplyPivotMatrix) {
  16517. if (!this._pivotMatrixInverse) {
  16518. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16519. }
  16520. else {
  16521. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16522. }
  16523. }
  16524. return this;
  16525. };
  16526. /**
  16527. * Returns the mesh pivot matrix.
  16528. * Default : Identity.
  16529. * A Matrix is returned.
  16530. */
  16531. TransformNode.prototype.getPivotMatrix = function () {
  16532. return this._pivotMatrix;
  16533. };
  16534. /**
  16535. * Prevents the World matrix to be computed any longer.
  16536. * Returns the AbstractMesh.
  16537. */
  16538. TransformNode.prototype.freezeWorldMatrix = function () {
  16539. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16540. this.computeWorldMatrix(true);
  16541. this._isWorldMatrixFrozen = true;
  16542. return this;
  16543. };
  16544. /**
  16545. * Allows back the World matrix computation.
  16546. * Returns the AbstractMesh.
  16547. */
  16548. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16549. this._isWorldMatrixFrozen = false;
  16550. this.computeWorldMatrix(true);
  16551. return this;
  16552. };
  16553. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16554. /**
  16555. * True if the World matrix has been frozen.
  16556. * Returns a boolean.
  16557. */
  16558. get: function () {
  16559. return this._isWorldMatrixFrozen;
  16560. },
  16561. enumerable: true,
  16562. configurable: true
  16563. });
  16564. /**
  16565. * Retuns the mesh absolute position in the World.
  16566. * Returns a Vector3.
  16567. */
  16568. TransformNode.prototype.getAbsolutePosition = function () {
  16569. this.computeWorldMatrix();
  16570. return this._absolutePosition;
  16571. };
  16572. /**
  16573. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16574. * Returns the AbstractMesh.
  16575. */
  16576. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16577. if (!absolutePosition) {
  16578. return this;
  16579. }
  16580. var absolutePositionX;
  16581. var absolutePositionY;
  16582. var absolutePositionZ;
  16583. if (absolutePosition.x === undefined) {
  16584. if (arguments.length < 3) {
  16585. return this;
  16586. }
  16587. absolutePositionX = arguments[0];
  16588. absolutePositionY = arguments[1];
  16589. absolutePositionZ = arguments[2];
  16590. }
  16591. else {
  16592. absolutePositionX = absolutePosition.x;
  16593. absolutePositionY = absolutePosition.y;
  16594. absolutePositionZ = absolutePosition.z;
  16595. }
  16596. if (this.parent) {
  16597. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16598. invertParentWorldMatrix.invert();
  16599. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16600. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16601. }
  16602. else {
  16603. this.position.x = absolutePositionX;
  16604. this.position.y = absolutePositionY;
  16605. this.position.z = absolutePositionZ;
  16606. }
  16607. return this;
  16608. };
  16609. /**
  16610. * Sets the mesh position in its local space.
  16611. * Returns the AbstractMesh.
  16612. */
  16613. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16614. this.computeWorldMatrix();
  16615. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16616. return this;
  16617. };
  16618. /**
  16619. * Returns the mesh position in the local space from the current World matrix values.
  16620. * Returns a new Vector3.
  16621. */
  16622. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16623. this.computeWorldMatrix();
  16624. var invLocalWorldMatrix = this._localWorld.clone();
  16625. invLocalWorldMatrix.invert();
  16626. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16627. };
  16628. /**
  16629. * Translates the mesh along the passed Vector3 in its local space.
  16630. * Returns the AbstractMesh.
  16631. */
  16632. TransformNode.prototype.locallyTranslate = function (vector3) {
  16633. this.computeWorldMatrix(true);
  16634. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16635. return this;
  16636. };
  16637. /**
  16638. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16639. * @param targetPoint the position (must be in same space as current mesh) to look at
  16640. * @param yawCor optional yaw (y-axis) correction in radians
  16641. * @param pitchCor optional pitch (x-axis) correction in radians
  16642. * @param rollCor optional roll (z-axis) correction in radians
  16643. * @param space the choosen space of the target
  16644. * @returns the TransformNode.
  16645. */
  16646. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16647. if (yawCor === void 0) { yawCor = 0; }
  16648. if (pitchCor === void 0) { pitchCor = 0; }
  16649. if (rollCor === void 0) { rollCor = 0; }
  16650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16651. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16652. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16653. targetPoint.subtractToRef(pos, dv);
  16654. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16655. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16656. var pitch = Math.atan2(dv.y, len);
  16657. if (this.rotationQuaternion) {
  16658. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16659. }
  16660. else {
  16661. this.rotation.x = pitch + pitchCor;
  16662. this.rotation.y = yaw + yawCor;
  16663. this.rotation.z = rollCor;
  16664. }
  16665. return this;
  16666. };
  16667. /**
  16668. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16669. * This Vector3 is expressed in the World space.
  16670. */
  16671. TransformNode.prototype.getDirection = function (localAxis) {
  16672. var result = BABYLON.Vector3.Zero();
  16673. this.getDirectionToRef(localAxis, result);
  16674. return result;
  16675. };
  16676. /**
  16677. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16678. * localAxis is expressed in the mesh local space.
  16679. * result is computed in the Wordl space from the mesh World matrix.
  16680. * Returns the AbstractMesh.
  16681. */
  16682. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16683. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16684. return this;
  16685. };
  16686. /**
  16687. * Sets a new pivot point to the current node
  16688. * @param point defines the new pivot point to use
  16689. * @param space defines if the point is in world or local space (local by default)
  16690. * @returns the current TransformNode
  16691. */
  16692. TransformNode.prototype.setPivotPoint = function (point, space) {
  16693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16694. if (this.getScene().getRenderId() == 0) {
  16695. this.computeWorldMatrix(true);
  16696. }
  16697. var wm = this.getWorldMatrix();
  16698. if (space == BABYLON.Space.WORLD) {
  16699. var tmat = BABYLON.Tmp.Matrix[0];
  16700. wm.invertToRef(tmat);
  16701. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16702. }
  16703. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16704. };
  16705. /**
  16706. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16707. */
  16708. TransformNode.prototype.getPivotPoint = function () {
  16709. var point = BABYLON.Vector3.Zero();
  16710. this.getPivotPointToRef(point);
  16711. return point;
  16712. };
  16713. /**
  16714. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16715. * Returns the AbstractMesh.
  16716. */
  16717. TransformNode.prototype.getPivotPointToRef = function (result) {
  16718. result.x = -this._pivotMatrix.m[12];
  16719. result.y = -this._pivotMatrix.m[13];
  16720. result.z = -this._pivotMatrix.m[14];
  16721. return this;
  16722. };
  16723. /**
  16724. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16725. */
  16726. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16727. var point = BABYLON.Vector3.Zero();
  16728. this.getAbsolutePivotPointToRef(point);
  16729. return point;
  16730. };
  16731. /**
  16732. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16733. * Returns the AbstractMesh.
  16734. */
  16735. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16736. result.x = this._pivotMatrix.m[12];
  16737. result.y = this._pivotMatrix.m[13];
  16738. result.z = this._pivotMatrix.m[14];
  16739. this.getPivotPointToRef(result);
  16740. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16741. return this;
  16742. };
  16743. /**
  16744. * Defines the passed node as the parent of the current node.
  16745. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16746. * Returns the TransformNode.
  16747. */
  16748. TransformNode.prototype.setParent = function (node) {
  16749. if (node === null) {
  16750. var rotation = BABYLON.Tmp.Quaternion[0];
  16751. var position = BABYLON.Tmp.Vector3[0];
  16752. var scale = BABYLON.Tmp.Vector3[1];
  16753. if (this.parent && this.parent.computeWorldMatrix) {
  16754. this.parent.computeWorldMatrix(true);
  16755. }
  16756. this.computeWorldMatrix(true);
  16757. this.getWorldMatrix().decompose(scale, rotation, position);
  16758. if (this.rotationQuaternion) {
  16759. this.rotationQuaternion.copyFrom(rotation);
  16760. }
  16761. else {
  16762. rotation.toEulerAnglesToRef(this.rotation);
  16763. }
  16764. this.scaling.x = scale.x;
  16765. this.scaling.y = scale.y;
  16766. this.scaling.z = scale.z;
  16767. this.position.x = position.x;
  16768. this.position.y = position.y;
  16769. this.position.z = position.z;
  16770. }
  16771. else {
  16772. var rotation = BABYLON.Tmp.Quaternion[0];
  16773. var position = BABYLON.Tmp.Vector3[0];
  16774. var scale = BABYLON.Tmp.Vector3[1];
  16775. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16776. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16777. this.computeWorldMatrix(true);
  16778. node.computeWorldMatrix(true);
  16779. node.getWorldMatrix().invertToRef(invParentMatrix);
  16780. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16781. diffMatrix.decompose(scale, rotation, position);
  16782. if (this.rotationQuaternion) {
  16783. this.rotationQuaternion.copyFrom(rotation);
  16784. }
  16785. else {
  16786. rotation.toEulerAnglesToRef(this.rotation);
  16787. }
  16788. this.position.x = position.x;
  16789. this.position.y = position.y;
  16790. this.position.z = position.z;
  16791. this.scaling.x = scale.x;
  16792. this.scaling.y = scale.y;
  16793. this.scaling.z = scale.z;
  16794. }
  16795. this.parent = node;
  16796. return this;
  16797. };
  16798. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16799. get: function () {
  16800. return this._nonUniformScaling;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16806. if (this._nonUniformScaling === value) {
  16807. return false;
  16808. }
  16809. this._nonUniformScaling = true;
  16810. return true;
  16811. };
  16812. /**
  16813. * Attach the current TransformNode to another TransformNode associated with a bone
  16814. * @param bone Bone affecting the TransformNode
  16815. * @param affectedTransformNode TransformNode associated with the bone
  16816. */
  16817. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16818. this._transformToBoneReferal = affectedTransformNode;
  16819. this.parent = bone;
  16820. if (bone.getWorldMatrix().determinant() < 0) {
  16821. this.scalingDeterminant *= -1;
  16822. }
  16823. return this;
  16824. };
  16825. TransformNode.prototype.detachFromBone = function () {
  16826. if (!this.parent) {
  16827. return this;
  16828. }
  16829. if (this.parent.getWorldMatrix().determinant() < 0) {
  16830. this.scalingDeterminant *= -1;
  16831. }
  16832. this._transformToBoneReferal = null;
  16833. this.parent = null;
  16834. return this;
  16835. };
  16836. /**
  16837. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16838. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16839. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16840. * The passed axis is also normalized.
  16841. * Returns the AbstractMesh.
  16842. */
  16843. TransformNode.prototype.rotate = function (axis, amount, space) {
  16844. axis.normalize();
  16845. if (!this.rotationQuaternion) {
  16846. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16847. this.rotation = BABYLON.Vector3.Zero();
  16848. }
  16849. var rotationQuaternion;
  16850. if (!space || space === BABYLON.Space.LOCAL) {
  16851. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16852. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16853. }
  16854. else {
  16855. if (this.parent) {
  16856. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16857. invertParentWorldMatrix.invert();
  16858. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16859. }
  16860. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16861. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16862. }
  16863. return this;
  16864. };
  16865. /**
  16866. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16867. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16868. * The passed axis is also normalized.
  16869. * Returns the AbstractMesh.
  16870. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16871. */
  16872. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16873. axis.normalize();
  16874. if (!this.rotationQuaternion) {
  16875. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16876. this.rotation.copyFromFloats(0, 0, 0);
  16877. }
  16878. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16879. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16880. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16881. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16882. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16883. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16884. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16885. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16886. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16887. return this;
  16888. };
  16889. /**
  16890. * Translates the mesh along the axis vector for the passed distance in the given space.
  16891. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16892. * Returns the AbstractMesh.
  16893. */
  16894. TransformNode.prototype.translate = function (axis, distance, space) {
  16895. var displacementVector = axis.scale(distance);
  16896. if (!space || space === BABYLON.Space.LOCAL) {
  16897. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16898. this.setPositionWithLocalVector(tempV3);
  16899. }
  16900. else {
  16901. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16902. }
  16903. return this;
  16904. };
  16905. /**
  16906. * Adds a rotation step to the mesh current rotation.
  16907. * x, y, z are Euler angles expressed in radians.
  16908. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16909. * This means this rotation is made in the mesh local space only.
  16910. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16911. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16912. * ```javascript
  16913. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16914. * ```
  16915. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16916. * 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.
  16917. * Returns the AbstractMesh.
  16918. */
  16919. TransformNode.prototype.addRotation = function (x, y, z) {
  16920. var rotationQuaternion;
  16921. if (this.rotationQuaternion) {
  16922. rotationQuaternion = this.rotationQuaternion;
  16923. }
  16924. else {
  16925. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16926. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16927. }
  16928. var accumulation = BABYLON.Tmp.Quaternion[0];
  16929. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16930. rotationQuaternion.multiplyInPlace(accumulation);
  16931. if (!this.rotationQuaternion) {
  16932. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16933. }
  16934. return this;
  16935. };
  16936. /**
  16937. * Computes the mesh World matrix and returns it.
  16938. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16939. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16940. * If the parameter `force`is set to `true`, the actual computation is done.
  16941. * Returns the mesh World Matrix.
  16942. */
  16943. TransformNode.prototype.computeWorldMatrix = function (force) {
  16944. if (this._isWorldMatrixFrozen) {
  16945. return this._worldMatrix;
  16946. }
  16947. if (!force && this.isSynchronized(true)) {
  16948. return this._worldMatrix;
  16949. }
  16950. this._cache.position.copyFrom(this.position);
  16951. this._cache.scaling.copyFrom(this.scaling);
  16952. this._cache.pivotMatrixUpdated = false;
  16953. this._cache.billboardMode = this.billboardMode;
  16954. this._currentRenderId = this.getScene().getRenderId();
  16955. this._isDirty = false;
  16956. // Scaling
  16957. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16958. // Rotation
  16959. //rotate, if quaternion is set and rotation was used
  16960. if (this.rotationQuaternion) {
  16961. var len = this.rotation.length();
  16962. if (len) {
  16963. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16964. this.rotation.copyFromFloats(0, 0, 0);
  16965. }
  16966. }
  16967. if (this.rotationQuaternion) {
  16968. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16969. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16970. }
  16971. else {
  16972. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16973. this._cache.rotation.copyFrom(this.rotation);
  16974. }
  16975. // Translation
  16976. var camera = this.getScene().activeCamera;
  16977. if (this.infiniteDistance && !this.parent && camera) {
  16978. var cameraWorldMatrix = camera.getWorldMatrix();
  16979. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16980. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16981. }
  16982. else {
  16983. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16984. }
  16985. // Composing transformations
  16986. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16987. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16988. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16989. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16990. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16991. // Need to decompose each rotation here
  16992. var currentPosition = BABYLON.Tmp.Vector3[3];
  16993. if (this.parent && this.parent.getWorldMatrix) {
  16994. if (this._transformToBoneReferal) {
  16995. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16996. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16997. }
  16998. else {
  16999. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17000. }
  17001. }
  17002. else {
  17003. currentPosition.copyFrom(this.position);
  17004. }
  17005. currentPosition.subtractInPlace(camera.globalPosition);
  17006. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17007. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17008. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17009. }
  17010. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17011. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17012. }
  17013. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17014. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17015. }
  17016. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17017. }
  17018. else {
  17019. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17020. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17021. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17022. }
  17023. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17024. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17025. }
  17026. // Local world
  17027. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17028. // Parent
  17029. if (this.parent && this.parent.getWorldMatrix) {
  17030. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17031. if (this._transformToBoneReferal) {
  17032. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17033. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17034. }
  17035. else {
  17036. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17037. }
  17038. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17039. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17040. this._worldMatrix.copyFrom(this._localWorld);
  17041. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17042. }
  17043. else {
  17044. if (this._transformToBoneReferal) {
  17045. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17046. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17047. }
  17048. else {
  17049. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17050. }
  17051. }
  17052. this._markSyncedWithParent();
  17053. }
  17054. else {
  17055. this._worldMatrix.copyFrom(this._localWorld);
  17056. }
  17057. // Post multiply inverse of pivotMatrix
  17058. if (this._postMultiplyPivotMatrix) {
  17059. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17060. }
  17061. // Normal matrix
  17062. if (this.scaling.isNonUniform) {
  17063. this._updateNonUniformScalingState(true);
  17064. }
  17065. else if (this.parent && this.parent._nonUniformScaling) {
  17066. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17067. }
  17068. else {
  17069. this._updateNonUniformScalingState(false);
  17070. }
  17071. this._afterComputeWorldMatrix();
  17072. // Absolute position
  17073. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17074. // Callbacks
  17075. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17076. if (!this._poseMatrix) {
  17077. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17078. }
  17079. // Cache the determinant
  17080. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17081. return this._worldMatrix;
  17082. };
  17083. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17084. };
  17085. /**
  17086. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17087. * @param func: callback function to add
  17088. *
  17089. * Returns the TransformNode.
  17090. */
  17091. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17092. this.onAfterWorldMatrixUpdateObservable.add(func);
  17093. return this;
  17094. };
  17095. /**
  17096. * Removes a registered callback function.
  17097. * Returns the TransformNode.
  17098. */
  17099. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17100. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17101. return this;
  17102. };
  17103. /**
  17104. * Clone the current transform node
  17105. * Returns the new transform node
  17106. * @param name Name of the new clone
  17107. * @param newParent New parent for the clone
  17108. * @param doNotCloneChildren Do not clone children hierarchy
  17109. */
  17110. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17111. var _this = this;
  17112. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17113. result.name = name;
  17114. result.id = name;
  17115. if (newParent) {
  17116. result.parent = newParent;
  17117. }
  17118. if (!doNotCloneChildren) {
  17119. // Children
  17120. var directDescendants = this.getDescendants(true);
  17121. for (var index = 0; index < directDescendants.length; index++) {
  17122. var child = directDescendants[index];
  17123. if (child.clone) {
  17124. child.clone(name + "." + child.name, result);
  17125. }
  17126. }
  17127. }
  17128. return result;
  17129. };
  17130. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17131. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17132. serializationObject.type = this.getClassName();
  17133. // Parent
  17134. if (this.parent) {
  17135. serializationObject.parentId = this.parent.id;
  17136. }
  17137. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17138. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17139. }
  17140. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17141. serializationObject.isEnabled = this.isEnabled();
  17142. // Parent
  17143. if (this.parent) {
  17144. serializationObject.parentId = this.parent.id;
  17145. }
  17146. return serializationObject;
  17147. };
  17148. // Statics
  17149. /**
  17150. * Returns a new TransformNode object parsed from the source provided.
  17151. * The parameter `parsedMesh` is the source.
  17152. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17153. */
  17154. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17155. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17156. if (BABYLON.Tags) {
  17157. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17158. }
  17159. if (parsedTransformNode.localMatrix) {
  17160. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17161. }
  17162. else if (parsedTransformNode.pivotMatrix) {
  17163. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17164. }
  17165. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17166. // Parent
  17167. if (parsedTransformNode.parentId) {
  17168. transformNode._waitingParentId = parsedTransformNode.parentId;
  17169. }
  17170. return transformNode;
  17171. };
  17172. /**
  17173. * Releases resources associated with this transform node.
  17174. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17175. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17176. */
  17177. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17178. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17179. // Animations
  17180. this.getScene().stopAnimation(this);
  17181. // Remove from scene
  17182. this.getScene().removeTransformNode(this);
  17183. this.onAfterWorldMatrixUpdateObservable.clear();
  17184. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17185. };
  17186. // Statics
  17187. TransformNode.BILLBOARDMODE_NONE = 0;
  17188. TransformNode.BILLBOARDMODE_X = 1;
  17189. TransformNode.BILLBOARDMODE_Y = 2;
  17190. TransformNode.BILLBOARDMODE_Z = 4;
  17191. TransformNode.BILLBOARDMODE_ALL = 7;
  17192. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17193. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17194. __decorate([
  17195. BABYLON.serializeAsVector3()
  17196. ], TransformNode.prototype, "_rotation", void 0);
  17197. __decorate([
  17198. BABYLON.serializeAsQuaternion()
  17199. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17200. __decorate([
  17201. BABYLON.serializeAsVector3()
  17202. ], TransformNode.prototype, "_scaling", void 0);
  17203. __decorate([
  17204. BABYLON.serialize()
  17205. ], TransformNode.prototype, "billboardMode", void 0);
  17206. __decorate([
  17207. BABYLON.serialize()
  17208. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17209. __decorate([
  17210. BABYLON.serialize()
  17211. ], TransformNode.prototype, "infiniteDistance", void 0);
  17212. __decorate([
  17213. BABYLON.serializeAsVector3()
  17214. ], TransformNode.prototype, "position", void 0);
  17215. return TransformNode;
  17216. }(BABYLON.Node));
  17217. BABYLON.TransformNode = TransformNode;
  17218. })(BABYLON || (BABYLON = {}));
  17219. //# sourceMappingURL=babylon.transformNode.js.map
  17220. var BABYLON;
  17221. (function (BABYLON) {
  17222. var AbstractMesh = /** @class */ (function (_super) {
  17223. __extends(AbstractMesh, _super);
  17224. // Constructor
  17225. function AbstractMesh(name, scene) {
  17226. if (scene === void 0) { scene = null; }
  17227. var _this = _super.call(this, name, scene, false) || this;
  17228. _this._facetNb = 0; // facet number
  17229. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17230. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17231. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17232. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17233. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17234. _this._subDiv = {
  17235. max: 1,
  17236. X: 1,
  17237. Y: 1,
  17238. Z: 1
  17239. };
  17240. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17241. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17242. // Events
  17243. /**
  17244. * An event triggered when this mesh collides with another one
  17245. * @type {BABYLON.Observable}
  17246. */
  17247. _this.onCollideObservable = new BABYLON.Observable();
  17248. /**
  17249. * An event triggered when the collision's position changes
  17250. * @type {BABYLON.Observable}
  17251. */
  17252. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17253. /**
  17254. * An event triggered when material is changed
  17255. * @type {BABYLON.Observable}
  17256. */
  17257. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17258. // Properties
  17259. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17260. /**
  17261. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17262. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17263. * or
  17264. * 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.
  17265. * for more info check WebGl documentations
  17266. */
  17267. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17268. /**
  17269. * 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:
  17270. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17271. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17272. * 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.
  17273. */
  17274. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17275. /**
  17276. * 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.
  17277. * The default value is -1 which means don't break the query and wait till the result.
  17278. */
  17279. _this.occlusionRetryCount = -1;
  17280. _this._occlusionInternalRetryCounter = 0;
  17281. _this._isOccluded = false;
  17282. _this._isOcclusionQueryInProgress = false;
  17283. _this._visibility = 1.0;
  17284. _this.alphaIndex = Number.MAX_VALUE;
  17285. _this.isVisible = true;
  17286. _this.isPickable = true;
  17287. _this.showBoundingBox = false;
  17288. _this.showSubMeshesBoundingBox = false;
  17289. _this.isBlocker = false;
  17290. _this.enablePointerMoveEvents = false;
  17291. _this.renderingGroupId = 0;
  17292. _this._receiveShadows = false;
  17293. _this.renderOutline = false;
  17294. _this.outlineColor = BABYLON.Color3.Red();
  17295. _this.outlineWidth = 0.02;
  17296. _this.renderOverlay = false;
  17297. _this.overlayColor = BABYLON.Color3.Red();
  17298. _this.overlayAlpha = 0.5;
  17299. _this._hasVertexAlpha = false;
  17300. _this._useVertexColors = true;
  17301. _this._computeBonesUsingShaders = true;
  17302. _this._numBoneInfluencers = 4;
  17303. _this._applyFog = true;
  17304. _this.useOctreeForRenderingSelection = true;
  17305. _this.useOctreeForPicking = true;
  17306. _this.useOctreeForCollisions = true;
  17307. _this._layerMask = 0x0FFFFFFF;
  17308. /**
  17309. * True if the mesh must be rendered in any case.
  17310. */
  17311. _this.alwaysSelectAsActiveMesh = false;
  17312. /**
  17313. * This scene's action manager
  17314. * @type {BABYLON.ActionManager}
  17315. */
  17316. _this.actionManager = null;
  17317. // Physics
  17318. _this.physicsImpostor = null;
  17319. // Collisions
  17320. _this._checkCollisions = false;
  17321. _this._collisionMask = -1;
  17322. _this._collisionGroup = -1;
  17323. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17324. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17325. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17326. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17327. // Edges
  17328. _this.edgesWidth = 1;
  17329. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17330. // Cache
  17331. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17332. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17333. _this._renderId = 0;
  17334. _this._intersectionsInProgress = new Array();
  17335. _this._unIndexed = false;
  17336. _this._lightSources = new Array();
  17337. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17338. if (collidedMesh === void 0) { collidedMesh = null; }
  17339. //TODO move this to the collision coordinator!
  17340. if (_this.getScene().workerCollisions)
  17341. newPosition.multiplyInPlace(_this._collider._radius);
  17342. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17343. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17344. _this.position.addInPlace(_this._diffPositionForCollisions);
  17345. }
  17346. if (collidedMesh) {
  17347. _this.onCollideObservable.notifyObservers(collidedMesh);
  17348. }
  17349. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17350. };
  17351. _this.getScene().addMesh(_this);
  17352. _this._resyncLightSources();
  17353. return _this;
  17354. }
  17355. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17356. get: function () {
  17357. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17358. },
  17359. enumerable: true,
  17360. configurable: true
  17361. });
  17362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17363. get: function () {
  17364. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17365. },
  17366. enumerable: true,
  17367. configurable: true
  17368. });
  17369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17370. get: function () {
  17371. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17377. get: function () {
  17378. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17384. get: function () {
  17385. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17386. },
  17387. enumerable: true,
  17388. configurable: true
  17389. });
  17390. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17391. /**
  17392. * Read-only : the number of facets in the mesh
  17393. */
  17394. get: function () {
  17395. return this._facetNb;
  17396. },
  17397. enumerable: true,
  17398. configurable: true
  17399. });
  17400. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17401. /**
  17402. * The number (integer) of subdivisions per axis in the partioning space
  17403. */
  17404. get: function () {
  17405. return this._partitioningSubdivisions;
  17406. },
  17407. set: function (nb) {
  17408. this._partitioningSubdivisions = nb;
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17414. /**
  17415. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17416. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17417. */
  17418. get: function () {
  17419. return this._partitioningBBoxRatio;
  17420. },
  17421. set: function (ratio) {
  17422. this._partitioningBBoxRatio = ratio;
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17428. /**
  17429. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17430. * Works only for updatable meshes.
  17431. * Doesn't work with multi-materials.
  17432. */
  17433. get: function () {
  17434. return this._facetDepthSort;
  17435. },
  17436. set: function (sort) {
  17437. this._facetDepthSort = sort;
  17438. },
  17439. enumerable: true,
  17440. configurable: true
  17441. });
  17442. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17443. /**
  17444. * The location (Vector3) where the facet depth sort must be computed from.
  17445. * By default, the active camera position.
  17446. * Used only when facet depth sort is enabled.
  17447. */
  17448. get: function () {
  17449. return this._facetDepthSortFrom;
  17450. },
  17451. set: function (location) {
  17452. this._facetDepthSortFrom = location;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17458. /**
  17459. * Read-only boolean : is the feature facetData enabled ?
  17460. */
  17461. get: function () {
  17462. return this._facetDataEnabled;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17468. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17469. return false;
  17470. }
  17471. this._markSubMeshesAsMiscDirty();
  17472. return true;
  17473. };
  17474. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17475. set: function (callback) {
  17476. if (this._onCollideObserver) {
  17477. this.onCollideObservable.remove(this._onCollideObserver);
  17478. }
  17479. this._onCollideObserver = this.onCollideObservable.add(callback);
  17480. },
  17481. enumerable: true,
  17482. configurable: true
  17483. });
  17484. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17485. set: function (callback) {
  17486. if (this._onCollisionPositionChangeObserver) {
  17487. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17488. }
  17489. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17495. /**
  17496. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17497. */
  17498. get: function () {
  17499. return this._isOccluded;
  17500. },
  17501. set: function (value) {
  17502. this._isOccluded = value;
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17508. /**
  17509. * Flag to check the progress status of the query
  17510. */
  17511. get: function () {
  17512. return this._isOcclusionQueryInProgress;
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17518. /**
  17519. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17520. */
  17521. get: function () {
  17522. return this._visibility;
  17523. },
  17524. /**
  17525. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17526. */
  17527. set: function (value) {
  17528. if (this._visibility === value) {
  17529. return;
  17530. }
  17531. this._visibility = value;
  17532. this._markSubMeshesAsMiscDirty();
  17533. },
  17534. enumerable: true,
  17535. configurable: true
  17536. });
  17537. Object.defineProperty(AbstractMesh.prototype, "material", {
  17538. get: function () {
  17539. return this._material;
  17540. },
  17541. set: function (value) {
  17542. if (this._material === value) {
  17543. return;
  17544. }
  17545. this._material = value;
  17546. if (this.onMaterialChangedObservable.hasObservers) {
  17547. this.onMaterialChangedObservable.notifyObservers(this);
  17548. }
  17549. if (!this.subMeshes) {
  17550. return;
  17551. }
  17552. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17553. var subMesh = _a[_i];
  17554. subMesh.setEffect(null);
  17555. }
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17561. get: function () {
  17562. return this._receiveShadows;
  17563. },
  17564. set: function (value) {
  17565. if (this._receiveShadows === value) {
  17566. return;
  17567. }
  17568. this._receiveShadows = value;
  17569. this._markSubMeshesAsLightDirty();
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17575. get: function () {
  17576. return this._hasVertexAlpha;
  17577. },
  17578. set: function (value) {
  17579. if (this._hasVertexAlpha === value) {
  17580. return;
  17581. }
  17582. this._hasVertexAlpha = value;
  17583. this._markSubMeshesAsAttributesDirty();
  17584. this._markSubMeshesAsMiscDirty();
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17590. get: function () {
  17591. return this._useVertexColors;
  17592. },
  17593. set: function (value) {
  17594. if (this._useVertexColors === value) {
  17595. return;
  17596. }
  17597. this._useVertexColors = value;
  17598. this._markSubMeshesAsAttributesDirty();
  17599. },
  17600. enumerable: true,
  17601. configurable: true
  17602. });
  17603. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17604. get: function () {
  17605. return this._computeBonesUsingShaders;
  17606. },
  17607. set: function (value) {
  17608. if (this._computeBonesUsingShaders === value) {
  17609. return;
  17610. }
  17611. this._computeBonesUsingShaders = value;
  17612. this._markSubMeshesAsAttributesDirty();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17618. get: function () {
  17619. return this._numBoneInfluencers;
  17620. },
  17621. set: function (value) {
  17622. if (this._numBoneInfluencers === value) {
  17623. return;
  17624. }
  17625. this._numBoneInfluencers = value;
  17626. this._markSubMeshesAsAttributesDirty();
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17632. get: function () {
  17633. return this._applyFog;
  17634. },
  17635. set: function (value) {
  17636. if (this._applyFog === value) {
  17637. return;
  17638. }
  17639. this._applyFog = value;
  17640. this._markSubMeshesAsMiscDirty();
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17646. get: function () {
  17647. return this._layerMask;
  17648. },
  17649. set: function (value) {
  17650. if (value === this._layerMask) {
  17651. return;
  17652. }
  17653. this._layerMask = value;
  17654. this._resyncLightSources();
  17655. },
  17656. enumerable: true,
  17657. configurable: true
  17658. });
  17659. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17660. get: function () {
  17661. return this._collisionMask;
  17662. },
  17663. set: function (mask) {
  17664. this._collisionMask = !isNaN(mask) ? mask : -1;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17670. get: function () {
  17671. return this._collisionGroup;
  17672. },
  17673. set: function (mask) {
  17674. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17680. get: function () {
  17681. return null;
  17682. },
  17683. enumerable: true,
  17684. configurable: true
  17685. });
  17686. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17687. get: function () {
  17688. return this._skeleton;
  17689. },
  17690. set: function (value) {
  17691. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17692. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17693. }
  17694. if (value && value.needInitialSkinMatrix) {
  17695. value._registerMeshWithPoseMatrix(this);
  17696. }
  17697. this._skeleton = value;
  17698. if (!this._skeleton) {
  17699. this._bonesTransformMatrices = null;
  17700. }
  17701. this._markSubMeshesAsAttributesDirty();
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. /**
  17707. * Returns the string "AbstractMesh"
  17708. */
  17709. AbstractMesh.prototype.getClassName = function () {
  17710. return "AbstractMesh";
  17711. };
  17712. /**
  17713. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17714. */
  17715. AbstractMesh.prototype.toString = function (fullDetails) {
  17716. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17717. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17718. if (this._skeleton) {
  17719. ret += ", skeleton: " + this._skeleton.name;
  17720. }
  17721. if (fullDetails) {
  17722. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17723. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17724. }
  17725. return ret;
  17726. };
  17727. AbstractMesh.prototype._rebuild = function () {
  17728. if (this._occlusionQuery) {
  17729. this._occlusionQuery = null;
  17730. }
  17731. if (this._edgesRenderer) {
  17732. this._edgesRenderer._rebuild();
  17733. }
  17734. if (!this.subMeshes) {
  17735. return;
  17736. }
  17737. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17738. var subMesh = _a[_i];
  17739. subMesh._rebuild();
  17740. }
  17741. };
  17742. AbstractMesh.prototype._resyncLightSources = function () {
  17743. this._lightSources.length = 0;
  17744. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17745. var light = _a[_i];
  17746. if (!light.isEnabled()) {
  17747. continue;
  17748. }
  17749. if (light.canAffectMesh(this)) {
  17750. this._lightSources.push(light);
  17751. }
  17752. }
  17753. this._markSubMeshesAsLightDirty();
  17754. };
  17755. AbstractMesh.prototype._resyncLighSource = function (light) {
  17756. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17757. var index = this._lightSources.indexOf(light);
  17758. if (index === -1) {
  17759. if (!isIn) {
  17760. return;
  17761. }
  17762. this._lightSources.push(light);
  17763. }
  17764. else {
  17765. if (isIn) {
  17766. return;
  17767. }
  17768. this._lightSources.splice(index, 1);
  17769. }
  17770. this._markSubMeshesAsLightDirty();
  17771. };
  17772. AbstractMesh.prototype._removeLightSource = function (light) {
  17773. var index = this._lightSources.indexOf(light);
  17774. if (index === -1) {
  17775. return;
  17776. }
  17777. this._lightSources.splice(index, 1);
  17778. this._markSubMeshesAsLightDirty();
  17779. };
  17780. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17781. if (!this.subMeshes) {
  17782. return;
  17783. }
  17784. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17785. var subMesh = _a[_i];
  17786. if (subMesh._materialDefines) {
  17787. func(subMesh._materialDefines);
  17788. }
  17789. }
  17790. };
  17791. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17792. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17793. };
  17794. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17795. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17796. };
  17797. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17798. if (!this.subMeshes) {
  17799. return;
  17800. }
  17801. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17802. var subMesh = _a[_i];
  17803. var material = subMesh.getMaterial();
  17804. if (material) {
  17805. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17806. }
  17807. }
  17808. };
  17809. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17810. /**
  17811. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17812. * Default : (1.0, 1.0, 1.0)
  17813. */
  17814. get: function () {
  17815. return this._scaling;
  17816. },
  17817. /**
  17818. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17819. * Default : (1.0, 1.0, 1.0)
  17820. */
  17821. set: function (newScaling) {
  17822. this._scaling = newScaling;
  17823. if (this.physicsImpostor) {
  17824. this.physicsImpostor.forceUpdate();
  17825. }
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. // Methods
  17831. /**
  17832. * Disables the mesh edger rendering mode.
  17833. * Returns the AbstractMesh.
  17834. */
  17835. AbstractMesh.prototype.disableEdgesRendering = function () {
  17836. if (this._edgesRenderer) {
  17837. this._edgesRenderer.dispose();
  17838. this._edgesRenderer = null;
  17839. }
  17840. return this;
  17841. };
  17842. /**
  17843. * Enables the edge rendering mode on the mesh.
  17844. * This mode makes the mesh edges visible.
  17845. * Returns the AbstractMesh.
  17846. */
  17847. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17848. if (epsilon === void 0) { epsilon = 0.95; }
  17849. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17850. this.disableEdgesRendering();
  17851. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17852. return this;
  17853. };
  17854. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17855. /**
  17856. * Returns true if the mesh is blocked. Used by the class Mesh.
  17857. * Returns the boolean `false` by default.
  17858. */
  17859. get: function () {
  17860. return false;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. /**
  17866. * Returns the mesh itself by default, used by the class Mesh.
  17867. * Returned type : AbstractMesh
  17868. */
  17869. AbstractMesh.prototype.getLOD = function (camera) {
  17870. return this;
  17871. };
  17872. /**
  17873. * Returns 0 by default, used by the class Mesh.
  17874. * Returns an integer.
  17875. */
  17876. AbstractMesh.prototype.getTotalVertices = function () {
  17877. return 0;
  17878. };
  17879. /**
  17880. * Returns null by default, used by the class Mesh.
  17881. * Returned type : integer array
  17882. */
  17883. AbstractMesh.prototype.getIndices = function () {
  17884. return null;
  17885. };
  17886. /**
  17887. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17888. * Returned type : float array or Float32Array
  17889. */
  17890. AbstractMesh.prototype.getVerticesData = function (kind) {
  17891. return null;
  17892. };
  17893. /**
  17894. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17895. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17896. * The `data` are either a numeric array either a Float32Array.
  17897. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17898. * 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).
  17899. * Note that a new underlying VertexBuffer object is created each call.
  17900. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17901. *
  17902. * Possible `kind` values :
  17903. * - BABYLON.VertexBuffer.PositionKind
  17904. * - BABYLON.VertexBuffer.UVKind
  17905. * - BABYLON.VertexBuffer.UV2Kind
  17906. * - BABYLON.VertexBuffer.UV3Kind
  17907. * - BABYLON.VertexBuffer.UV4Kind
  17908. * - BABYLON.VertexBuffer.UV5Kind
  17909. * - BABYLON.VertexBuffer.UV6Kind
  17910. * - BABYLON.VertexBuffer.ColorKind
  17911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17915. *
  17916. * Returns the Mesh.
  17917. */
  17918. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17919. return this;
  17920. };
  17921. /**
  17922. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17923. * If the mesh has no geometry, it is simply returned as it is.
  17924. * The `data` are either a numeric array either a Float32Array.
  17925. * No new underlying VertexBuffer object is created.
  17926. * 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.
  17927. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17928. *
  17929. * Possible `kind` values :
  17930. * - BABYLON.VertexBuffer.PositionKind
  17931. * - BABYLON.VertexBuffer.UVKind
  17932. * - BABYLON.VertexBuffer.UV2Kind
  17933. * - BABYLON.VertexBuffer.UV3Kind
  17934. * - BABYLON.VertexBuffer.UV4Kind
  17935. * - BABYLON.VertexBuffer.UV5Kind
  17936. * - BABYLON.VertexBuffer.UV6Kind
  17937. * - BABYLON.VertexBuffer.ColorKind
  17938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17942. *
  17943. * Returns the Mesh.
  17944. */
  17945. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17946. return this;
  17947. };
  17948. /**
  17949. * Sets the mesh indices.
  17950. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17951. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17952. * This method creates a new index buffer each call.
  17953. * Returns the Mesh.
  17954. */
  17955. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17956. return this;
  17957. };
  17958. /** Returns false by default, used by the class Mesh.
  17959. * Returns a boolean
  17960. */
  17961. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17962. return false;
  17963. };
  17964. /**
  17965. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17966. * Returns a BoundingInfo
  17967. */
  17968. AbstractMesh.prototype.getBoundingInfo = function () {
  17969. if (this._masterMesh) {
  17970. return this._masterMesh.getBoundingInfo();
  17971. }
  17972. if (!this._boundingInfo) {
  17973. // this._boundingInfo is being created here
  17974. this._updateBoundingInfo();
  17975. }
  17976. // cannot be null.
  17977. return this._boundingInfo;
  17978. };
  17979. /**
  17980. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17981. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17982. */
  17983. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17984. if (includeDescendants === void 0) { includeDescendants = true; }
  17985. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17986. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17987. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17988. if (maxDimension === 0) {
  17989. return this;
  17990. }
  17991. var scale = 1 / maxDimension;
  17992. this.scaling.scaleInPlace(scale);
  17993. return this;
  17994. };
  17995. /**
  17996. * Sets a mesh new object BoundingInfo.
  17997. * Returns the AbstractMesh.
  17998. */
  17999. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18000. this._boundingInfo = boundingInfo;
  18001. return this;
  18002. };
  18003. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18004. get: function () {
  18005. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. AbstractMesh.prototype._preActivate = function () {
  18011. };
  18012. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18013. };
  18014. AbstractMesh.prototype._activate = function (renderId) {
  18015. this._renderId = renderId;
  18016. };
  18017. /**
  18018. * Returns the latest update of the World matrix
  18019. * Returns a Matrix.
  18020. */
  18021. AbstractMesh.prototype.getWorldMatrix = function () {
  18022. if (this._masterMesh) {
  18023. return this._masterMesh.getWorldMatrix();
  18024. }
  18025. return _super.prototype.getWorldMatrix.call(this);
  18026. };
  18027. /**
  18028. * Returns the latest update of the World matrix determinant.
  18029. */
  18030. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18031. if (this._masterMesh) {
  18032. return this._masterMesh._getWorldMatrixDeterminant();
  18033. }
  18034. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18035. };
  18036. // ================================== Point of View Movement =================================
  18037. /**
  18038. * Perform relative position change from the point of view of behind the front of the mesh.
  18039. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18040. * Supports definition of mesh facing forward or backward.
  18041. * @param {number} amountRight
  18042. * @param {number} amountUp
  18043. * @param {number} amountForward
  18044. *
  18045. * Returns the AbstractMesh.
  18046. */
  18047. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18048. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18049. return this;
  18050. };
  18051. /**
  18052. * Calculate relative position change from the point of view of behind the front of the mesh.
  18053. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18054. * Supports definition of mesh facing forward or backward.
  18055. * @param {number} amountRight
  18056. * @param {number} amountUp
  18057. * @param {number} amountForward
  18058. *
  18059. * Returns a new Vector3.
  18060. */
  18061. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18062. var rotMatrix = new BABYLON.Matrix();
  18063. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18064. rotQuaternion.toRotationMatrix(rotMatrix);
  18065. var translationDelta = BABYLON.Vector3.Zero();
  18066. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18067. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18068. return translationDelta;
  18069. };
  18070. // ================================== Point of View Rotation =================================
  18071. /**
  18072. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18073. * Supports definition of mesh facing forward or backward.
  18074. * @param {number} flipBack
  18075. * @param {number} twirlClockwise
  18076. * @param {number} tiltRight
  18077. *
  18078. * Returns the AbstractMesh.
  18079. */
  18080. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18081. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18082. return this;
  18083. };
  18084. /**
  18085. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18086. * Supports definition of mesh facing forward or backward.
  18087. * @param {number} flipBack
  18088. * @param {number} twirlClockwise
  18089. * @param {number} tiltRight
  18090. *
  18091. * Returns a new Vector3.
  18092. */
  18093. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18094. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18095. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18096. };
  18097. /**
  18098. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18099. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18100. */
  18101. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18102. if (includeDescendants === void 0) { includeDescendants = true; }
  18103. this.computeWorldMatrix(true);
  18104. var min;
  18105. var max;
  18106. var boundingInfo = this.getBoundingInfo();
  18107. if (!this.subMeshes) {
  18108. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18109. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18110. }
  18111. else {
  18112. min = boundingInfo.boundingBox.minimumWorld;
  18113. max = boundingInfo.boundingBox.maximumWorld;
  18114. }
  18115. if (includeDescendants) {
  18116. var descendants = this.getDescendants(false);
  18117. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18118. var descendant = descendants_1[_i];
  18119. var childMesh = descendant;
  18120. childMesh.computeWorldMatrix(true);
  18121. //make sure we have the needed params to get mix and max
  18122. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18123. continue;
  18124. }
  18125. var childBoundingInfo = childMesh.getBoundingInfo();
  18126. var boundingBox = childBoundingInfo.boundingBox;
  18127. var minBox = boundingBox.minimumWorld;
  18128. var maxBox = boundingBox.maximumWorld;
  18129. BABYLON.Tools.CheckExtends(minBox, min, max);
  18130. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18131. }
  18132. }
  18133. return {
  18134. min: min,
  18135. max: max
  18136. };
  18137. };
  18138. /**
  18139. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18140. * Returns the AbstractMesh.
  18141. */
  18142. AbstractMesh.prototype._updateBoundingInfo = function () {
  18143. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18144. this._boundingInfo.update(this.worldMatrixFromCache);
  18145. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18146. return this;
  18147. };
  18148. /**
  18149. * Update a mesh's children BoundingInfo objects only.
  18150. * Returns the AbstractMesh.
  18151. */
  18152. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18153. if (!this.subMeshes) {
  18154. return this;
  18155. }
  18156. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18157. var subMesh = this.subMeshes[subIndex];
  18158. if (!subMesh.IsGlobal) {
  18159. subMesh.updateBoundingInfo(matrix);
  18160. }
  18161. }
  18162. return this;
  18163. };
  18164. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18165. // Bounding info
  18166. this._updateBoundingInfo();
  18167. };
  18168. /**
  18169. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18170. * A mesh is in the frustum if its bounding box intersects the frustum.
  18171. * Boolean returned.
  18172. */
  18173. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18174. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18175. };
  18176. /**
  18177. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18178. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18179. * Boolean returned.
  18180. */
  18181. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18182. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18183. ;
  18184. };
  18185. /**
  18186. * True if the mesh intersects another mesh or a SolidParticle object.
  18187. * 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)
  18188. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18189. * Returns a boolean.
  18190. */
  18191. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18192. if (precise === void 0) { precise = false; }
  18193. if (!this._boundingInfo || !mesh._boundingInfo) {
  18194. return false;
  18195. }
  18196. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18197. return true;
  18198. }
  18199. if (includeDescendants) {
  18200. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18201. var child = _a[_i];
  18202. if (child.intersectsMesh(mesh, precise, true)) {
  18203. return true;
  18204. }
  18205. }
  18206. }
  18207. return false;
  18208. };
  18209. /**
  18210. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18211. * Returns a boolean.
  18212. */
  18213. AbstractMesh.prototype.intersectsPoint = function (point) {
  18214. if (!this._boundingInfo) {
  18215. return false;
  18216. }
  18217. return this._boundingInfo.intersectsPoint(point);
  18218. };
  18219. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18220. return this.physicsImpostor;
  18221. };
  18222. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18223. if (camera === void 0) { camera = null; }
  18224. if (!camera) {
  18225. camera = this.getScene().activeCamera;
  18226. }
  18227. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18228. };
  18229. /**
  18230. * Returns the distance from the mesh to the active camera.
  18231. * Returns a float.
  18232. */
  18233. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18234. if (camera === void 0) { camera = null; }
  18235. if (!camera) {
  18236. camera = this.getScene().activeCamera;
  18237. }
  18238. return this.absolutePosition.subtract(camera.position).length();
  18239. };
  18240. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18241. if (!this.physicsImpostor) {
  18242. return this;
  18243. }
  18244. this.physicsImpostor.applyImpulse(force, contactPoint);
  18245. return this;
  18246. };
  18247. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18248. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18249. return this;
  18250. }
  18251. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18252. mainPivot: pivot1,
  18253. connectedPivot: pivot2,
  18254. nativeParams: options
  18255. });
  18256. return this;
  18257. };
  18258. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18259. // Collisions
  18260. /**
  18261. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18262. * Default `false`.
  18263. */
  18264. get: function () {
  18265. return this._checkCollisions;
  18266. },
  18267. set: function (collisionEnabled) {
  18268. this._checkCollisions = collisionEnabled;
  18269. if (this.getScene().workerCollisions) {
  18270. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18271. }
  18272. },
  18273. enumerable: true,
  18274. configurable: true
  18275. });
  18276. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18277. /**
  18278. * Gets Collider object used to compute collisions (not physics)
  18279. */
  18280. get: function () {
  18281. return this._collider;
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18287. var globalPosition = this.getAbsolutePosition();
  18288. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18289. if (!this._collider) {
  18290. this._collider = new BABYLON.Collider();
  18291. }
  18292. this._collider._radius = this.ellipsoid;
  18293. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18294. return this;
  18295. };
  18296. // Submeshes octree
  18297. /**
  18298. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18299. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18300. * Returns an Octree of submeshes.
  18301. */
  18302. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18303. if (maxCapacity === void 0) { maxCapacity = 64; }
  18304. if (maxDepth === void 0) { maxDepth = 2; }
  18305. if (!this._submeshesOctree) {
  18306. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18307. }
  18308. this.computeWorldMatrix(true);
  18309. var boundingInfo = this.getBoundingInfo();
  18310. // Update octree
  18311. var bbox = boundingInfo.boundingBox;
  18312. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18313. return this._submeshesOctree;
  18314. };
  18315. // Collisions
  18316. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18317. this._generatePointsArray();
  18318. if (!this._positions) {
  18319. return this;
  18320. }
  18321. // Transformation
  18322. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18323. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18324. subMesh._lastColliderWorldVertices = [];
  18325. subMesh._trianglePlanes = [];
  18326. var start = subMesh.verticesStart;
  18327. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18328. for (var i = start; i < end; i++) {
  18329. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18330. }
  18331. }
  18332. // Collide
  18333. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18334. if (collider.collisionFound) {
  18335. collider.collidedMesh = this;
  18336. }
  18337. return this;
  18338. };
  18339. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18340. var subMeshes;
  18341. var len;
  18342. // Octrees
  18343. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18344. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18345. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18346. len = intersections.length;
  18347. subMeshes = intersections.data;
  18348. }
  18349. else {
  18350. subMeshes = this.subMeshes;
  18351. len = subMeshes.length;
  18352. }
  18353. for (var index = 0; index < len; index++) {
  18354. var subMesh = subMeshes[index];
  18355. // Bounding test
  18356. if (len > 1 && !subMesh._checkCollision(collider))
  18357. continue;
  18358. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18359. }
  18360. return this;
  18361. };
  18362. AbstractMesh.prototype._checkCollision = function (collider) {
  18363. // Bounding box test
  18364. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18365. return this;
  18366. // Transformation matrix
  18367. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18368. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18369. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18370. return this;
  18371. };
  18372. // Picking
  18373. AbstractMesh.prototype._generatePointsArray = function () {
  18374. return false;
  18375. };
  18376. /**
  18377. * Checks if the passed Ray intersects with the mesh.
  18378. * Returns an object PickingInfo.
  18379. */
  18380. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18381. var pickingInfo = new BABYLON.PickingInfo();
  18382. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18383. return pickingInfo;
  18384. }
  18385. if (!this._generatePointsArray()) {
  18386. return pickingInfo;
  18387. }
  18388. var intersectInfo = null;
  18389. // Octrees
  18390. var subMeshes;
  18391. var len;
  18392. if (this._submeshesOctree && this.useOctreeForPicking) {
  18393. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18394. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18395. len = intersections.length;
  18396. subMeshes = intersections.data;
  18397. }
  18398. else {
  18399. subMeshes = this.subMeshes;
  18400. len = subMeshes.length;
  18401. }
  18402. for (var index = 0; index < len; index++) {
  18403. var subMesh = subMeshes[index];
  18404. // Bounding test
  18405. if (len > 1 && !subMesh.canIntersects(ray))
  18406. continue;
  18407. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18408. if (currentIntersectInfo) {
  18409. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18410. intersectInfo = currentIntersectInfo;
  18411. intersectInfo.subMeshId = index;
  18412. if (fastCheck) {
  18413. break;
  18414. }
  18415. }
  18416. }
  18417. }
  18418. if (intersectInfo) {
  18419. // Get picked point
  18420. var world = this.getWorldMatrix();
  18421. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18422. var direction = ray.direction.clone();
  18423. direction = direction.scale(intersectInfo.distance);
  18424. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18425. var pickedPoint = worldOrigin.add(worldDirection);
  18426. // Return result
  18427. pickingInfo.hit = true;
  18428. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18429. pickingInfo.pickedPoint = pickedPoint;
  18430. pickingInfo.pickedMesh = this;
  18431. pickingInfo.bu = intersectInfo.bu || 0;
  18432. pickingInfo.bv = intersectInfo.bv || 0;
  18433. pickingInfo.faceId = intersectInfo.faceId;
  18434. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18435. return pickingInfo;
  18436. }
  18437. return pickingInfo;
  18438. };
  18439. /**
  18440. * Clones the mesh, used by the class Mesh.
  18441. * Just returns `null` for an AbstractMesh.
  18442. */
  18443. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18444. return null;
  18445. };
  18446. /**
  18447. * Disposes all the mesh submeshes.
  18448. * Returns the AbstractMesh.
  18449. */
  18450. AbstractMesh.prototype.releaseSubMeshes = function () {
  18451. if (this.subMeshes) {
  18452. while (this.subMeshes.length) {
  18453. this.subMeshes[0].dispose();
  18454. }
  18455. }
  18456. else {
  18457. this.subMeshes = new Array();
  18458. }
  18459. return this;
  18460. };
  18461. /**
  18462. * Releases resources associated with this abstract mesh.
  18463. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18464. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18465. */
  18466. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18467. var _this = this;
  18468. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18469. var index;
  18470. // Smart Array Retainers.
  18471. this.getScene().freeActiveMeshes();
  18472. this.getScene().freeRenderingGroups();
  18473. // Action manager
  18474. if (this.actionManager !== undefined && this.actionManager !== null) {
  18475. this.actionManager.dispose();
  18476. this.actionManager = null;
  18477. }
  18478. // Skeleton
  18479. this.skeleton = null;
  18480. // Physics
  18481. if (this.physicsImpostor) {
  18482. this.physicsImpostor.dispose();
  18483. }
  18484. // Intersections in progress
  18485. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18486. var other = this._intersectionsInProgress[index];
  18487. var pos = other._intersectionsInProgress.indexOf(this);
  18488. other._intersectionsInProgress.splice(pos, 1);
  18489. }
  18490. this._intersectionsInProgress = [];
  18491. // Lights
  18492. var lights = this.getScene().lights;
  18493. lights.forEach(function (light) {
  18494. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18495. if (meshIndex !== -1) {
  18496. light.includedOnlyMeshes.splice(meshIndex, 1);
  18497. }
  18498. meshIndex = light.excludedMeshes.indexOf(_this);
  18499. if (meshIndex !== -1) {
  18500. light.excludedMeshes.splice(meshIndex, 1);
  18501. }
  18502. // Shadow generators
  18503. var generator = light.getShadowGenerator();
  18504. if (generator) {
  18505. var shadowMap = generator.getShadowMap();
  18506. if (shadowMap && shadowMap.renderList) {
  18507. meshIndex = shadowMap.renderList.indexOf(_this);
  18508. if (meshIndex !== -1) {
  18509. shadowMap.renderList.splice(meshIndex, 1);
  18510. }
  18511. }
  18512. }
  18513. });
  18514. // Edges
  18515. if (this._edgesRenderer) {
  18516. this._edgesRenderer.dispose();
  18517. this._edgesRenderer = null;
  18518. }
  18519. // SubMeshes
  18520. if (this.getClassName() !== "InstancedMesh") {
  18521. this.releaseSubMeshes();
  18522. }
  18523. // Octree
  18524. var sceneOctree = this.getScene().selectionOctree;
  18525. if (sceneOctree !== undefined && sceneOctree !== null) {
  18526. var index = sceneOctree.dynamicContent.indexOf(this);
  18527. if (index !== -1) {
  18528. sceneOctree.dynamicContent.splice(index, 1);
  18529. }
  18530. }
  18531. // Query
  18532. var engine = this.getScene().getEngine();
  18533. if (this._occlusionQuery) {
  18534. this._isOcclusionQueryInProgress = false;
  18535. engine.deleteQuery(this._occlusionQuery);
  18536. this._occlusionQuery = null;
  18537. }
  18538. // Engine
  18539. engine.wipeCaches();
  18540. // Remove from scene
  18541. this.getScene().removeMesh(this);
  18542. if (disposeMaterialAndTextures) {
  18543. if (this.material) {
  18544. this.material.dispose(false, true);
  18545. }
  18546. }
  18547. if (!doNotRecurse) {
  18548. // Particles
  18549. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18550. if (this.getScene().particleSystems[index].emitter === this) {
  18551. this.getScene().particleSystems[index].dispose();
  18552. index--;
  18553. }
  18554. }
  18555. }
  18556. // facet data
  18557. if (this._facetDataEnabled) {
  18558. this.disableFacetData();
  18559. }
  18560. this.onAfterWorldMatrixUpdateObservable.clear();
  18561. this.onCollideObservable.clear();
  18562. this.onCollisionPositionChangeObservable.clear();
  18563. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18564. };
  18565. /**
  18566. * Adds the passed mesh as a child to the current mesh.
  18567. * Returns the AbstractMesh.
  18568. */
  18569. AbstractMesh.prototype.addChild = function (mesh) {
  18570. mesh.setParent(this);
  18571. return this;
  18572. };
  18573. /**
  18574. * Removes the passed mesh from the current mesh children list.
  18575. * Returns the AbstractMesh.
  18576. */
  18577. AbstractMesh.prototype.removeChild = function (mesh) {
  18578. mesh.setParent(null);
  18579. return this;
  18580. };
  18581. // Facet data
  18582. /**
  18583. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18584. * Returns the AbstractMesh.
  18585. */
  18586. AbstractMesh.prototype._initFacetData = function () {
  18587. if (!this._facetNormals) {
  18588. this._facetNormals = new Array();
  18589. }
  18590. if (!this._facetPositions) {
  18591. this._facetPositions = new Array();
  18592. }
  18593. if (!this._facetPartitioning) {
  18594. this._facetPartitioning = new Array();
  18595. }
  18596. this._facetNb = (this.getIndices().length / 3) | 0;
  18597. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18598. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18599. for (var f = 0; f < this._facetNb; f++) {
  18600. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18601. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18602. }
  18603. this._facetDataEnabled = true;
  18604. return this;
  18605. };
  18606. /**
  18607. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18608. * This method can be called within the render loop.
  18609. * 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.
  18610. * Returns the AbstractMesh.
  18611. */
  18612. AbstractMesh.prototype.updateFacetData = function () {
  18613. if (!this._facetDataEnabled) {
  18614. this._initFacetData();
  18615. }
  18616. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18617. var indices = this.getIndices();
  18618. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18619. var bInfo = this.getBoundingInfo();
  18620. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18621. // init arrays, matrix and sort function on first call
  18622. this._facetDepthSortEnabled = true;
  18623. if (indices instanceof Uint16Array) {
  18624. this._depthSortedIndices = new Uint16Array(indices);
  18625. }
  18626. else if (indices instanceof Uint32Array) {
  18627. this._depthSortedIndices = new Uint32Array(indices);
  18628. }
  18629. else {
  18630. var needs32bits = false;
  18631. for (var i = 0; i < indices.length; i++) {
  18632. if (indices[i] > 65535) {
  18633. needs32bits = true;
  18634. break;
  18635. }
  18636. }
  18637. if (needs32bits) {
  18638. this._depthSortedIndices = new Uint32Array(indices);
  18639. }
  18640. else {
  18641. this._depthSortedIndices = new Uint16Array(indices);
  18642. }
  18643. }
  18644. this._facetDepthSortFunction = function (f1, f2) {
  18645. return (f2.sqDistance - f1.sqDistance);
  18646. };
  18647. if (!this._facetDepthSortFrom) {
  18648. var camera = this.getScene().activeCamera;
  18649. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18650. }
  18651. this._depthSortedFacets = [];
  18652. for (var f = 0; f < this._facetNb; f++) {
  18653. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18654. this._depthSortedFacets.push(depthSortedFacet);
  18655. }
  18656. this._invertedMatrix = BABYLON.Matrix.Identity();
  18657. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18658. }
  18659. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18660. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18661. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18662. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18663. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18664. this._subDiv.max = this._partitioningSubdivisions;
  18665. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18666. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18667. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18668. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18669. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18670. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18671. // set the parameters for ComputeNormals()
  18672. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18673. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18674. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18675. this._facetParameters.bInfo = bInfo;
  18676. this._facetParameters.bbSize = this._bbSize;
  18677. this._facetParameters.subDiv = this._subDiv;
  18678. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18679. this._facetParameters.depthSort = this._facetDepthSort;
  18680. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18681. this.computeWorldMatrix(true);
  18682. this._worldMatrix.invertToRef(this._invertedMatrix);
  18683. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18684. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18685. }
  18686. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18687. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18688. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18689. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18690. var l = (this._depthSortedIndices.length / 3) | 0;
  18691. for (var f = 0; f < l; f++) {
  18692. var sind = this._depthSortedFacets[f].ind;
  18693. this._depthSortedIndices[f * 3] = indices[sind];
  18694. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18695. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18696. }
  18697. this.updateIndices(this._depthSortedIndices);
  18698. }
  18699. return this;
  18700. };
  18701. /**
  18702. * Returns the facetLocalNormals array.
  18703. * The normals are expressed in the mesh local space.
  18704. */
  18705. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18706. if (!this._facetNormals) {
  18707. this.updateFacetData();
  18708. }
  18709. return this._facetNormals;
  18710. };
  18711. /**
  18712. * Returns the facetLocalPositions array.
  18713. * The facet positions are expressed in the mesh local space.
  18714. */
  18715. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18716. if (!this._facetPositions) {
  18717. this.updateFacetData();
  18718. }
  18719. return this._facetPositions;
  18720. };
  18721. /**
  18722. * Returns the facetLocalPartioning array.
  18723. */
  18724. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18725. if (!this._facetPartitioning) {
  18726. this.updateFacetData();
  18727. }
  18728. return this._facetPartitioning;
  18729. };
  18730. /**
  18731. * Returns the i-th facet position in the world system.
  18732. * This method allocates a new Vector3 per call.
  18733. */
  18734. AbstractMesh.prototype.getFacetPosition = function (i) {
  18735. var pos = BABYLON.Vector3.Zero();
  18736. this.getFacetPositionToRef(i, pos);
  18737. return pos;
  18738. };
  18739. /**
  18740. * Sets the reference Vector3 with the i-th facet position in the world system.
  18741. * Returns the AbstractMesh.
  18742. */
  18743. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18744. var localPos = (this.getFacetLocalPositions())[i];
  18745. var world = this.getWorldMatrix();
  18746. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18747. return this;
  18748. };
  18749. /**
  18750. * Returns the i-th facet normal in the world system.
  18751. * This method allocates a new Vector3 per call.
  18752. */
  18753. AbstractMesh.prototype.getFacetNormal = function (i) {
  18754. var norm = BABYLON.Vector3.Zero();
  18755. this.getFacetNormalToRef(i, norm);
  18756. return norm;
  18757. };
  18758. /**
  18759. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18760. * Returns the AbstractMesh.
  18761. */
  18762. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18763. var localNorm = (this.getFacetLocalNormals())[i];
  18764. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18765. return this;
  18766. };
  18767. /**
  18768. * 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).
  18769. */
  18770. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18771. var bInfo = this.getBoundingInfo();
  18772. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18773. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18774. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18775. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18776. return null;
  18777. }
  18778. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18779. };
  18780. /**
  18781. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18782. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18783. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18784. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18785. * 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.
  18786. */
  18787. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18788. if (checkFace === void 0) { checkFace = false; }
  18789. if (facing === void 0) { facing = true; }
  18790. var world = this.getWorldMatrix();
  18791. var invMat = BABYLON.Tmp.Matrix[5];
  18792. world.invertToRef(invMat);
  18793. var invVect = BABYLON.Tmp.Vector3[8];
  18794. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18795. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18796. if (projected) {
  18797. // tranform the local computed projected vector to world coordinates
  18798. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18799. }
  18800. return closest;
  18801. };
  18802. /**
  18803. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18804. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18805. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18806. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18807. * 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.
  18808. */
  18809. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18810. if (checkFace === void 0) { checkFace = false; }
  18811. if (facing === void 0) { facing = true; }
  18812. var closest = null;
  18813. var tmpx = 0.0;
  18814. var tmpy = 0.0;
  18815. var tmpz = 0.0;
  18816. var d = 0.0; // tmp dot facet normal * facet position
  18817. var t0 = 0.0;
  18818. var projx = 0.0;
  18819. var projy = 0.0;
  18820. var projz = 0.0;
  18821. // Get all the facets in the same partitioning block than (x, y, z)
  18822. var facetPositions = this.getFacetLocalPositions();
  18823. var facetNormals = this.getFacetLocalNormals();
  18824. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18825. if (!facetsInBlock) {
  18826. return null;
  18827. }
  18828. // Get the closest facet to (x, y, z)
  18829. var shortest = Number.MAX_VALUE; // init distance vars
  18830. var tmpDistance = shortest;
  18831. var fib; // current facet in the block
  18832. var norm; // current facet normal
  18833. var p0; // current facet barycenter position
  18834. // loop on all the facets in the current partitioning block
  18835. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18836. fib = facetsInBlock[idx];
  18837. norm = facetNormals[fib];
  18838. p0 = facetPositions[fib];
  18839. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18840. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18841. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18842. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18843. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18844. projx = x + norm.x * t0;
  18845. projy = y + norm.y * t0;
  18846. projz = z + norm.z * t0;
  18847. tmpx = projx - x;
  18848. tmpy = projy - y;
  18849. tmpz = projz - z;
  18850. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18851. if (tmpDistance < shortest) {
  18852. shortest = tmpDistance;
  18853. closest = fib;
  18854. if (projected) {
  18855. projected.x = projx;
  18856. projected.y = projy;
  18857. projected.z = projz;
  18858. }
  18859. }
  18860. }
  18861. }
  18862. return closest;
  18863. };
  18864. /**
  18865. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18866. */
  18867. AbstractMesh.prototype.getFacetDataParameters = function () {
  18868. return this._facetParameters;
  18869. };
  18870. /**
  18871. * Disables the feature FacetData and frees the related memory.
  18872. * Returns the AbstractMesh.
  18873. */
  18874. AbstractMesh.prototype.disableFacetData = function () {
  18875. if (this._facetDataEnabled) {
  18876. this._facetDataEnabled = false;
  18877. this._facetPositions = new Array();
  18878. this._facetNormals = new Array();
  18879. this._facetPartitioning = new Array();
  18880. this._facetParameters = null;
  18881. this._depthSortedIndices = new Uint32Array(0);
  18882. }
  18883. return this;
  18884. };
  18885. /**
  18886. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18887. * Returns the mesh.
  18888. */
  18889. AbstractMesh.prototype.updateIndices = function (indices) {
  18890. return this;
  18891. };
  18892. /**
  18893. * The mesh Geometry. Actually used by the Mesh object.
  18894. * Returns a blank geometry object.
  18895. */
  18896. /**
  18897. * Creates new normals data for the mesh.
  18898. * @param updatable.
  18899. */
  18900. AbstractMesh.prototype.createNormals = function (updatable) {
  18901. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18902. var indices = this.getIndices();
  18903. var normals;
  18904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18905. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18906. }
  18907. else {
  18908. normals = [];
  18909. }
  18910. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18911. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18912. };
  18913. /**
  18914. * Align the mesh with a normal.
  18915. * Returns the mesh.
  18916. */
  18917. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18918. if (!upDirection) {
  18919. upDirection = BABYLON.Axis.Y;
  18920. }
  18921. var axisX = BABYLON.Tmp.Vector3[0];
  18922. var axisZ = BABYLON.Tmp.Vector3[1];
  18923. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18924. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18925. if (this.rotationQuaternion) {
  18926. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18927. }
  18928. else {
  18929. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18930. }
  18931. return this;
  18932. };
  18933. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18934. var engine = this.getEngine();
  18935. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18936. this._isOccluded = false;
  18937. return;
  18938. }
  18939. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18940. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18941. if (isOcclusionQueryAvailable) {
  18942. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18943. this._isOcclusionQueryInProgress = false;
  18944. this._occlusionInternalRetryCounter = 0;
  18945. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18946. }
  18947. else {
  18948. this._occlusionInternalRetryCounter++;
  18949. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18950. this._isOcclusionQueryInProgress = false;
  18951. this._occlusionInternalRetryCounter = 0;
  18952. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18953. // if strict continue the last state of the object.
  18954. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18955. }
  18956. else {
  18957. return;
  18958. }
  18959. }
  18960. }
  18961. var scene = this.getScene();
  18962. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18963. if (!this._occlusionQuery) {
  18964. this._occlusionQuery = engine.createQuery();
  18965. }
  18966. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18967. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18968. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18969. this._isOcclusionQueryInProgress = true;
  18970. };
  18971. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18972. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18973. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18974. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18975. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18976. return AbstractMesh;
  18977. }(BABYLON.TransformNode));
  18978. BABYLON.AbstractMesh = AbstractMesh;
  18979. })(BABYLON || (BABYLON = {}));
  18980. //# sourceMappingURL=babylon.abstractMesh.js.map
  18981. var BABYLON;
  18982. (function (BABYLON) {
  18983. /**
  18984. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18985. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18986. * 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.
  18987. */
  18988. var Light = /** @class */ (function (_super) {
  18989. __extends(Light, _super);
  18990. /**
  18991. * Creates a Light object in the scene.
  18992. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18993. * @param name The firendly name of the light
  18994. * @param scene The scene the light belongs too
  18995. */
  18996. function Light(name, scene) {
  18997. var _this = _super.call(this, name, scene) || this;
  18998. /**
  18999. * Diffuse gives the basic color to an object.
  19000. */
  19001. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19002. /**
  19003. * Specular produces a highlight color on an object.
  19004. * Note: This is note affecting PBR materials.
  19005. */
  19006. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19007. /**
  19008. * Strength of the light.
  19009. * Note: By default it is define in the framework own unit.
  19010. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19011. */
  19012. _this.intensity = 1.0;
  19013. /**
  19014. * Defines how far from the source the light is impacting in scene units.
  19015. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19016. */
  19017. _this.range = Number.MAX_VALUE;
  19018. /**
  19019. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19020. * of light.
  19021. */
  19022. _this._photometricScale = 1.0;
  19023. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19024. _this._radius = 0.00001;
  19025. /**
  19026. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19027. * exceeding the number allowed of the materials.
  19028. */
  19029. _this.renderPriority = 0;
  19030. /**
  19031. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19032. * the current shadow generator.
  19033. */
  19034. _this.shadowEnabled = true;
  19035. _this._excludeWithLayerMask = 0;
  19036. _this._includeOnlyWithLayerMask = 0;
  19037. _this._lightmapMode = 0;
  19038. /**
  19039. * @ignore Internal use only.
  19040. */
  19041. _this._excludedMeshesIds = new Array();
  19042. /**
  19043. * @ignore Internal use only.
  19044. */
  19045. _this._includedOnlyMeshesIds = new Array();
  19046. _this.getScene().addLight(_this);
  19047. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19048. _this._buildUniformLayout();
  19049. _this.includedOnlyMeshes = new Array();
  19050. _this.excludedMeshes = new Array();
  19051. _this._resyncMeshes();
  19052. return _this;
  19053. }
  19054. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19055. /**
  19056. * If every light affecting the material is in this lightmapMode,
  19057. * material.lightmapTexture adds or multiplies
  19058. * (depends on material.useLightmapAsShadowmap)
  19059. * after every other light calculations.
  19060. */
  19061. get: function () {
  19062. return Light._LIGHTMAP_DEFAULT;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19068. /**
  19069. * material.lightmapTexture as only diffuse lighting from this light
  19070. * adds only specular lighting from this light
  19071. * adds dynamic shadows
  19072. */
  19073. get: function () {
  19074. return Light._LIGHTMAP_SPECULAR;
  19075. },
  19076. enumerable: true,
  19077. configurable: true
  19078. });
  19079. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19080. /**
  19081. * material.lightmapTexture as only lighting
  19082. * no light calculation from this light
  19083. * only adds dynamic shadows from this light
  19084. */
  19085. get: function () {
  19086. return Light._LIGHTMAP_SHADOWSONLY;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19092. /**
  19093. * Each light type uses the default quantity according to its type:
  19094. * point/spot lights use luminous intensity
  19095. * directional lights use illuminance
  19096. */
  19097. get: function () {
  19098. return Light._INTENSITYMODE_AUTOMATIC;
  19099. },
  19100. enumerable: true,
  19101. configurable: true
  19102. });
  19103. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19104. /**
  19105. * lumen (lm)
  19106. */
  19107. get: function () {
  19108. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19114. /**
  19115. * candela (lm/sr)
  19116. */
  19117. get: function () {
  19118. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19124. /**
  19125. * lux (lm/m^2)
  19126. */
  19127. get: function () {
  19128. return Light._INTENSITYMODE_ILLUMINANCE;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19134. /**
  19135. * nit (cd/m^2)
  19136. */
  19137. get: function () {
  19138. return Light._INTENSITYMODE_LUMINANCE;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19144. /**
  19145. * Light type const id of the point light.
  19146. */
  19147. get: function () {
  19148. return Light._LIGHTTYPEID_POINTLIGHT;
  19149. },
  19150. enumerable: true,
  19151. configurable: true
  19152. });
  19153. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19154. /**
  19155. * Light type const id of the directional light.
  19156. */
  19157. get: function () {
  19158. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19159. },
  19160. enumerable: true,
  19161. configurable: true
  19162. });
  19163. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19164. /**
  19165. * Light type const id of the spot light.
  19166. */
  19167. get: function () {
  19168. return Light._LIGHTTYPEID_SPOTLIGHT;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19174. /**
  19175. * Light type const id of the hemispheric light.
  19176. */
  19177. get: function () {
  19178. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19179. },
  19180. enumerable: true,
  19181. configurable: true
  19182. });
  19183. Object.defineProperty(Light.prototype, "intensityMode", {
  19184. /**
  19185. * Gets the photometric scale used to interpret the intensity.
  19186. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19187. */
  19188. get: function () {
  19189. return this._intensityMode;
  19190. },
  19191. /**
  19192. * Sets the photometric scale used to interpret the intensity.
  19193. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19194. */
  19195. set: function (value) {
  19196. this._intensityMode = value;
  19197. this._computePhotometricScale();
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. ;
  19203. ;
  19204. Object.defineProperty(Light.prototype, "radius", {
  19205. /**
  19206. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19207. */
  19208. get: function () {
  19209. return this._radius;
  19210. },
  19211. /**
  19212. * sets the light radius used by PBR Materials to simulate soft area lights.
  19213. */
  19214. set: function (value) {
  19215. this._radius = value;
  19216. this._computePhotometricScale();
  19217. },
  19218. enumerable: true,
  19219. configurable: true
  19220. });
  19221. ;
  19222. ;
  19223. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19224. /**
  19225. * Gets the only meshes impacted by this light.
  19226. */
  19227. get: function () {
  19228. return this._includedOnlyMeshes;
  19229. },
  19230. /**
  19231. * Sets the only meshes impacted by this light.
  19232. */
  19233. set: function (value) {
  19234. this._includedOnlyMeshes = value;
  19235. this._hookArrayForIncludedOnly(value);
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19241. /**
  19242. * Gets the meshes not impacted by this light.
  19243. */
  19244. get: function () {
  19245. return this._excludedMeshes;
  19246. },
  19247. /**
  19248. * Sets the meshes not impacted by this light.
  19249. */
  19250. set: function (value) {
  19251. this._excludedMeshes = value;
  19252. this._hookArrayForExcluded(value);
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19258. /**
  19259. * Gets the layer id use to find what meshes are not impacted by the light.
  19260. * Inactive if 0
  19261. */
  19262. get: function () {
  19263. return this._excludeWithLayerMask;
  19264. },
  19265. /**
  19266. * Sets the layer id use to find what meshes are not impacted by the light.
  19267. * Inactive if 0
  19268. */
  19269. set: function (value) {
  19270. this._excludeWithLayerMask = value;
  19271. this._resyncMeshes();
  19272. },
  19273. enumerable: true,
  19274. configurable: true
  19275. });
  19276. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19277. /**
  19278. * Gets the layer id use to find what meshes are impacted by the light.
  19279. * Inactive if 0
  19280. */
  19281. get: function () {
  19282. return this._includeOnlyWithLayerMask;
  19283. },
  19284. /**
  19285. * Sets the layer id use to find what meshes are impacted by the light.
  19286. * Inactive if 0
  19287. */
  19288. set: function (value) {
  19289. this._includeOnlyWithLayerMask = value;
  19290. this._resyncMeshes();
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. Object.defineProperty(Light.prototype, "lightmapMode", {
  19296. /**
  19297. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19298. */
  19299. get: function () {
  19300. return this._lightmapMode;
  19301. },
  19302. /**
  19303. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19304. */
  19305. set: function (value) {
  19306. if (this._lightmapMode === value) {
  19307. return;
  19308. }
  19309. this._lightmapMode = value;
  19310. this._markMeshesAsLightDirty();
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. /**
  19316. * Returns the string "Light".
  19317. * @returns the class name
  19318. */
  19319. Light.prototype.getClassName = function () {
  19320. return "Light";
  19321. };
  19322. /**
  19323. * Converts the light information to a readable string for debug purpose.
  19324. * @param fullDetails Supports for multiple levels of logging within scene loading
  19325. * @returns the human readable light info
  19326. */
  19327. Light.prototype.toString = function (fullDetails) {
  19328. var ret = "Name: " + this.name;
  19329. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19330. if (this.animations) {
  19331. for (var i = 0; i < this.animations.length; i++) {
  19332. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19333. }
  19334. }
  19335. if (fullDetails) {
  19336. }
  19337. return ret;
  19338. };
  19339. /**
  19340. * Set the enabled state of this node.
  19341. * @param value - the new enabled state
  19342. * @see isEnabled
  19343. */
  19344. Light.prototype.setEnabled = function (value) {
  19345. _super.prototype.setEnabled.call(this, value);
  19346. this._resyncMeshes();
  19347. };
  19348. /**
  19349. * Returns the Light associated shadow generator if any.
  19350. * @return the associated shadow generator.
  19351. */
  19352. Light.prototype.getShadowGenerator = function () {
  19353. return this._shadowGenerator;
  19354. };
  19355. /**
  19356. * Returns a Vector3, the absolute light position in the World.
  19357. * @returns the world space position of the light
  19358. */
  19359. Light.prototype.getAbsolutePosition = function () {
  19360. return BABYLON.Vector3.Zero();
  19361. };
  19362. /**
  19363. * Specifies if the light will affect the passed mesh.
  19364. * @param mesh The mesh to test against the light
  19365. * @return true the mesh is affected otherwise, false.
  19366. */
  19367. Light.prototype.canAffectMesh = function (mesh) {
  19368. if (!mesh) {
  19369. return true;
  19370. }
  19371. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19372. return false;
  19373. }
  19374. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19375. return false;
  19376. }
  19377. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19378. return false;
  19379. }
  19380. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19381. return false;
  19382. }
  19383. return true;
  19384. };
  19385. /**
  19386. * Computes and Returns the light World matrix.
  19387. * @returns the world matrix
  19388. */
  19389. Light.prototype.getWorldMatrix = function () {
  19390. this._currentRenderId = this.getScene().getRenderId();
  19391. var worldMatrix = this._getWorldMatrix();
  19392. if (this.parent && this.parent.getWorldMatrix) {
  19393. if (!this._parentedWorldMatrix) {
  19394. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19395. }
  19396. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19397. this._markSyncedWithParent();
  19398. return this._parentedWorldMatrix;
  19399. }
  19400. return worldMatrix;
  19401. };
  19402. /**
  19403. * Sort function to order lights for rendering.
  19404. * @param a First Light object to compare to second.
  19405. * @param b Second Light object to compare first.
  19406. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19407. */
  19408. Light.CompareLightsPriority = function (a, b) {
  19409. //shadow-casting lights have priority over non-shadow-casting lights
  19410. //the renderPrioirty is a secondary sort criterion
  19411. if (a.shadowEnabled !== b.shadowEnabled) {
  19412. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19413. }
  19414. return b.renderPriority - a.renderPriority;
  19415. };
  19416. /**
  19417. * Releases resources associated with this node.
  19418. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19419. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19420. */
  19421. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19422. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19423. if (this._shadowGenerator) {
  19424. this._shadowGenerator.dispose();
  19425. this._shadowGenerator = null;
  19426. }
  19427. // Animations
  19428. this.getScene().stopAnimation(this);
  19429. // Remove from meshes
  19430. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19431. var mesh = _a[_i];
  19432. mesh._removeLightSource(this);
  19433. }
  19434. this._uniformBuffer.dispose();
  19435. // Remove from scene
  19436. this.getScene().removeLight(this);
  19437. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19438. };
  19439. /**
  19440. * Returns the light type ID (integer).
  19441. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19442. */
  19443. Light.prototype.getTypeID = function () {
  19444. return 0;
  19445. };
  19446. /**
  19447. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19448. * @returns the scaled intensity in intensity mode unit
  19449. */
  19450. Light.prototype.getScaledIntensity = function () {
  19451. return this._photometricScale * this.intensity;
  19452. };
  19453. /**
  19454. * Returns a new Light object, named "name", from the current one.
  19455. * @param name The name of the cloned light
  19456. * @returns the new created light
  19457. */
  19458. Light.prototype.clone = function (name) {
  19459. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19460. if (!constructor) {
  19461. return null;
  19462. }
  19463. return BABYLON.SerializationHelper.Clone(constructor, this);
  19464. };
  19465. /**
  19466. * Serializes the current light into a Serialization object.
  19467. * @returns the serialized object.
  19468. */
  19469. Light.prototype.serialize = function () {
  19470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19471. // Type
  19472. serializationObject.type = this.getTypeID();
  19473. // Parent
  19474. if (this.parent) {
  19475. serializationObject.parentId = this.parent.id;
  19476. }
  19477. // Inclusion / exclusions
  19478. if (this.excludedMeshes.length > 0) {
  19479. serializationObject.excludedMeshesIds = [];
  19480. this.excludedMeshes.forEach(function (mesh) {
  19481. serializationObject.excludedMeshesIds.push(mesh.id);
  19482. });
  19483. }
  19484. if (this.includedOnlyMeshes.length > 0) {
  19485. serializationObject.includedOnlyMeshesIds = [];
  19486. this.includedOnlyMeshes.forEach(function (mesh) {
  19487. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19488. });
  19489. }
  19490. // Animations
  19491. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19492. serializationObject.ranges = this.serializeAnimationRanges();
  19493. return serializationObject;
  19494. };
  19495. /**
  19496. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19497. * This new light is named "name" and added to the passed scene.
  19498. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19499. * @param name The friendly name of the light
  19500. * @param scene The scene the new light will belong to
  19501. * @returns the constructor function
  19502. */
  19503. Light.GetConstructorFromName = function (type, name, scene) {
  19504. switch (type) {
  19505. case 0:
  19506. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19507. case 1:
  19508. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19509. case 2:
  19510. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19511. case 3:
  19512. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19513. }
  19514. return null;
  19515. };
  19516. /**
  19517. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19518. * @param parsedLight The JSON representation of the light
  19519. * @param scene The scene to create the parsed light in
  19520. * @returns the created light after parsing
  19521. */
  19522. Light.Parse = function (parsedLight, scene) {
  19523. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19524. if (!constructor) {
  19525. return null;
  19526. }
  19527. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19528. // Inclusion / exclusions
  19529. if (parsedLight.excludedMeshesIds) {
  19530. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19531. }
  19532. if (parsedLight.includedOnlyMeshesIds) {
  19533. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19534. }
  19535. // Parent
  19536. if (parsedLight.parentId) {
  19537. light._waitingParentId = parsedLight.parentId;
  19538. }
  19539. // Animations
  19540. if (parsedLight.animations) {
  19541. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19542. var parsedAnimation = parsedLight.animations[animationIndex];
  19543. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19544. }
  19545. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19546. }
  19547. if (parsedLight.autoAnimate) {
  19548. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19549. }
  19550. return light;
  19551. };
  19552. Light.prototype._hookArrayForExcluded = function (array) {
  19553. var _this = this;
  19554. var oldPush = array.push;
  19555. array.push = function () {
  19556. var items = [];
  19557. for (var _i = 0; _i < arguments.length; _i++) {
  19558. items[_i] = arguments[_i];
  19559. }
  19560. var result = oldPush.apply(array, items);
  19561. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19562. var item = items_1[_a];
  19563. item._resyncLighSource(_this);
  19564. }
  19565. return result;
  19566. };
  19567. var oldSplice = array.splice;
  19568. array.splice = function (index, deleteCount) {
  19569. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19570. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19571. var item = deleted_1[_i];
  19572. item._resyncLighSource(_this);
  19573. }
  19574. return deleted;
  19575. };
  19576. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19577. var item = array_1[_i];
  19578. item._resyncLighSource(this);
  19579. }
  19580. };
  19581. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19582. var _this = this;
  19583. var oldPush = array.push;
  19584. array.push = function () {
  19585. var items = [];
  19586. for (var _i = 0; _i < arguments.length; _i++) {
  19587. items[_i] = arguments[_i];
  19588. }
  19589. var result = oldPush.apply(array, items);
  19590. _this._resyncMeshes();
  19591. return result;
  19592. };
  19593. var oldSplice = array.splice;
  19594. array.splice = function (index, deleteCount) {
  19595. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19596. _this._resyncMeshes();
  19597. return deleted;
  19598. };
  19599. this._resyncMeshes();
  19600. };
  19601. Light.prototype._resyncMeshes = function () {
  19602. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19603. var mesh = _a[_i];
  19604. mesh._resyncLighSource(this);
  19605. }
  19606. };
  19607. /**
  19608. * Forces the meshes to update their light related information in their rendering used effects
  19609. * @ignore Internal Use Only
  19610. */
  19611. Light.prototype._markMeshesAsLightDirty = function () {
  19612. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19613. var mesh = _a[_i];
  19614. if (mesh._lightSources.indexOf(this) !== -1) {
  19615. mesh._markSubMeshesAsLightDirty();
  19616. }
  19617. }
  19618. };
  19619. /**
  19620. * Recomputes the cached photometric scale if needed.
  19621. */
  19622. Light.prototype._computePhotometricScale = function () {
  19623. this._photometricScale = this._getPhotometricScale();
  19624. this.getScene().resetCachedMaterial();
  19625. };
  19626. /**
  19627. * Returns the Photometric Scale according to the light type and intensity mode.
  19628. */
  19629. Light.prototype._getPhotometricScale = function () {
  19630. var photometricScale = 0.0;
  19631. var lightTypeID = this.getTypeID();
  19632. //get photometric mode
  19633. var photometricMode = this.intensityMode;
  19634. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19635. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19636. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19637. }
  19638. else {
  19639. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19640. }
  19641. }
  19642. //compute photometric scale
  19643. switch (lightTypeID) {
  19644. case Light.LIGHTTYPEID_POINTLIGHT:
  19645. case Light.LIGHTTYPEID_SPOTLIGHT:
  19646. switch (photometricMode) {
  19647. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19648. photometricScale = 1.0 / (4.0 * Math.PI);
  19649. break;
  19650. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19651. photometricScale = 1.0;
  19652. break;
  19653. case Light.INTENSITYMODE_LUMINANCE:
  19654. photometricScale = this.radius * this.radius;
  19655. break;
  19656. }
  19657. break;
  19658. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19659. switch (photometricMode) {
  19660. case Light.INTENSITYMODE_ILLUMINANCE:
  19661. photometricScale = 1.0;
  19662. break;
  19663. case Light.INTENSITYMODE_LUMINANCE:
  19664. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19665. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19666. var apexAngleRadians = this.radius;
  19667. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19668. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19669. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19670. photometricScale = solidAngle;
  19671. break;
  19672. }
  19673. break;
  19674. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19675. // No fall off in hemisperic light.
  19676. photometricScale = 1.0;
  19677. break;
  19678. }
  19679. return photometricScale;
  19680. };
  19681. /**
  19682. * Reorder the light in the scene according to their defined priority.
  19683. * @ignore Internal Use Only
  19684. */
  19685. Light.prototype._reorderLightsInScene = function () {
  19686. var scene = this.getScene();
  19687. if (this._renderPriority != 0) {
  19688. scene.requireLightSorting = true;
  19689. }
  19690. this.getScene().sortLightsByPriority();
  19691. };
  19692. //lightmapMode Consts
  19693. Light._LIGHTMAP_DEFAULT = 0;
  19694. Light._LIGHTMAP_SPECULAR = 1;
  19695. Light._LIGHTMAP_SHADOWSONLY = 2;
  19696. // Intensity Mode Consts
  19697. Light._INTENSITYMODE_AUTOMATIC = 0;
  19698. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19699. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19700. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19701. Light._INTENSITYMODE_LUMINANCE = 4;
  19702. // Light types ids const.
  19703. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19704. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19705. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19706. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19707. __decorate([
  19708. BABYLON.serializeAsColor3()
  19709. ], Light.prototype, "diffuse", void 0);
  19710. __decorate([
  19711. BABYLON.serializeAsColor3()
  19712. ], Light.prototype, "specular", void 0);
  19713. __decorate([
  19714. BABYLON.serialize()
  19715. ], Light.prototype, "intensity", void 0);
  19716. __decorate([
  19717. BABYLON.serialize()
  19718. ], Light.prototype, "range", void 0);
  19719. __decorate([
  19720. BABYLON.serialize()
  19721. ], Light.prototype, "intensityMode", null);
  19722. __decorate([
  19723. BABYLON.serialize()
  19724. ], Light.prototype, "radius", null);
  19725. __decorate([
  19726. BABYLON.serialize()
  19727. ], Light.prototype, "_renderPriority", void 0);
  19728. __decorate([
  19729. BABYLON.expandToProperty("_reorderLightsInScene")
  19730. ], Light.prototype, "renderPriority", void 0);
  19731. __decorate([
  19732. BABYLON.serialize()
  19733. ], Light.prototype, "shadowEnabled", void 0);
  19734. __decorate([
  19735. BABYLON.serialize("excludeWithLayerMask")
  19736. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19737. __decorate([
  19738. BABYLON.serialize("includeOnlyWithLayerMask")
  19739. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19740. __decorate([
  19741. BABYLON.serialize("lightmapMode")
  19742. ], Light.prototype, "_lightmapMode", void 0);
  19743. return Light;
  19744. }(BABYLON.Node));
  19745. BABYLON.Light = Light;
  19746. })(BABYLON || (BABYLON = {}));
  19747. //# sourceMappingURL=babylon.light.js.map
  19748. var BABYLON;
  19749. (function (BABYLON) {
  19750. var Camera = /** @class */ (function (_super) {
  19751. __extends(Camera, _super);
  19752. function Camera(name, position, scene) {
  19753. var _this = _super.call(this, name, scene) || this;
  19754. /**
  19755. * The vector the camera should consider as up.
  19756. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19757. */
  19758. _this.upVector = BABYLON.Vector3.Up();
  19759. _this.orthoLeft = null;
  19760. _this.orthoRight = null;
  19761. _this.orthoBottom = null;
  19762. _this.orthoTop = null;
  19763. /**
  19764. * FOV is set in Radians. (default is 0.8)
  19765. */
  19766. _this.fov = 0.8;
  19767. _this.minZ = 1;
  19768. _this.maxZ = 10000.0;
  19769. _this.inertia = 0.9;
  19770. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19771. _this.isIntermediate = false;
  19772. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19773. /**
  19774. * Restricts the camera to viewing objects with the same layerMask.
  19775. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19776. */
  19777. _this.layerMask = 0x0FFFFFFF;
  19778. /**
  19779. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19780. */
  19781. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19782. // Camera rig members
  19783. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19784. _this._rigCameras = new Array();
  19785. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19786. _this._skipRendering = false;
  19787. _this.customRenderTargets = new Array();
  19788. // Observables
  19789. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19790. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19791. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19792. _this.onRestoreStateObservable = new BABYLON.Observable();
  19793. // Cache
  19794. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19795. _this._projectionMatrix = new BABYLON.Matrix();
  19796. _this._doNotComputeProjectionMatrix = false;
  19797. _this._postProcesses = new Array();
  19798. _this._transformMatrix = BABYLON.Matrix.Zero();
  19799. _this._activeMeshes = new BABYLON.SmartArray(256);
  19800. _this._globalPosition = BABYLON.Vector3.Zero();
  19801. _this._refreshFrustumPlanes = true;
  19802. _this.getScene().addCamera(_this);
  19803. if (!_this.getScene().activeCamera) {
  19804. _this.getScene().activeCamera = _this;
  19805. }
  19806. _this.position = position;
  19807. return _this;
  19808. }
  19809. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19810. get: function () {
  19811. return Camera._PERSPECTIVE_CAMERA;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19817. get: function () {
  19818. return Camera._ORTHOGRAPHIC_CAMERA;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19824. /**
  19825. * This is the default FOV mode for perspective cameras.
  19826. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19827. *
  19828. */
  19829. get: function () {
  19830. return Camera._FOVMODE_VERTICAL_FIXED;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19836. /**
  19837. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19838. *
  19839. */
  19840. get: function () {
  19841. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19847. get: function () {
  19848. return Camera._RIG_MODE_NONE;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19854. get: function () {
  19855. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19861. get: function () {
  19862. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19868. get: function () {
  19869. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19875. get: function () {
  19876. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19882. get: function () {
  19883. return Camera._RIG_MODE_VR;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19889. get: function () {
  19890. return Camera._RIG_MODE_WEBVR;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. /**
  19896. * Store current camera state (fov, position, etc..)
  19897. */
  19898. Camera.prototype.storeState = function () {
  19899. this._stateStored = true;
  19900. this._storedFov = this.fov;
  19901. return this;
  19902. };
  19903. /**
  19904. * Restores the camera state values if it has been stored. You must call storeState() first
  19905. */
  19906. Camera.prototype._restoreStateValues = function () {
  19907. if (!this._stateStored) {
  19908. return false;
  19909. }
  19910. this.fov = this._storedFov;
  19911. return true;
  19912. };
  19913. /**
  19914. * Restored camera state. You must call storeState() first
  19915. */
  19916. Camera.prototype.restoreState = function () {
  19917. if (this._restoreStateValues()) {
  19918. this.onRestoreStateObservable.notifyObservers(this);
  19919. return true;
  19920. }
  19921. return false;
  19922. };
  19923. Camera.prototype.getClassName = function () {
  19924. return "Camera";
  19925. };
  19926. /**
  19927. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19928. */
  19929. Camera.prototype.toString = function (fullDetails) {
  19930. var ret = "Name: " + this.name;
  19931. ret += ", type: " + this.getClassName();
  19932. if (this.animations) {
  19933. for (var i = 0; i < this.animations.length; i++) {
  19934. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19935. }
  19936. }
  19937. if (fullDetails) {
  19938. }
  19939. return ret;
  19940. };
  19941. Object.defineProperty(Camera.prototype, "globalPosition", {
  19942. get: function () {
  19943. return this._globalPosition;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Camera.prototype.getActiveMeshes = function () {
  19949. return this._activeMeshes;
  19950. };
  19951. Camera.prototype.isActiveMesh = function (mesh) {
  19952. return (this._activeMeshes.indexOf(mesh) !== -1);
  19953. };
  19954. //Cache
  19955. Camera.prototype._initCache = function () {
  19956. _super.prototype._initCache.call(this);
  19957. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19958. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19959. this._cache.mode = undefined;
  19960. this._cache.minZ = undefined;
  19961. this._cache.maxZ = undefined;
  19962. this._cache.fov = undefined;
  19963. this._cache.fovMode = undefined;
  19964. this._cache.aspectRatio = undefined;
  19965. this._cache.orthoLeft = undefined;
  19966. this._cache.orthoRight = undefined;
  19967. this._cache.orthoBottom = undefined;
  19968. this._cache.orthoTop = undefined;
  19969. this._cache.renderWidth = undefined;
  19970. this._cache.renderHeight = undefined;
  19971. };
  19972. Camera.prototype._updateCache = function (ignoreParentClass) {
  19973. if (!ignoreParentClass) {
  19974. _super.prototype._updateCache.call(this);
  19975. }
  19976. this._cache.position.copyFrom(this.position);
  19977. this._cache.upVector.copyFrom(this.upVector);
  19978. };
  19979. // Synchronized
  19980. Camera.prototype._isSynchronized = function () {
  19981. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19982. };
  19983. Camera.prototype._isSynchronizedViewMatrix = function () {
  19984. if (!_super.prototype._isSynchronized.call(this))
  19985. return false;
  19986. return this._cache.position.equals(this.position)
  19987. && this._cache.upVector.equals(this.upVector)
  19988. && this.isSynchronizedWithParent();
  19989. };
  19990. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19991. var check = this._cache.mode === this.mode
  19992. && this._cache.minZ === this.minZ
  19993. && this._cache.maxZ === this.maxZ;
  19994. if (!check) {
  19995. return false;
  19996. }
  19997. var engine = this.getEngine();
  19998. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19999. check = this._cache.fov === this.fov
  20000. && this._cache.fovMode === this.fovMode
  20001. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20002. }
  20003. else {
  20004. check = this._cache.orthoLeft === this.orthoLeft
  20005. && this._cache.orthoRight === this.orthoRight
  20006. && this._cache.orthoBottom === this.orthoBottom
  20007. && this._cache.orthoTop === this.orthoTop
  20008. && this._cache.renderWidth === engine.getRenderWidth()
  20009. && this._cache.renderHeight === engine.getRenderHeight();
  20010. }
  20011. return check;
  20012. };
  20013. // Controls
  20014. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20015. };
  20016. Camera.prototype.detachControl = function (element) {
  20017. };
  20018. Camera.prototype.update = function () {
  20019. this._checkInputs();
  20020. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20021. this._updateRigCameras();
  20022. }
  20023. };
  20024. Camera.prototype._checkInputs = function () {
  20025. this.onAfterCheckInputsObservable.notifyObservers(this);
  20026. };
  20027. Object.defineProperty(Camera.prototype, "rigCameras", {
  20028. get: function () {
  20029. return this._rigCameras;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20035. get: function () {
  20036. return this._rigPostProcess;
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. /**
  20042. * Internal, gets the first post proces.
  20043. * @returns the first post process to be run on this camera.
  20044. */
  20045. Camera.prototype._getFirstPostProcess = function () {
  20046. for (var pp in this._postProcesses) {
  20047. if (this._postProcesses[pp] !== null) {
  20048. return this._postProcesses[pp];
  20049. }
  20050. }
  20051. return null;
  20052. };
  20053. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20054. // invalidate framebuffer
  20055. var firstPostProcess = this._getFirstPostProcess();
  20056. if (firstPostProcess) {
  20057. firstPostProcess.markTextureDirty();
  20058. }
  20059. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20060. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20061. var cam = this._rigCameras[i];
  20062. var rigPostProcess = cam._rigPostProcess;
  20063. // for VR rig, there does not have to be a post process
  20064. if (rigPostProcess) {
  20065. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20066. if (isPass) {
  20067. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20068. cam.isIntermediate = this._postProcesses.length === 0;
  20069. }
  20070. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20071. rigPostProcess.markTextureDirty();
  20072. }
  20073. else {
  20074. cam._postProcesses = this._postProcesses.slice(0);
  20075. }
  20076. }
  20077. };
  20078. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20079. if (insertAt === void 0) { insertAt = null; }
  20080. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20081. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20082. return 0;
  20083. }
  20084. if (insertAt == null || insertAt < 0) {
  20085. this._postProcesses.push(postProcess);
  20086. }
  20087. else if (this._postProcesses[insertAt] === null) {
  20088. this._postProcesses[insertAt] = postProcess;
  20089. }
  20090. else {
  20091. this._postProcesses.splice(insertAt, 0, postProcess);
  20092. }
  20093. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20094. return this._postProcesses.indexOf(postProcess);
  20095. };
  20096. Camera.prototype.detachPostProcess = function (postProcess) {
  20097. var idx = this._postProcesses.indexOf(postProcess);
  20098. if (idx !== -1) {
  20099. this._postProcesses[idx] = null;
  20100. }
  20101. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20102. };
  20103. Camera.prototype.getWorldMatrix = function () {
  20104. if (!this._worldMatrix) {
  20105. this._worldMatrix = BABYLON.Matrix.Identity();
  20106. }
  20107. var viewMatrix = this.getViewMatrix();
  20108. viewMatrix.invertToRef(this._worldMatrix);
  20109. return this._worldMatrix;
  20110. };
  20111. Camera.prototype._getViewMatrix = function () {
  20112. return BABYLON.Matrix.Identity();
  20113. };
  20114. Camera.prototype.getViewMatrix = function (force) {
  20115. if (!force && this._isSynchronizedViewMatrix()) {
  20116. return this._computedViewMatrix;
  20117. }
  20118. this.updateCache();
  20119. this._computedViewMatrix = this._getViewMatrix();
  20120. this._currentRenderId = this.getScene().getRenderId();
  20121. this._refreshFrustumPlanes = true;
  20122. if (!this.parent || !this.parent.getWorldMatrix) {
  20123. this._globalPosition.copyFrom(this.position);
  20124. }
  20125. else {
  20126. if (!this._worldMatrix) {
  20127. this._worldMatrix = BABYLON.Matrix.Identity();
  20128. }
  20129. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20130. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20131. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20132. this._computedViewMatrix.invert();
  20133. this._markSyncedWithParent();
  20134. }
  20135. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20136. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20137. }
  20138. this.onViewMatrixChangedObservable.notifyObservers(this);
  20139. return this._computedViewMatrix;
  20140. };
  20141. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20142. this._doNotComputeProjectionMatrix = true;
  20143. if (projection !== undefined) {
  20144. this._projectionMatrix = projection;
  20145. }
  20146. };
  20147. ;
  20148. Camera.prototype.unfreezeProjectionMatrix = function () {
  20149. this._doNotComputeProjectionMatrix = false;
  20150. };
  20151. ;
  20152. Camera.prototype.getProjectionMatrix = function (force) {
  20153. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20154. return this._projectionMatrix;
  20155. }
  20156. // Cache
  20157. this._cache.mode = this.mode;
  20158. this._cache.minZ = this.minZ;
  20159. this._cache.maxZ = this.maxZ;
  20160. // Matrix
  20161. this._refreshFrustumPlanes = true;
  20162. var engine = this.getEngine();
  20163. var scene = this.getScene();
  20164. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20165. this._cache.fov = this.fov;
  20166. this._cache.fovMode = this.fovMode;
  20167. this._cache.aspectRatio = engine.getAspectRatio(this);
  20168. if (this.minZ <= 0) {
  20169. this.minZ = 0.1;
  20170. }
  20171. if (scene.useRightHandedSystem) {
  20172. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20173. }
  20174. else {
  20175. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20176. }
  20177. }
  20178. else {
  20179. var halfWidth = engine.getRenderWidth() / 2.0;
  20180. var halfHeight = engine.getRenderHeight() / 2.0;
  20181. if (scene.useRightHandedSystem) {
  20182. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20183. }
  20184. else {
  20185. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20186. }
  20187. this._cache.orthoLeft = this.orthoLeft;
  20188. this._cache.orthoRight = this.orthoRight;
  20189. this._cache.orthoBottom = this.orthoBottom;
  20190. this._cache.orthoTop = this.orthoTop;
  20191. this._cache.renderWidth = engine.getRenderWidth();
  20192. this._cache.renderHeight = engine.getRenderHeight();
  20193. }
  20194. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20195. return this._projectionMatrix;
  20196. };
  20197. Camera.prototype.getTranformationMatrix = function () {
  20198. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20199. return this._transformMatrix;
  20200. };
  20201. Camera.prototype.updateFrustumPlanes = function () {
  20202. if (!this._refreshFrustumPlanes) {
  20203. return;
  20204. }
  20205. this.getTranformationMatrix();
  20206. if (!this._frustumPlanes) {
  20207. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20208. }
  20209. else {
  20210. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20211. }
  20212. this._refreshFrustumPlanes = false;
  20213. };
  20214. Camera.prototype.isInFrustum = function (target) {
  20215. this.updateFrustumPlanes();
  20216. return target.isInFrustum(this._frustumPlanes);
  20217. };
  20218. Camera.prototype.isCompletelyInFrustum = function (target) {
  20219. this.updateFrustumPlanes();
  20220. return target.isCompletelyInFrustum(this._frustumPlanes);
  20221. };
  20222. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20223. if (length === void 0) { length = 100; }
  20224. if (!transform) {
  20225. transform = this.getWorldMatrix();
  20226. }
  20227. if (!origin) {
  20228. origin = this.position;
  20229. }
  20230. var forward = new BABYLON.Vector3(0, 0, 1);
  20231. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20232. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20233. return new BABYLON.Ray(origin, direction, length);
  20234. };
  20235. /**
  20236. * Releases resources associated with this node.
  20237. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20238. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20239. */
  20240. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20241. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20242. // Observables
  20243. this.onViewMatrixChangedObservable.clear();
  20244. this.onProjectionMatrixChangedObservable.clear();
  20245. this.onAfterCheckInputsObservable.clear();
  20246. this.onRestoreStateObservable.clear();
  20247. // Inputs
  20248. if (this.inputs) {
  20249. this.inputs.clear();
  20250. }
  20251. // Animations
  20252. this.getScene().stopAnimation(this);
  20253. // Remove from scene
  20254. this.getScene().removeCamera(this);
  20255. while (this._rigCameras.length > 0) {
  20256. var camera = this._rigCameras.pop();
  20257. if (camera) {
  20258. camera.dispose();
  20259. }
  20260. }
  20261. // Postprocesses
  20262. if (this._rigPostProcess) {
  20263. this._rigPostProcess.dispose(this);
  20264. this._rigPostProcess = null;
  20265. this._postProcesses = [];
  20266. }
  20267. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20268. this._rigPostProcess = null;
  20269. this._postProcesses = [];
  20270. }
  20271. else {
  20272. var i = this._postProcesses.length;
  20273. while (--i >= 0) {
  20274. var postProcess = this._postProcesses[i];
  20275. if (postProcess) {
  20276. postProcess.dispose(this);
  20277. }
  20278. }
  20279. }
  20280. // Render targets
  20281. var i = this.customRenderTargets.length;
  20282. while (--i >= 0) {
  20283. this.customRenderTargets[i].dispose();
  20284. }
  20285. this.customRenderTargets = [];
  20286. // Active Meshes
  20287. this._activeMeshes.dispose();
  20288. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20289. };
  20290. Object.defineProperty(Camera.prototype, "leftCamera", {
  20291. // ---- Camera rigs section ----
  20292. get: function () {
  20293. if (this._rigCameras.length < 1) {
  20294. return null;
  20295. }
  20296. return this._rigCameras[0];
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(Camera.prototype, "rightCamera", {
  20302. get: function () {
  20303. if (this._rigCameras.length < 2) {
  20304. return null;
  20305. }
  20306. return this._rigCameras[1];
  20307. },
  20308. enumerable: true,
  20309. configurable: true
  20310. });
  20311. Camera.prototype.getLeftTarget = function () {
  20312. if (this._rigCameras.length < 1) {
  20313. return null;
  20314. }
  20315. return this._rigCameras[0].getTarget();
  20316. };
  20317. Camera.prototype.getRightTarget = function () {
  20318. if (this._rigCameras.length < 2) {
  20319. return null;
  20320. }
  20321. return this._rigCameras[1].getTarget();
  20322. };
  20323. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20324. if (this.cameraRigMode === mode) {
  20325. return;
  20326. }
  20327. while (this._rigCameras.length > 0) {
  20328. var camera = this._rigCameras.pop();
  20329. if (camera) {
  20330. camera.dispose();
  20331. }
  20332. }
  20333. this.cameraRigMode = mode;
  20334. this._cameraRigParams = {};
  20335. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20336. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20337. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20338. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20339. // create the rig cameras, unless none
  20340. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20341. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20342. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20343. if (leftCamera && rightCamera) {
  20344. this._rigCameras.push(leftCamera);
  20345. this._rigCameras.push(rightCamera);
  20346. }
  20347. }
  20348. switch (this.cameraRigMode) {
  20349. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20350. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20351. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20352. break;
  20353. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20354. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20355. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20356. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20357. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20358. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20359. break;
  20360. case Camera.RIG_MODE_VR:
  20361. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20362. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20363. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20364. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20365. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20366. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20367. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20368. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20369. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20370. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20371. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20372. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20373. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20374. if (metrics.compensateDistortion) {
  20375. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20376. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20377. }
  20378. break;
  20379. case Camera.RIG_MODE_WEBVR:
  20380. if (rigParams.vrDisplay) {
  20381. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20382. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20383. //Left eye
  20384. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20385. this._rigCameras[0].setCameraRigParameter("left", true);
  20386. //leaving this for future reference
  20387. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20388. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20389. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20390. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20391. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20392. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20393. this._rigCameras[0].parent = this;
  20394. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20395. //Right eye
  20396. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20397. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20398. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20399. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20400. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20401. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20402. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20403. this._rigCameras[1].parent = this;
  20404. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20405. if (Camera.UseAlternateWebVRRendering) {
  20406. this._rigCameras[1]._skipRendering = true;
  20407. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20408. }
  20409. }
  20410. break;
  20411. }
  20412. this._cascadePostProcessesToRigCams();
  20413. this.update();
  20414. };
  20415. Camera.prototype._getVRProjectionMatrix = function () {
  20416. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20417. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20418. return this._projectionMatrix;
  20419. };
  20420. Camera.prototype._updateCameraRotationMatrix = function () {
  20421. //Here for WebVR
  20422. };
  20423. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20424. //Here for WebVR
  20425. };
  20426. /**
  20427. * This function MUST be overwritten by the different WebVR cameras available.
  20428. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20429. */
  20430. Camera.prototype._getWebVRProjectionMatrix = function () {
  20431. return BABYLON.Matrix.Identity();
  20432. };
  20433. /**
  20434. * This function MUST be overwritten by the different WebVR cameras available.
  20435. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20436. */
  20437. Camera.prototype._getWebVRViewMatrix = function () {
  20438. return BABYLON.Matrix.Identity();
  20439. };
  20440. Camera.prototype.setCameraRigParameter = function (name, value) {
  20441. if (!this._cameraRigParams) {
  20442. this._cameraRigParams = {};
  20443. }
  20444. this._cameraRigParams[name] = value;
  20445. //provisionnally:
  20446. if (name === "interaxialDistance") {
  20447. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20448. }
  20449. };
  20450. /**
  20451. * needs to be overridden by children so sub has required properties to be copied
  20452. */
  20453. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20454. return null;
  20455. };
  20456. /**
  20457. * May need to be overridden by children
  20458. */
  20459. Camera.prototype._updateRigCameras = function () {
  20460. for (var i = 0; i < this._rigCameras.length; i++) {
  20461. this._rigCameras[i].minZ = this.minZ;
  20462. this._rigCameras[i].maxZ = this.maxZ;
  20463. this._rigCameras[i].fov = this.fov;
  20464. }
  20465. // only update viewport when ANAGLYPH
  20466. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20467. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20468. }
  20469. };
  20470. Camera.prototype._setupInputs = function () {
  20471. };
  20472. Camera.prototype.serialize = function () {
  20473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20474. // Type
  20475. serializationObject.type = this.getClassName();
  20476. // Parent
  20477. if (this.parent) {
  20478. serializationObject.parentId = this.parent.id;
  20479. }
  20480. if (this.inputs) {
  20481. this.inputs.serialize(serializationObject);
  20482. }
  20483. // Animations
  20484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20485. serializationObject.ranges = this.serializeAnimationRanges();
  20486. return serializationObject;
  20487. };
  20488. Camera.prototype.clone = function (name) {
  20489. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20490. };
  20491. Camera.prototype.getDirection = function (localAxis) {
  20492. var result = BABYLON.Vector3.Zero();
  20493. this.getDirectionToRef(localAxis, result);
  20494. return result;
  20495. };
  20496. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20497. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20498. };
  20499. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20500. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20501. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20502. switch (type) {
  20503. case "ArcRotateCamera":
  20504. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20505. case "DeviceOrientationCamera":
  20506. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20507. case "FollowCamera":
  20508. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20509. case "ArcFollowCamera":
  20510. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20511. case "GamepadCamera":
  20512. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20513. case "TouchCamera":
  20514. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20515. case "VirtualJoysticksCamera":
  20516. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20517. case "WebVRFreeCamera":
  20518. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20519. case "WebVRGamepadCamera":
  20520. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20521. case "VRDeviceOrientationFreeCamera":
  20522. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20523. case "VRDeviceOrientationGamepadCamera":
  20524. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20525. case "AnaglyphArcRotateCamera":
  20526. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20527. case "AnaglyphFreeCamera":
  20528. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20529. case "AnaglyphGamepadCamera":
  20530. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20531. case "AnaglyphUniversalCamera":
  20532. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20533. case "StereoscopicArcRotateCamera":
  20534. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20535. case "StereoscopicFreeCamera":
  20536. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20537. case "StereoscopicGamepadCamera":
  20538. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20539. case "StereoscopicUniversalCamera":
  20540. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20541. case "FreeCamera":// Forcing Universal here
  20542. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20543. default:// Universal Camera is the default value
  20544. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20545. }
  20546. };
  20547. Camera.prototype.computeWorldMatrix = function () {
  20548. return this.getWorldMatrix();
  20549. };
  20550. Camera.Parse = function (parsedCamera, scene) {
  20551. var type = parsedCamera.type;
  20552. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20553. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20554. // Parent
  20555. if (parsedCamera.parentId) {
  20556. camera._waitingParentId = parsedCamera.parentId;
  20557. }
  20558. //If camera has an input manager, let it parse inputs settings
  20559. if (camera.inputs) {
  20560. camera.inputs.parse(parsedCamera);
  20561. camera._setupInputs();
  20562. }
  20563. if (camera.setPosition) {
  20564. camera.position.copyFromFloats(0, 0, 0);
  20565. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20566. }
  20567. // Target
  20568. if (parsedCamera.target) {
  20569. if (camera.setTarget) {
  20570. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20571. }
  20572. }
  20573. // Apply 3d rig, when found
  20574. if (parsedCamera.cameraRigMode) {
  20575. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20576. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20577. }
  20578. // Animations
  20579. if (parsedCamera.animations) {
  20580. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20581. var parsedAnimation = parsedCamera.animations[animationIndex];
  20582. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20583. }
  20584. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20585. }
  20586. if (parsedCamera.autoAnimate) {
  20587. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20588. }
  20589. return camera;
  20590. };
  20591. // Statics
  20592. Camera._PERSPECTIVE_CAMERA = 0;
  20593. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20594. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20595. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20596. Camera._RIG_MODE_NONE = 0;
  20597. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20598. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20599. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20600. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20601. Camera._RIG_MODE_VR = 20;
  20602. Camera._RIG_MODE_WEBVR = 21;
  20603. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20604. Camera.UseAlternateWebVRRendering = false;
  20605. __decorate([
  20606. BABYLON.serializeAsVector3()
  20607. ], Camera.prototype, "position", void 0);
  20608. __decorate([
  20609. BABYLON.serializeAsVector3()
  20610. ], Camera.prototype, "upVector", void 0);
  20611. __decorate([
  20612. BABYLON.serialize()
  20613. ], Camera.prototype, "orthoLeft", void 0);
  20614. __decorate([
  20615. BABYLON.serialize()
  20616. ], Camera.prototype, "orthoRight", void 0);
  20617. __decorate([
  20618. BABYLON.serialize()
  20619. ], Camera.prototype, "orthoBottom", void 0);
  20620. __decorate([
  20621. BABYLON.serialize()
  20622. ], Camera.prototype, "orthoTop", void 0);
  20623. __decorate([
  20624. BABYLON.serialize()
  20625. ], Camera.prototype, "fov", void 0);
  20626. __decorate([
  20627. BABYLON.serialize()
  20628. ], Camera.prototype, "minZ", void 0);
  20629. __decorate([
  20630. BABYLON.serialize()
  20631. ], Camera.prototype, "maxZ", void 0);
  20632. __decorate([
  20633. BABYLON.serialize()
  20634. ], Camera.prototype, "inertia", void 0);
  20635. __decorate([
  20636. BABYLON.serialize()
  20637. ], Camera.prototype, "mode", void 0);
  20638. __decorate([
  20639. BABYLON.serialize()
  20640. ], Camera.prototype, "layerMask", void 0);
  20641. __decorate([
  20642. BABYLON.serialize()
  20643. ], Camera.prototype, "fovMode", void 0);
  20644. __decorate([
  20645. BABYLON.serialize()
  20646. ], Camera.prototype, "cameraRigMode", void 0);
  20647. __decorate([
  20648. BABYLON.serialize()
  20649. ], Camera.prototype, "interaxialDistance", void 0);
  20650. __decorate([
  20651. BABYLON.serialize()
  20652. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20653. return Camera;
  20654. }(BABYLON.Node));
  20655. BABYLON.Camera = Camera;
  20656. })(BABYLON || (BABYLON = {}));
  20657. //# sourceMappingURL=babylon.camera.js.map
  20658. var BABYLON;
  20659. (function (BABYLON) {
  20660. var RenderingManager = /** @class */ (function () {
  20661. function RenderingManager(scene) {
  20662. this._renderingGroups = new Array();
  20663. this._autoClearDepthStencil = {};
  20664. this._customOpaqueSortCompareFn = {};
  20665. this._customAlphaTestSortCompareFn = {};
  20666. this._customTransparentSortCompareFn = {};
  20667. this._renderinGroupInfo = null;
  20668. this._scene = scene;
  20669. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20670. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20671. }
  20672. }
  20673. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20674. if (depth === void 0) { depth = true; }
  20675. if (stencil === void 0) { stencil = true; }
  20676. if (this._depthStencilBufferAlreadyCleaned) {
  20677. return;
  20678. }
  20679. this._scene.getEngine().clear(null, false, depth, stencil);
  20680. this._depthStencilBufferAlreadyCleaned = true;
  20681. };
  20682. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20683. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20684. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20685. var info = null;
  20686. if (observable) {
  20687. if (!this._renderinGroupInfo) {
  20688. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20689. }
  20690. info = this._renderinGroupInfo;
  20691. info.scene = this._scene;
  20692. info.camera = this._scene.activeCamera;
  20693. }
  20694. // Dispatch sprites
  20695. if (renderSprites) {
  20696. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20697. var manager = this._scene.spriteManagers[index];
  20698. this.dispatchSprites(manager);
  20699. }
  20700. }
  20701. // Render
  20702. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20703. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20704. var renderingGroup = this._renderingGroups[index];
  20705. if (!renderingGroup && !observable)
  20706. continue;
  20707. var renderingGroupMask = 0;
  20708. // Fire PRECLEAR stage
  20709. if (observable && info) {
  20710. renderingGroupMask = Math.pow(2, index);
  20711. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20712. info.renderingGroupId = index;
  20713. observable.notifyObservers(info, renderingGroupMask);
  20714. }
  20715. // Clear depth/stencil if needed
  20716. if (RenderingManager.AUTOCLEAR) {
  20717. var autoClear = this._autoClearDepthStencil[index];
  20718. if (autoClear && autoClear.autoClear) {
  20719. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20720. }
  20721. }
  20722. if (observable && info) {
  20723. // Fire PREOPAQUE stage
  20724. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20725. observable.notifyObservers(info, renderingGroupMask);
  20726. // Fire PRETRANSPARENT stage
  20727. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20728. observable.notifyObservers(info, renderingGroupMask);
  20729. }
  20730. if (renderingGroup)
  20731. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20732. // Fire POSTTRANSPARENT stage
  20733. if (observable && info) {
  20734. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20735. observable.notifyObservers(info, renderingGroupMask);
  20736. }
  20737. }
  20738. };
  20739. RenderingManager.prototype.reset = function () {
  20740. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20741. var renderingGroup = this._renderingGroups[index];
  20742. if (renderingGroup) {
  20743. renderingGroup.prepare();
  20744. }
  20745. }
  20746. };
  20747. RenderingManager.prototype.dispose = function () {
  20748. this.freeRenderingGroups();
  20749. this._renderingGroups.length = 0;
  20750. };
  20751. /**
  20752. * Clear the info related to rendering groups preventing retention points during dispose.
  20753. */
  20754. RenderingManager.prototype.freeRenderingGroups = function () {
  20755. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20756. var renderingGroup = this._renderingGroups[index];
  20757. if (renderingGroup) {
  20758. renderingGroup.dispose();
  20759. }
  20760. }
  20761. };
  20762. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20763. if (this._renderingGroups[renderingGroupId] === undefined) {
  20764. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20765. }
  20766. };
  20767. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20768. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20769. this._prepareRenderingGroup(renderingGroupId);
  20770. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20771. };
  20772. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20773. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20774. this._prepareRenderingGroup(renderingGroupId);
  20775. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20776. };
  20777. /**
  20778. * @param subMesh The submesh to dispatch
  20779. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20780. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20781. */
  20782. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20783. if (mesh === undefined) {
  20784. mesh = subMesh.getMesh();
  20785. }
  20786. var renderingGroupId = mesh.renderingGroupId || 0;
  20787. this._prepareRenderingGroup(renderingGroupId);
  20788. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20789. };
  20790. /**
  20791. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20792. * This allowed control for front to back rendering or reversly depending of the special needs.
  20793. *
  20794. * @param renderingGroupId The rendering group id corresponding to its index
  20795. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20796. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20797. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20798. */
  20799. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20800. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20801. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20802. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20803. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20804. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20805. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20806. if (this._renderingGroups[renderingGroupId]) {
  20807. var group = this._renderingGroups[renderingGroupId];
  20808. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20809. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20810. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20811. }
  20812. };
  20813. /**
  20814. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20815. *
  20816. * @param renderingGroupId The rendering group id corresponding to its index
  20817. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20818. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20819. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20820. */
  20821. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20822. if (depth === void 0) { depth = true; }
  20823. if (stencil === void 0) { stencil = true; }
  20824. this._autoClearDepthStencil[renderingGroupId] = {
  20825. autoClear: autoClearDepthStencil,
  20826. depth: depth,
  20827. stencil: stencil
  20828. };
  20829. };
  20830. /**
  20831. * The max id used for rendering groups (not included)
  20832. */
  20833. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20834. /**
  20835. * The min id used for rendering groups (included)
  20836. */
  20837. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20838. /**
  20839. * Used to globally prevent autoclearing scenes.
  20840. */
  20841. RenderingManager.AUTOCLEAR = true;
  20842. return RenderingManager;
  20843. }());
  20844. BABYLON.RenderingManager = RenderingManager;
  20845. })(BABYLON || (BABYLON = {}));
  20846. //# sourceMappingURL=babylon.renderingManager.js.map
  20847. var BABYLON;
  20848. (function (BABYLON) {
  20849. var RenderingGroup = /** @class */ (function () {
  20850. /**
  20851. * Creates a new rendering group.
  20852. * @param index The rendering group index
  20853. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20854. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20855. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20856. */
  20857. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20858. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20859. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20860. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20861. this.index = index;
  20862. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20863. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20864. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20865. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20866. this._particleSystems = new BABYLON.SmartArray(256);
  20867. this._spriteManagers = new BABYLON.SmartArray(256);
  20868. this._edgesRenderers = new BABYLON.SmartArray(16);
  20869. this._scene = scene;
  20870. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20871. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20872. this.transparentSortCompareFn = transparentSortCompareFn;
  20873. }
  20874. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20875. /**
  20876. * Set the opaque sort comparison function.
  20877. * If null the sub meshes will be render in the order they were created
  20878. */
  20879. set: function (value) {
  20880. this._opaqueSortCompareFn = value;
  20881. if (value) {
  20882. this._renderOpaque = this.renderOpaqueSorted;
  20883. }
  20884. else {
  20885. this._renderOpaque = RenderingGroup.renderUnsorted;
  20886. }
  20887. },
  20888. enumerable: true,
  20889. configurable: true
  20890. });
  20891. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20892. /**
  20893. * Set the alpha test sort comparison function.
  20894. * If null the sub meshes will be render in the order they were created
  20895. */
  20896. set: function (value) {
  20897. this._alphaTestSortCompareFn = value;
  20898. if (value) {
  20899. this._renderAlphaTest = this.renderAlphaTestSorted;
  20900. }
  20901. else {
  20902. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20903. }
  20904. },
  20905. enumerable: true,
  20906. configurable: true
  20907. });
  20908. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20909. /**
  20910. * Set the transparent sort comparison function.
  20911. * If null the sub meshes will be render in the order they were created
  20912. */
  20913. set: function (value) {
  20914. if (value) {
  20915. this._transparentSortCompareFn = value;
  20916. }
  20917. else {
  20918. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20919. }
  20920. this._renderTransparent = this.renderTransparentSorted;
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. /**
  20926. * Render all the sub meshes contained in the group.
  20927. * @param customRenderFunction Used to override the default render behaviour of the group.
  20928. * @returns true if rendered some submeshes.
  20929. */
  20930. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20931. if (customRenderFunction) {
  20932. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20933. return;
  20934. }
  20935. var engine = this._scene.getEngine();
  20936. // Depth only
  20937. if (this._depthOnlySubMeshes.length !== 0) {
  20938. engine.setColorWrite(false);
  20939. this._renderAlphaTest(this._depthOnlySubMeshes);
  20940. engine.setColorWrite(true);
  20941. }
  20942. // Opaque
  20943. if (this._opaqueSubMeshes.length !== 0) {
  20944. this._renderOpaque(this._opaqueSubMeshes);
  20945. }
  20946. // Alpha test
  20947. if (this._alphaTestSubMeshes.length !== 0) {
  20948. this._renderAlphaTest(this._alphaTestSubMeshes);
  20949. }
  20950. var stencilState = engine.getStencilBuffer();
  20951. engine.setStencilBuffer(false);
  20952. // Sprites
  20953. if (renderSprites) {
  20954. this._renderSprites();
  20955. }
  20956. // Particles
  20957. if (renderParticles) {
  20958. this._renderParticles(activeMeshes);
  20959. }
  20960. if (this.onBeforeTransparentRendering) {
  20961. this.onBeforeTransparentRendering();
  20962. }
  20963. // Transparent
  20964. if (this._transparentSubMeshes.length !== 0) {
  20965. this._renderTransparent(this._transparentSubMeshes);
  20966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20967. }
  20968. // Set back stencil to false in case it changes before the edge renderer.
  20969. engine.setStencilBuffer(false);
  20970. // Edges
  20971. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20972. this._edgesRenderers.data[edgesRendererIndex].render();
  20973. }
  20974. // Restore Stencil state.
  20975. engine.setStencilBuffer(stencilState);
  20976. };
  20977. /**
  20978. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20979. * @param subMeshes The submeshes to render
  20980. */
  20981. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20982. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20983. };
  20984. /**
  20985. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20986. * @param subMeshes The submeshes to render
  20987. */
  20988. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20989. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20990. };
  20991. /**
  20992. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20993. * @param subMeshes The submeshes to render
  20994. */
  20995. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20996. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20997. };
  20998. /**
  20999. * Renders the submeshes in a specified order.
  21000. * @param subMeshes The submeshes to sort before render
  21001. * @param sortCompareFn The comparison function use to sort
  21002. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21003. * @param transparent Specifies to activate blending if true
  21004. */
  21005. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21006. var subIndex = 0;
  21007. var subMesh;
  21008. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21009. for (; subIndex < subMeshes.length; subIndex++) {
  21010. subMesh = subMeshes.data[subIndex];
  21011. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21012. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21013. }
  21014. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21015. if (sortCompareFn) {
  21016. sortedArray.sort(sortCompareFn);
  21017. }
  21018. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21019. subMesh = sortedArray[subIndex];
  21020. if (transparent) {
  21021. var material = subMesh.getMaterial();
  21022. if (material && material.needDepthPrePass) {
  21023. var engine = material.getScene().getEngine();
  21024. engine.setColorWrite(false);
  21025. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21026. subMesh.render(false);
  21027. engine.setColorWrite(true);
  21028. }
  21029. }
  21030. subMesh.render(transparent);
  21031. }
  21032. };
  21033. /**
  21034. * Renders the submeshes in the order they were dispatched (no sort applied).
  21035. * @param subMeshes The submeshes to render
  21036. */
  21037. RenderingGroup.renderUnsorted = function (subMeshes) {
  21038. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21039. var submesh = subMeshes.data[subIndex];
  21040. submesh.render(false);
  21041. }
  21042. };
  21043. /**
  21044. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21045. * are rendered back to front if in the same alpha index.
  21046. *
  21047. * @param a The first submesh
  21048. * @param b The second submesh
  21049. * @returns The result of the comparison
  21050. */
  21051. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21052. // Alpha index first
  21053. if (a._alphaIndex > b._alphaIndex) {
  21054. return 1;
  21055. }
  21056. if (a._alphaIndex < b._alphaIndex) {
  21057. return -1;
  21058. }
  21059. // Then distance to camera
  21060. return RenderingGroup.backToFrontSortCompare(a, b);
  21061. };
  21062. /**
  21063. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21064. * are rendered back to front.
  21065. *
  21066. * @param a The first submesh
  21067. * @param b The second submesh
  21068. * @returns The result of the comparison
  21069. */
  21070. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21071. // Then distance to camera
  21072. if (a._distanceToCamera < b._distanceToCamera) {
  21073. return 1;
  21074. }
  21075. if (a._distanceToCamera > b._distanceToCamera) {
  21076. return -1;
  21077. }
  21078. return 0;
  21079. };
  21080. /**
  21081. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21082. * are rendered front to back (prevent overdraw).
  21083. *
  21084. * @param a The first submesh
  21085. * @param b The second submesh
  21086. * @returns The result of the comparison
  21087. */
  21088. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21089. // Then distance to camera
  21090. if (a._distanceToCamera < b._distanceToCamera) {
  21091. return -1;
  21092. }
  21093. if (a._distanceToCamera > b._distanceToCamera) {
  21094. return 1;
  21095. }
  21096. return 0;
  21097. };
  21098. /**
  21099. * Resets the different lists of submeshes to prepare a new frame.
  21100. */
  21101. RenderingGroup.prototype.prepare = function () {
  21102. this._opaqueSubMeshes.reset();
  21103. this._transparentSubMeshes.reset();
  21104. this._alphaTestSubMeshes.reset();
  21105. this._depthOnlySubMeshes.reset();
  21106. this._particleSystems.reset();
  21107. this._spriteManagers.reset();
  21108. this._edgesRenderers.reset();
  21109. };
  21110. RenderingGroup.prototype.dispose = function () {
  21111. this._opaqueSubMeshes.dispose();
  21112. this._transparentSubMeshes.dispose();
  21113. this._alphaTestSubMeshes.dispose();
  21114. this._depthOnlySubMeshes.dispose();
  21115. this._particleSystems.dispose();
  21116. this._spriteManagers.dispose();
  21117. this._edgesRenderers.dispose();
  21118. };
  21119. /**
  21120. * Inserts the submesh in its correct queue depending on its material.
  21121. * @param subMesh The submesh to dispatch
  21122. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21123. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21124. */
  21125. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21126. // Get mesh and materials if not provided
  21127. if (mesh === undefined) {
  21128. mesh = subMesh.getMesh();
  21129. }
  21130. if (material === undefined) {
  21131. material = subMesh.getMaterial();
  21132. }
  21133. if (material === null || material === undefined) {
  21134. return;
  21135. }
  21136. if (material.needAlphaBlendingForMesh(mesh)) {
  21137. this._transparentSubMeshes.push(subMesh);
  21138. }
  21139. else if (material.needAlphaTesting()) {
  21140. if (material.needDepthPrePass) {
  21141. this._depthOnlySubMeshes.push(subMesh);
  21142. }
  21143. this._alphaTestSubMeshes.push(subMesh);
  21144. }
  21145. else {
  21146. if (material.needDepthPrePass) {
  21147. this._depthOnlySubMeshes.push(subMesh);
  21148. }
  21149. this._opaqueSubMeshes.push(subMesh); // Opaque
  21150. }
  21151. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21152. this._edgesRenderers.push(mesh._edgesRenderer);
  21153. }
  21154. };
  21155. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21156. this._spriteManagers.push(spriteManager);
  21157. };
  21158. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21159. this._particleSystems.push(particleSystem);
  21160. };
  21161. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21162. if (this._particleSystems.length === 0) {
  21163. return;
  21164. }
  21165. // Particles
  21166. var activeCamera = this._scene.activeCamera;
  21167. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21168. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21169. var particleSystem = this._particleSystems.data[particleIndex];
  21170. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21171. continue;
  21172. }
  21173. var emitter = particleSystem.emitter;
  21174. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21175. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21176. }
  21177. }
  21178. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21179. };
  21180. RenderingGroup.prototype._renderSprites = function () {
  21181. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21182. return;
  21183. }
  21184. // Sprites
  21185. var activeCamera = this._scene.activeCamera;
  21186. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21187. for (var id = 0; id < this._spriteManagers.length; id++) {
  21188. var spriteManager = this._spriteManagers.data[id];
  21189. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21190. spriteManager.render();
  21191. }
  21192. }
  21193. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21194. };
  21195. return RenderingGroup;
  21196. }());
  21197. BABYLON.RenderingGroup = RenderingGroup;
  21198. })(BABYLON || (BABYLON = {}));
  21199. //# sourceMappingURL=babylon.renderingGroup.js.map
  21200. var BABYLON;
  21201. (function (BABYLON) {
  21202. var ClickInfo = /** @class */ (function () {
  21203. function ClickInfo() {
  21204. this._singleClick = false;
  21205. this._doubleClick = false;
  21206. this._hasSwiped = false;
  21207. this._ignore = false;
  21208. }
  21209. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21210. get: function () {
  21211. return this._singleClick;
  21212. },
  21213. set: function (b) {
  21214. this._singleClick = b;
  21215. },
  21216. enumerable: true,
  21217. configurable: true
  21218. });
  21219. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21220. get: function () {
  21221. return this._doubleClick;
  21222. },
  21223. set: function (b) {
  21224. this._doubleClick = b;
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21230. get: function () {
  21231. return this._hasSwiped;
  21232. },
  21233. set: function (b) {
  21234. this._hasSwiped = b;
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21240. get: function () {
  21241. return this._ignore;
  21242. },
  21243. set: function (b) {
  21244. this._ignore = b;
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. return ClickInfo;
  21250. }());
  21251. /**
  21252. * This class is used by the onRenderingGroupObservable
  21253. */
  21254. var RenderingGroupInfo = /** @class */ (function () {
  21255. function RenderingGroupInfo() {
  21256. }
  21257. /**
  21258. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21259. * This stage will be fired no matter what
  21260. */
  21261. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21262. /**
  21263. * Called before opaque object are rendered.
  21264. * This stage will be fired only if there's 3D Opaque content to render
  21265. */
  21266. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21267. /**
  21268. * Called after the opaque objects are rendered and before the transparent ones
  21269. * This stage will be fired only if there's 3D transparent content to render
  21270. */
  21271. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21272. /**
  21273. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21274. * This stage will be fired no matter what
  21275. */
  21276. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21277. return RenderingGroupInfo;
  21278. }());
  21279. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21280. /**
  21281. * Represents a scene to be rendered by the engine.
  21282. * @see http://doc.babylonjs.com/page.php?p=21911
  21283. */
  21284. var Scene = /** @class */ (function () {
  21285. /**
  21286. * @constructor
  21287. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21288. */
  21289. function Scene(engine) {
  21290. // Members
  21291. this.autoClear = true;
  21292. this.autoClearDepthAndStencil = true;
  21293. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21294. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21295. this.forceWireframe = false;
  21296. this._forcePointsCloud = false;
  21297. this.forceShowBoundingBoxes = false;
  21298. this.animationsEnabled = true;
  21299. this.useConstantAnimationDeltaTime = false;
  21300. this.constantlyUpdateMeshUnderPointer = false;
  21301. this.hoverCursor = "pointer";
  21302. this.defaultCursor = "";
  21303. /**
  21304. * This is used to call preventDefault() on pointer down
  21305. * in order to block unwanted artifacts like system double clicks
  21306. */
  21307. this.preventDefaultOnPointerDown = true;
  21308. // Metadata
  21309. this.metadata = null;
  21310. /**
  21311. * An event triggered when the scene is disposed.
  21312. * @type {BABYLON.Observable}
  21313. */
  21314. this.onDisposeObservable = new BABYLON.Observable();
  21315. /**
  21316. * An event triggered before rendering the scene (right after animations and physics)
  21317. * @type {BABYLON.Observable}
  21318. */
  21319. this.onBeforeRenderObservable = new BABYLON.Observable();
  21320. /**
  21321. * An event triggered after rendering the scene
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.onAfterRenderObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered before animating the scene
  21327. * @type {BABYLON.Observable}
  21328. */
  21329. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21330. /**
  21331. * An event triggered after animations processing
  21332. * @type {BABYLON.Observable}
  21333. */
  21334. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21335. /**
  21336. * An event triggered before draw calls are ready to be sent
  21337. * @type {BABYLON.Observable}
  21338. */
  21339. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21340. /**
  21341. * An event triggered after draw calls have been sent
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered when physic simulation is about to be run
  21347. * @type {BABYLON.Observable}
  21348. */
  21349. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21350. /**
  21351. * An event triggered when physic simulation has been done
  21352. * @type {BABYLON.Observable}
  21353. */
  21354. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21355. /**
  21356. * An event triggered when the scene is ready
  21357. * @type {BABYLON.Observable}
  21358. */
  21359. this.onReadyObservable = new BABYLON.Observable();
  21360. /**
  21361. * An event triggered before rendering a camera
  21362. * @type {BABYLON.Observable}
  21363. */
  21364. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21365. /**
  21366. * An event triggered after rendering a camera
  21367. * @type {BABYLON.Observable}
  21368. */
  21369. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21370. /**
  21371. * An event triggered when active meshes evaluation is about to start
  21372. * @type {BABYLON.Observable}
  21373. */
  21374. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21375. /**
  21376. * An event triggered when active meshes evaluation is done
  21377. * @type {BABYLON.Observable}
  21378. */
  21379. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21380. /**
  21381. * An event triggered when particles rendering is about to start
  21382. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21383. * @type {BABYLON.Observable}
  21384. */
  21385. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21386. /**
  21387. * An event triggered when particles rendering is done
  21388. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21389. * @type {BABYLON.Observable}
  21390. */
  21391. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21392. /**
  21393. * An event triggered when sprites rendering is about to start
  21394. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21395. * @type {BABYLON.Observable}
  21396. */
  21397. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21398. /**
  21399. * An event triggered when sprites rendering is done
  21400. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21401. * @type {BABYLON.Observable}
  21402. */
  21403. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21404. /**
  21405. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21406. * @type {BABYLON.Observable}
  21407. */
  21408. this.onDataLoadedObservable = new BABYLON.Observable();
  21409. /**
  21410. * An event triggered when a camera is created
  21411. * @type {BABYLON.Observable}
  21412. */
  21413. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21414. /**
  21415. * An event triggered when a camera is removed
  21416. * @type {BABYLON.Observable}
  21417. */
  21418. this.onCameraRemovedObservable = new BABYLON.Observable();
  21419. /**
  21420. * An event triggered when a light is created
  21421. * @type {BABYLON.Observable}
  21422. */
  21423. this.onNewLightAddedObservable = new BABYLON.Observable();
  21424. /**
  21425. * An event triggered when a light is removed
  21426. * @type {BABYLON.Observable}
  21427. */
  21428. this.onLightRemovedObservable = new BABYLON.Observable();
  21429. /**
  21430. * An event triggered when a geometry is created
  21431. * @type {BABYLON.Observable}
  21432. */
  21433. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21434. /**
  21435. * An event triggered when a geometry is removed
  21436. * @type {BABYLON.Observable}
  21437. */
  21438. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21439. /**
  21440. * An event triggered when a transform node is created
  21441. * @type {BABYLON.Observable}
  21442. */
  21443. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21444. /**
  21445. * An event triggered when a transform node is removed
  21446. * @type {BABYLON.Observable}
  21447. */
  21448. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21449. /**
  21450. * An event triggered when a mesh is created
  21451. * @type {BABYLON.Observable}
  21452. */
  21453. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21454. /**
  21455. * An event triggered when a mesh is removed
  21456. * @type {BABYLON.Observable}
  21457. */
  21458. this.onMeshRemovedObservable = new BABYLON.Observable();
  21459. /**
  21460. * An event triggered when render targets are about to be rendered
  21461. * Can happen multiple times per frame.
  21462. * @type {BABYLON.Observable}
  21463. */
  21464. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21465. /**
  21466. * An event triggered when render targets were rendered.
  21467. * Can happen multiple times per frame.
  21468. * @type {BABYLON.Observable}
  21469. */
  21470. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21471. /**
  21472. * An event triggered before calculating deterministic simulation step
  21473. * @type {BABYLON.Observable}
  21474. */
  21475. this.onBeforeStepObservable = new BABYLON.Observable();
  21476. /**
  21477. * An event triggered after calculating deterministic simulation step
  21478. * @type {BABYLON.Observable}
  21479. */
  21480. this.onAfterStepObservable = new BABYLON.Observable();
  21481. /**
  21482. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21483. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21484. * 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)
  21485. */
  21486. this.onRenderingGroupObservable = new BABYLON.Observable();
  21487. // Animations
  21488. this.animations = [];
  21489. /**
  21490. * 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).
  21491. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21492. */
  21493. this.onPrePointerObservable = new BABYLON.Observable();
  21494. /**
  21495. * Observable event triggered each time an input event is received from the rendering canvas
  21496. */
  21497. this.onPointerObservable = new BABYLON.Observable();
  21498. this._meshPickProceed = false;
  21499. this._currentPickResult = null;
  21500. this._previousPickResult = null;
  21501. this._totalPointersPressed = 0;
  21502. this._doubleClickOccured = false;
  21503. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21504. this.cameraToUseForPointers = null;
  21505. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21506. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21507. this._startingPointerTime = 0;
  21508. this._previousStartingPointerTime = 0;
  21509. // Deterministic lockstep
  21510. this._timeAccumulator = 0;
  21511. this._currentStepId = 0;
  21512. this._currentInternalStep = 0;
  21513. // Keyboard
  21514. /**
  21515. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21516. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21517. */
  21518. this.onPreKeyboardObservable = new BABYLON.Observable();
  21519. /**
  21520. * Observable event triggered each time an keyboard event is received from the hosting window
  21521. */
  21522. this.onKeyboardObservable = new BABYLON.Observable();
  21523. // Coordinate system
  21524. /**
  21525. * use right-handed coordinate system on this scene.
  21526. * @type {boolean}
  21527. */
  21528. this._useRightHandedSystem = false;
  21529. // Fog
  21530. this._fogEnabled = true;
  21531. this._fogMode = Scene.FOGMODE_NONE;
  21532. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21533. this.fogDensity = 0.1;
  21534. this.fogStart = 0;
  21535. this.fogEnd = 1000.0;
  21536. // Lights
  21537. /**
  21538. * is shadow enabled on this scene.
  21539. * @type {boolean}
  21540. */
  21541. this._shadowsEnabled = true;
  21542. /**
  21543. * is light enabled on this scene.
  21544. * @type {boolean}
  21545. */
  21546. this._lightsEnabled = true;
  21547. /**
  21548. * All of the lights added to this scene.
  21549. * @see BABYLON.Light
  21550. * @type {BABYLON.Light[]}
  21551. */
  21552. this.lights = new Array();
  21553. // Cameras
  21554. /** All of the cameras added to this scene. */
  21555. this.cameras = new Array();
  21556. /** All of the active cameras added to this scene. */
  21557. this.activeCameras = new Array();
  21558. // Meshes
  21559. /**
  21560. * All of the tranform nodes added to this scene.
  21561. * @see BABYLON.TransformNode
  21562. * @type {BABYLON.TransformNode[]}
  21563. */
  21564. this.transformNodes = new Array();
  21565. /**
  21566. * All of the (abstract) meshes added to this scene.
  21567. * @see BABYLON.AbstractMesh
  21568. * @type {BABYLON.AbstractMesh[]}
  21569. */
  21570. this.meshes = new Array();
  21571. /**
  21572. * All of the animation groups added to this scene.
  21573. * @see BABYLON.AnimationGroup
  21574. * @type {BABYLON.AnimationGroup[]}
  21575. */
  21576. this.animationGroups = new Array();
  21577. // Geometries
  21578. this._geometries = new Array();
  21579. this.materials = new Array();
  21580. this.multiMaterials = new Array();
  21581. // Textures
  21582. this._texturesEnabled = true;
  21583. this.textures = new Array();
  21584. // Particles
  21585. this.particlesEnabled = true;
  21586. this.particleSystems = new Array();
  21587. // Sprites
  21588. this.spritesEnabled = true;
  21589. this.spriteManagers = new Array();
  21590. /**
  21591. * The list of layers (background and foreground) of the scene.
  21592. */
  21593. this.layers = new Array();
  21594. /**
  21595. * The list of effect layers (highlights/glow) contained in the scene.
  21596. */
  21597. this.effectLayers = new Array();
  21598. // Skeletons
  21599. this._skeletonsEnabled = true;
  21600. this.skeletons = new Array();
  21601. // Morph targets
  21602. this.morphTargetManagers = new Array();
  21603. // Lens flares
  21604. this.lensFlaresEnabled = true;
  21605. this.lensFlareSystems = new Array();
  21606. // Collisions
  21607. this.collisionsEnabled = true;
  21608. /** Defines the gravity applied to this scene */
  21609. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21610. // Postprocesses
  21611. this.postProcesses = new Array();
  21612. this.postProcessesEnabled = true;
  21613. // Customs render targets
  21614. this.renderTargetsEnabled = true;
  21615. this.dumpNextRenderTargets = false;
  21616. this.customRenderTargets = new Array();
  21617. // Imported meshes
  21618. this.importedMeshesFiles = new Array();
  21619. // Probes
  21620. this.probesEnabled = true;
  21621. this.reflectionProbes = new Array();
  21622. this._actionManagers = new Array();
  21623. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21624. // Procedural textures
  21625. this.proceduralTexturesEnabled = true;
  21626. this._proceduralTextures = new Array();
  21627. this.soundTracks = new Array();
  21628. this._audioEnabled = true;
  21629. this._headphone = false;
  21630. // Performance counters
  21631. this._totalVertices = new BABYLON.PerfCounter();
  21632. this._activeIndices = new BABYLON.PerfCounter();
  21633. this._activeParticles = new BABYLON.PerfCounter();
  21634. this._activeBones = new BABYLON.PerfCounter();
  21635. this._animationTime = 0;
  21636. this.animationTimeScale = 1;
  21637. this._renderId = 0;
  21638. this._executeWhenReadyTimeoutId = -1;
  21639. this._intermediateRendering = false;
  21640. this._viewUpdateFlag = -1;
  21641. this._projectionUpdateFlag = -1;
  21642. this._alternateViewUpdateFlag = -1;
  21643. this._alternateProjectionUpdateFlag = -1;
  21644. this._toBeDisposed = new BABYLON.SmartArray(256);
  21645. this._activeRequests = new Array();
  21646. this._pendingData = new Array();
  21647. this._isDisposed = false;
  21648. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21649. this._activeMeshes = new BABYLON.SmartArray(256);
  21650. this._processedMaterials = new BABYLON.SmartArray(256);
  21651. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21652. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21653. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21654. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21655. this._activeAnimatables = new Array();
  21656. this._transformMatrix = BABYLON.Matrix.Zero();
  21657. this._useAlternateCameraConfiguration = false;
  21658. this._alternateRendering = false;
  21659. this.requireLightSorting = false;
  21660. this._depthRenderer = {};
  21661. this._activeMeshesFrozen = false;
  21662. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21663. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21664. this._engine.scenes.push(this);
  21665. this._uid = null;
  21666. this._renderingManager = new BABYLON.RenderingManager(this);
  21667. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21668. if (BABYLON.OutlineRenderer) {
  21669. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21670. }
  21671. if (BABYLON.Tools.IsWindowObjectExist()) {
  21672. this.attachControl();
  21673. }
  21674. //simplification queue
  21675. if (BABYLON.SimplificationQueue) {
  21676. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21677. }
  21678. //collision coordinator initialization. For now legacy per default.
  21679. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21680. // Uniform Buffer
  21681. this._createUbo();
  21682. // Default Image processing definition.
  21683. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21684. }
  21685. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21686. /** The fog is deactivated */
  21687. get: function () {
  21688. return Scene._FOGMODE_NONE;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21694. /** The fog density is following an exponential function */
  21695. get: function () {
  21696. return Scene._FOGMODE_EXP;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21702. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21703. get: function () {
  21704. return Scene._FOGMODE_EXP2;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21710. /** The fog density is following a linear function. */
  21711. get: function () {
  21712. return Scene._FOGMODE_LINEAR;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21718. /**
  21719. * Texture used in all pbr material as the reflection texture.
  21720. * As in the majority of the scene they are the same (exception for multi room and so on),
  21721. * this is easier to reference from here than from all the materials.
  21722. */
  21723. get: function () {
  21724. return this._environmentTexture;
  21725. },
  21726. /**
  21727. * Texture used in all pbr material as the reflection texture.
  21728. * As in the majority of the scene they are the same (exception for multi room and so on),
  21729. * this is easier to set here than in all the materials.
  21730. */
  21731. set: function (value) {
  21732. if (this._environmentTexture === value) {
  21733. return;
  21734. }
  21735. this._environmentTexture = value;
  21736. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21742. /**
  21743. * Default image processing configuration used either in the rendering
  21744. * Forward main pass or through the imageProcessingPostProcess if present.
  21745. * As in the majority of the scene they are the same (exception for multi camera),
  21746. * this is easier to reference from here than from all the materials and post process.
  21747. *
  21748. * No setter as we it is a shared configuration, you can set the values instead.
  21749. */
  21750. get: function () {
  21751. return this._imageProcessingConfiguration;
  21752. },
  21753. enumerable: true,
  21754. configurable: true
  21755. });
  21756. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21757. get: function () {
  21758. return this._forcePointsCloud;
  21759. },
  21760. set: function (value) {
  21761. if (this._forcePointsCloud === value) {
  21762. return;
  21763. }
  21764. this._forcePointsCloud = value;
  21765. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21766. },
  21767. enumerable: true,
  21768. configurable: true
  21769. });
  21770. Object.defineProperty(Scene.prototype, "onDispose", {
  21771. /** A function to be executed when this scene is disposed. */
  21772. set: function (callback) {
  21773. if (this._onDisposeObserver) {
  21774. this.onDisposeObservable.remove(this._onDisposeObserver);
  21775. }
  21776. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(Scene.prototype, "beforeRender", {
  21782. /** A function to be executed before rendering this scene */
  21783. set: function (callback) {
  21784. if (this._onBeforeRenderObserver) {
  21785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21786. }
  21787. if (callback) {
  21788. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21789. }
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. Object.defineProperty(Scene.prototype, "afterRender", {
  21795. /** A function to be executed after rendering this scene */
  21796. set: function (callback) {
  21797. if (this._onAfterRenderObserver) {
  21798. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21799. }
  21800. if (callback) {
  21801. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21802. }
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21808. set: function (callback) {
  21809. if (this._onBeforeCameraRenderObserver) {
  21810. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21811. }
  21812. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21818. set: function (callback) {
  21819. if (this._onAfterCameraRenderObserver) {
  21820. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21821. }
  21822. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21823. },
  21824. enumerable: true,
  21825. configurable: true
  21826. });
  21827. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21828. get: function () {
  21829. if (!this._gamepadManager) {
  21830. this._gamepadManager = new BABYLON.GamepadManager(this);
  21831. }
  21832. return this._gamepadManager;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21838. get: function () {
  21839. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21845. get: function () {
  21846. return this._useRightHandedSystem;
  21847. },
  21848. set: function (value) {
  21849. if (this._useRightHandedSystem === value) {
  21850. return;
  21851. }
  21852. this._useRightHandedSystem = value;
  21853. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Scene.prototype.setStepId = function (newStepId) {
  21859. this._currentStepId = newStepId;
  21860. };
  21861. ;
  21862. Scene.prototype.getStepId = function () {
  21863. return this._currentStepId;
  21864. };
  21865. ;
  21866. Scene.prototype.getInternalStep = function () {
  21867. return this._currentInternalStep;
  21868. };
  21869. ;
  21870. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21871. get: function () {
  21872. return this._fogEnabled;
  21873. },
  21874. /**
  21875. * is fog enabled on this scene.
  21876. */
  21877. set: function (value) {
  21878. if (this._fogEnabled === value) {
  21879. return;
  21880. }
  21881. this._fogEnabled = value;
  21882. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(Scene.prototype, "fogMode", {
  21888. get: function () {
  21889. return this._fogMode;
  21890. },
  21891. set: function (value) {
  21892. if (this._fogMode === value) {
  21893. return;
  21894. }
  21895. this._fogMode = value;
  21896. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21902. get: function () {
  21903. return this._shadowsEnabled;
  21904. },
  21905. set: function (value) {
  21906. if (this._shadowsEnabled === value) {
  21907. return;
  21908. }
  21909. this._shadowsEnabled = value;
  21910. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21916. get: function () {
  21917. return this._lightsEnabled;
  21918. },
  21919. set: function (value) {
  21920. if (this._lightsEnabled === value) {
  21921. return;
  21922. }
  21923. this._lightsEnabled = value;
  21924. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21925. },
  21926. enumerable: true,
  21927. configurable: true
  21928. });
  21929. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21930. /** The default material used on meshes when no material is affected */
  21931. get: function () {
  21932. if (!this._defaultMaterial) {
  21933. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21934. }
  21935. return this._defaultMaterial;
  21936. },
  21937. /** The default material used on meshes when no material is affected */
  21938. set: function (value) {
  21939. this._defaultMaterial = value;
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21945. get: function () {
  21946. return this._texturesEnabled;
  21947. },
  21948. set: function (value) {
  21949. if (this._texturesEnabled === value) {
  21950. return;
  21951. }
  21952. this._texturesEnabled = value;
  21953. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21959. get: function () {
  21960. return this._skeletonsEnabled;
  21961. },
  21962. set: function (value) {
  21963. if (this._skeletonsEnabled === value) {
  21964. return;
  21965. }
  21966. this._skeletonsEnabled = value;
  21967. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21973. get: function () {
  21974. if (!this._postProcessRenderPipelineManager) {
  21975. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21976. }
  21977. return this._postProcessRenderPipelineManager;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21983. get: function () {
  21984. if (!this._mainSoundTrack) {
  21985. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21986. }
  21987. return this._mainSoundTrack;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21993. get: function () {
  21994. return this._alternateRendering;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22000. get: function () {
  22001. return this._frustumPlanes;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22007. /**
  22008. * Gets the current geometry buffer associated to the scene.
  22009. */
  22010. get: function () {
  22011. return this._geometryBufferRenderer;
  22012. },
  22013. /**
  22014. * Sets the current geometry buffer for the scene.
  22015. */
  22016. set: function (geometryBufferRenderer) {
  22017. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22018. this._geometryBufferRenderer = geometryBufferRenderer;
  22019. }
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Scene.prototype, "debugLayer", {
  22025. // Properties
  22026. get: function () {
  22027. if (!this._debugLayer) {
  22028. this._debugLayer = new BABYLON.DebugLayer(this);
  22029. }
  22030. return this._debugLayer;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22036. get: function () {
  22037. return this._workerCollisions;
  22038. },
  22039. set: function (enabled) {
  22040. if (!BABYLON.CollisionCoordinatorLegacy) {
  22041. return;
  22042. }
  22043. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22044. this._workerCollisions = enabled;
  22045. if (this.collisionCoordinator) {
  22046. this.collisionCoordinator.destroy();
  22047. }
  22048. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22049. this.collisionCoordinator.init(this);
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22055. get: function () {
  22056. return this._selectionOctree;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22062. /**
  22063. * The mesh that is currently under the pointer.
  22064. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22065. */
  22066. get: function () {
  22067. return this._pointerOverMesh;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Scene.prototype, "pointerX", {
  22073. /**
  22074. * Current on-screen X position of the pointer
  22075. * @return {number} X position of the pointer
  22076. */
  22077. get: function () {
  22078. return this._pointerX;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "pointerY", {
  22084. /**
  22085. * Current on-screen Y position of the pointer
  22086. * @return {number} Y position of the pointer
  22087. */
  22088. get: function () {
  22089. return this._pointerY;
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Scene.prototype.getCachedMaterial = function () {
  22095. return this._cachedMaterial;
  22096. };
  22097. Scene.prototype.getCachedEffect = function () {
  22098. return this._cachedEffect;
  22099. };
  22100. Scene.prototype.getCachedVisibility = function () {
  22101. return this._cachedVisibility;
  22102. };
  22103. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22104. if (visibility === void 0) { visibility = 1; }
  22105. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22106. };
  22107. Scene.prototype.getBoundingBoxRenderer = function () {
  22108. if (!this._boundingBoxRenderer) {
  22109. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22110. }
  22111. return this._boundingBoxRenderer;
  22112. };
  22113. Scene.prototype.getOutlineRenderer = function () {
  22114. return this._outlineRenderer;
  22115. };
  22116. Scene.prototype.getEngine = function () {
  22117. return this._engine;
  22118. };
  22119. Scene.prototype.getTotalVertices = function () {
  22120. return this._totalVertices.current;
  22121. };
  22122. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22123. get: function () {
  22124. return this._totalVertices;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Scene.prototype.getActiveIndices = function () {
  22130. return this._activeIndices.current;
  22131. };
  22132. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22133. get: function () {
  22134. return this._activeIndices;
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. Scene.prototype.getActiveParticles = function () {
  22140. return this._activeParticles.current;
  22141. };
  22142. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22143. get: function () {
  22144. return this._activeParticles;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Scene.prototype.getActiveBones = function () {
  22150. return this._activeBones.current;
  22151. };
  22152. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22153. get: function () {
  22154. return this._activeBones;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. // Stats
  22160. Scene.prototype.getInterFramePerfCounter = function () {
  22161. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22162. return 0;
  22163. };
  22164. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22165. get: function () {
  22166. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22167. return null;
  22168. },
  22169. enumerable: true,
  22170. configurable: true
  22171. });
  22172. Scene.prototype.getLastFrameDuration = function () {
  22173. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22174. return 0;
  22175. };
  22176. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22177. get: function () {
  22178. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22179. return null;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22185. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22186. return 0;
  22187. };
  22188. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22189. get: function () {
  22190. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22191. return null;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Scene.prototype.getActiveMeshes = function () {
  22197. return this._activeMeshes;
  22198. };
  22199. Scene.prototype.getRenderTargetsDuration = function () {
  22200. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22201. return 0;
  22202. };
  22203. Scene.prototype.getRenderDuration = function () {
  22204. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22205. return 0;
  22206. };
  22207. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22208. get: function () {
  22209. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22210. return null;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Scene.prototype.getParticlesDuration = function () {
  22216. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22217. return 0;
  22218. };
  22219. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22220. get: function () {
  22221. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22222. return null;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. Scene.prototype.getSpritesDuration = function () {
  22228. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22229. return 0;
  22230. };
  22231. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22232. get: function () {
  22233. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22234. return null;
  22235. },
  22236. enumerable: true,
  22237. configurable: true
  22238. });
  22239. Scene.prototype.getAnimationRatio = function () {
  22240. return this._animationRatio;
  22241. };
  22242. Scene.prototype.getRenderId = function () {
  22243. return this._renderId;
  22244. };
  22245. Scene.prototype.incrementRenderId = function () {
  22246. this._renderId++;
  22247. };
  22248. Scene.prototype._updatePointerPosition = function (evt) {
  22249. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22250. if (!canvasRect) {
  22251. return;
  22252. }
  22253. this._pointerX = evt.clientX - canvasRect.left;
  22254. this._pointerY = evt.clientY - canvasRect.top;
  22255. this._unTranslatedPointerX = this._pointerX;
  22256. this._unTranslatedPointerY = this._pointerY;
  22257. };
  22258. Scene.prototype._createUbo = function () {
  22259. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22260. this._sceneUbo.addUniform("viewProjection", 16);
  22261. this._sceneUbo.addUniform("view", 16);
  22262. };
  22263. Scene.prototype._createAlternateUbo = function () {
  22264. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22265. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22266. this._alternateSceneUbo.addUniform("view", 16);
  22267. };
  22268. // Pointers handling
  22269. /**
  22270. * Use this method to simulate a pointer move on a mesh
  22271. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22272. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22273. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22274. */
  22275. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22276. var evt = new PointerEvent("pointermove", pointerEventInit);
  22277. return this._processPointerMove(pickResult, evt);
  22278. };
  22279. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22280. var canvas = this._engine.getRenderingCanvas();
  22281. if (!canvas) {
  22282. return this;
  22283. }
  22284. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22285. this.setPointerOverSprite(null);
  22286. this.setPointerOverMesh(pickResult.pickedMesh);
  22287. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22288. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22289. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22290. }
  22291. else {
  22292. canvas.style.cursor = this.hoverCursor;
  22293. }
  22294. }
  22295. else {
  22296. canvas.style.cursor = this.defaultCursor;
  22297. }
  22298. }
  22299. else {
  22300. this.setPointerOverMesh(null);
  22301. // Sprites
  22302. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22303. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22304. this.setPointerOverSprite(pickResult.pickedSprite);
  22305. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22306. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22307. }
  22308. else {
  22309. canvas.style.cursor = this.hoverCursor;
  22310. }
  22311. }
  22312. else {
  22313. this.setPointerOverSprite(null);
  22314. // Restore pointer
  22315. canvas.style.cursor = this.defaultCursor;
  22316. }
  22317. }
  22318. if (pickResult) {
  22319. if (this.onPointerMove) {
  22320. this.onPointerMove(evt, pickResult);
  22321. }
  22322. if (this.onPointerObservable.hasObservers()) {
  22323. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22324. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22325. this.onPointerObservable.notifyObservers(pi, type);
  22326. }
  22327. }
  22328. return this;
  22329. };
  22330. /**
  22331. * Use this method to simulate a pointer down on a mesh
  22332. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22333. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22334. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22335. */
  22336. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22337. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22338. return this._processPointerDown(pickResult, evt);
  22339. };
  22340. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22341. var _this = this;
  22342. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22343. this._pickedDownMesh = pickResult.pickedMesh;
  22344. var actionManager = pickResult.pickedMesh.actionManager;
  22345. if (actionManager) {
  22346. if (actionManager.hasPickTriggers) {
  22347. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22348. switch (evt.button) {
  22349. case 0:
  22350. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22351. break;
  22352. case 1:
  22353. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22354. break;
  22355. case 2:
  22356. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22357. break;
  22358. }
  22359. }
  22360. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22361. window.setTimeout(function () {
  22362. 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);
  22363. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22364. if (_this._totalPointersPressed !== 0 &&
  22365. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22366. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22367. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22368. _this._startingPointerTime = 0;
  22369. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22370. }
  22371. }
  22372. }, Scene.LongPressDelay);
  22373. }
  22374. }
  22375. }
  22376. if (pickResult) {
  22377. if (this.onPointerDown) {
  22378. this.onPointerDown(evt, pickResult);
  22379. }
  22380. if (this.onPointerObservable.hasObservers()) {
  22381. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22383. this.onPointerObservable.notifyObservers(pi, type);
  22384. }
  22385. }
  22386. return this;
  22387. };
  22388. /**
  22389. * Use this method to simulate a pointer up on a mesh
  22390. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22391. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22392. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22393. */
  22394. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22395. var evt = new PointerEvent("pointerup", pointerEventInit);
  22396. var clickInfo = new ClickInfo();
  22397. clickInfo.singleClick = true;
  22398. clickInfo.ignore = true;
  22399. return this._processPointerUp(pickResult, evt, clickInfo);
  22400. };
  22401. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22402. if (pickResult && pickResult && pickResult.pickedMesh) {
  22403. this._pickedUpMesh = pickResult.pickedMesh;
  22404. if (this._pickedDownMesh === this._pickedUpMesh) {
  22405. if (this.onPointerPick) {
  22406. this.onPointerPick(evt, pickResult);
  22407. }
  22408. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22409. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22410. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22411. this.onPointerObservable.notifyObservers(pi, type);
  22412. }
  22413. }
  22414. if (pickResult.pickedMesh.actionManager) {
  22415. if (clickInfo.ignore) {
  22416. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22417. }
  22418. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22419. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22420. }
  22421. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22422. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22423. }
  22424. }
  22425. }
  22426. if (this._pickedDownMesh &&
  22427. this._pickedDownMesh.actionManager &&
  22428. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22429. this._pickedDownMesh !== this._pickedUpMesh) {
  22430. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22431. }
  22432. if (this.onPointerUp) {
  22433. this.onPointerUp(evt, pickResult);
  22434. }
  22435. if (this.onPointerObservable.hasObservers()) {
  22436. if (!clickInfo.ignore) {
  22437. if (!clickInfo.hasSwiped) {
  22438. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22439. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22440. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22441. this.onPointerObservable.notifyObservers(pi, type);
  22442. }
  22443. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22444. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22445. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22446. this.onPointerObservable.notifyObservers(pi, type);
  22447. }
  22448. }
  22449. }
  22450. else {
  22451. var type = BABYLON.PointerEventTypes.POINTERUP;
  22452. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22453. this.onPointerObservable.notifyObservers(pi, type);
  22454. }
  22455. }
  22456. return this;
  22457. };
  22458. /**
  22459. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22460. * @param attachUp defines if you want to attach events to pointerup
  22461. * @param attachDown defines if you want to attach events to pointerdown
  22462. * @param attachMove defines if you want to attach events to pointermove
  22463. */
  22464. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22465. var _this = this;
  22466. if (attachUp === void 0) { attachUp = true; }
  22467. if (attachDown === void 0) { attachDown = true; }
  22468. if (attachMove === void 0) { attachMove = true; }
  22469. this._initActionManager = function (act, clickInfo) {
  22470. if (!_this._meshPickProceed) {
  22471. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22472. _this._currentPickResult = pickResult;
  22473. if (pickResult) {
  22474. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22475. }
  22476. _this._meshPickProceed = true;
  22477. }
  22478. return act;
  22479. };
  22480. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22481. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22482. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22483. btn !== _this._previousButtonPressed) {
  22484. _this._doubleClickOccured = false;
  22485. clickInfo.singleClick = true;
  22486. clickInfo.ignore = false;
  22487. cb(clickInfo, _this._currentPickResult);
  22488. }
  22489. };
  22490. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22491. var clickInfo = new ClickInfo();
  22492. _this._currentPickResult = null;
  22493. var act = null;
  22494. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22495. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22496. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22497. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22498. act = _this._initActionManager(act, clickInfo);
  22499. if (act)
  22500. checkPicking = act.hasPickTriggers;
  22501. }
  22502. if (checkPicking) {
  22503. var btn = evt.button;
  22504. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22505. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22506. if (!clickInfo.hasSwiped) {
  22507. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22508. if (!checkSingleClickImmediately) {
  22509. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22510. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22511. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22512. act = _this._initActionManager(act, clickInfo);
  22513. if (act)
  22514. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22515. }
  22516. }
  22517. if (checkSingleClickImmediately) {
  22518. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22519. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22520. btn !== _this._previousButtonPressed) {
  22521. clickInfo.singleClick = true;
  22522. cb(clickInfo, _this._currentPickResult);
  22523. }
  22524. }
  22525. else {
  22526. // wait that no double click has been raised during the double click delay
  22527. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22528. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22529. }
  22530. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22531. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22532. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22533. act = _this._initActionManager(act, clickInfo);
  22534. if (act)
  22535. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22536. }
  22537. if (checkDoubleClick) {
  22538. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22539. if (btn === _this._previousButtonPressed &&
  22540. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22541. !_this._doubleClickOccured) {
  22542. // pointer has not moved for 2 clicks, it's a double click
  22543. if (!clickInfo.hasSwiped &&
  22544. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22545. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22546. _this._previousStartingPointerTime = 0;
  22547. _this._doubleClickOccured = true;
  22548. clickInfo.doubleClick = true;
  22549. clickInfo.ignore = false;
  22550. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22551. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22552. }
  22553. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22554. cb(clickInfo, _this._currentPickResult);
  22555. }
  22556. else {
  22557. _this._doubleClickOccured = false;
  22558. _this._previousStartingPointerTime = _this._startingPointerTime;
  22559. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22560. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22561. _this._previousButtonPressed = btn;
  22562. if (Scene.ExclusiveDoubleClickMode) {
  22563. if (_this._previousDelayedSimpleClickTimeout) {
  22564. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22565. }
  22566. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22567. cb(clickInfo, _this._previousPickResult);
  22568. }
  22569. else {
  22570. cb(clickInfo, _this._currentPickResult);
  22571. }
  22572. }
  22573. }
  22574. else {
  22575. _this._doubleClickOccured = false;
  22576. _this._previousStartingPointerTime = _this._startingPointerTime;
  22577. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22578. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22579. _this._previousButtonPressed = btn;
  22580. }
  22581. }
  22582. }
  22583. }
  22584. clickInfo.ignore = true;
  22585. cb(clickInfo, _this._currentPickResult);
  22586. };
  22587. this._spritePredicate = function (sprite) {
  22588. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22589. };
  22590. this._onPointerMove = function (evt) {
  22591. _this._updatePointerPosition(evt);
  22592. // PreObservable support
  22593. if (_this.onPrePointerObservable.hasObservers()) {
  22594. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22595. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22596. _this.onPrePointerObservable.notifyObservers(pi, type);
  22597. if (pi.skipOnPointerObservable) {
  22598. return;
  22599. }
  22600. }
  22601. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22602. return;
  22603. }
  22604. if (!_this.pointerMovePredicate) {
  22605. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22606. }
  22607. // Meshes
  22608. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22609. _this._processPointerMove(pickResult, evt);
  22610. };
  22611. this._onPointerDown = function (evt) {
  22612. _this._totalPointersPressed++;
  22613. _this._pickedDownMesh = null;
  22614. _this._meshPickProceed = false;
  22615. _this._updatePointerPosition(evt);
  22616. if (_this.preventDefaultOnPointerDown && canvas) {
  22617. evt.preventDefault();
  22618. canvas.focus();
  22619. }
  22620. // PreObservable support
  22621. if (_this.onPrePointerObservable.hasObservers()) {
  22622. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22623. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22624. _this.onPrePointerObservable.notifyObservers(pi, type);
  22625. if (pi.skipOnPointerObservable) {
  22626. return;
  22627. }
  22628. }
  22629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22630. return;
  22631. }
  22632. _this._startingPointerPosition.x = _this._pointerX;
  22633. _this._startingPointerPosition.y = _this._pointerY;
  22634. _this._startingPointerTime = new Date().getTime();
  22635. if (!_this.pointerDownPredicate) {
  22636. _this.pointerDownPredicate = function (mesh) {
  22637. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22638. };
  22639. }
  22640. // Meshes
  22641. _this._pickedDownMesh = null;
  22642. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22643. _this._processPointerDown(pickResult, evt);
  22644. // Sprites
  22645. _this._pickedDownSprite = null;
  22646. if (_this.spriteManagers.length > 0) {
  22647. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22648. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22649. if (pickResult.pickedSprite.actionManager) {
  22650. _this._pickedDownSprite = pickResult.pickedSprite;
  22651. switch (evt.button) {
  22652. case 0:
  22653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22654. break;
  22655. case 1:
  22656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22657. break;
  22658. case 2:
  22659. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22660. break;
  22661. }
  22662. if (pickResult.pickedSprite.actionManager) {
  22663. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22664. }
  22665. }
  22666. }
  22667. }
  22668. };
  22669. this._onPointerUp = function (evt) {
  22670. if (_this._totalPointersPressed === 0) {
  22671. return; // So we need to test it the pointer down was pressed before.
  22672. }
  22673. _this._totalPointersPressed--;
  22674. _this._pickedUpMesh = null;
  22675. _this._meshPickProceed = false;
  22676. _this._updatePointerPosition(evt);
  22677. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22678. // PreObservable support
  22679. if (_this.onPrePointerObservable.hasObservers()) {
  22680. if (!clickInfo.ignore) {
  22681. if (!clickInfo.hasSwiped) {
  22682. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22683. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22684. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22685. _this.onPrePointerObservable.notifyObservers(pi, type);
  22686. if (pi.skipOnPointerObservable) {
  22687. return;
  22688. }
  22689. }
  22690. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22691. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22692. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22693. _this.onPrePointerObservable.notifyObservers(pi, type);
  22694. if (pi.skipOnPointerObservable) {
  22695. return;
  22696. }
  22697. }
  22698. }
  22699. }
  22700. else {
  22701. var type = BABYLON.PointerEventTypes.POINTERUP;
  22702. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22703. _this.onPrePointerObservable.notifyObservers(pi, type);
  22704. if (pi.skipOnPointerObservable) {
  22705. return;
  22706. }
  22707. }
  22708. }
  22709. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22710. return;
  22711. }
  22712. if (!_this.pointerUpPredicate) {
  22713. _this.pointerUpPredicate = function (mesh) {
  22714. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22715. };
  22716. }
  22717. // Meshes
  22718. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22719. _this._initActionManager(null, clickInfo);
  22720. }
  22721. if (!pickResult) {
  22722. pickResult = _this._currentPickResult;
  22723. }
  22724. _this._processPointerUp(pickResult, evt, clickInfo);
  22725. // Sprites
  22726. if (_this.spriteManagers.length > 0) {
  22727. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22728. if (spritePickResult) {
  22729. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22730. if (spritePickResult.pickedSprite.actionManager) {
  22731. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22732. if (spritePickResult.pickedSprite.actionManager) {
  22733. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22734. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22735. }
  22736. }
  22737. }
  22738. }
  22739. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22740. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22741. }
  22742. }
  22743. }
  22744. _this._previousPickResult = _this._currentPickResult;
  22745. });
  22746. };
  22747. this._onKeyDown = function (evt) {
  22748. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22749. if (_this.onPreKeyboardObservable.hasObservers()) {
  22750. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22751. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22752. if (pi.skipOnPointerObservable) {
  22753. return;
  22754. }
  22755. }
  22756. if (_this.onKeyboardObservable.hasObservers()) {
  22757. var pi = new BABYLON.KeyboardInfo(type, evt);
  22758. _this.onKeyboardObservable.notifyObservers(pi, type);
  22759. }
  22760. if (_this.actionManager) {
  22761. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22762. }
  22763. };
  22764. this._onKeyUp = function (evt) {
  22765. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22766. if (_this.onPreKeyboardObservable.hasObservers()) {
  22767. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22768. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22769. if (pi.skipOnPointerObservable) {
  22770. return;
  22771. }
  22772. }
  22773. if (_this.onKeyboardObservable.hasObservers()) {
  22774. var pi = new BABYLON.KeyboardInfo(type, evt);
  22775. _this.onKeyboardObservable.notifyObservers(pi, type);
  22776. }
  22777. if (_this.actionManager) {
  22778. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22779. }
  22780. };
  22781. var engine = this.getEngine();
  22782. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22783. if (!canvas) {
  22784. return;
  22785. }
  22786. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22787. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22788. });
  22789. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22790. if (!canvas) {
  22791. return;
  22792. }
  22793. canvas.removeEventListener("keydown", _this._onKeyDown);
  22794. canvas.removeEventListener("keyup", _this._onKeyUp);
  22795. });
  22796. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22797. var canvas = this._engine.getRenderingCanvas();
  22798. if (!canvas) {
  22799. return;
  22800. }
  22801. if (attachMove) {
  22802. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22803. // Wheel
  22804. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22805. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22806. }
  22807. if (attachDown) {
  22808. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22809. }
  22810. if (attachUp) {
  22811. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22812. }
  22813. canvas.tabIndex = 1;
  22814. };
  22815. Scene.prototype.detachControl = function () {
  22816. var engine = this.getEngine();
  22817. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22818. var canvas = engine.getRenderingCanvas();
  22819. if (!canvas) {
  22820. return;
  22821. }
  22822. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22823. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22824. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22825. if (this._onCanvasBlurObserver) {
  22826. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22827. }
  22828. if (this._onCanvasFocusObserver) {
  22829. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22830. }
  22831. // Wheel
  22832. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22833. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22834. // Keyboard
  22835. canvas.removeEventListener("keydown", this._onKeyDown);
  22836. canvas.removeEventListener("keyup", this._onKeyUp);
  22837. // Observables
  22838. this.onKeyboardObservable.clear();
  22839. this.onPreKeyboardObservable.clear();
  22840. this.onPointerObservable.clear();
  22841. this.onPrePointerObservable.clear();
  22842. };
  22843. /**
  22844. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22845. * Delay loaded resources are not taking in account
  22846. * @return true if all required resources are ready
  22847. */
  22848. Scene.prototype.isReady = function () {
  22849. if (this._isDisposed) {
  22850. return false;
  22851. }
  22852. if (this._pendingData.length > 0) {
  22853. return false;
  22854. }
  22855. var index;
  22856. var engine = this.getEngine();
  22857. // Geometries
  22858. for (index = 0; index < this._geometries.length; index++) {
  22859. var geometry = this._geometries[index];
  22860. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22861. return false;
  22862. }
  22863. }
  22864. // Meshes
  22865. for (index = 0; index < this.meshes.length; index++) {
  22866. var mesh = this.meshes[index];
  22867. if (!mesh.isEnabled()) {
  22868. continue;
  22869. }
  22870. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22871. continue;
  22872. }
  22873. if (!mesh.isReady(true)) {
  22874. return false;
  22875. }
  22876. // Effect layers
  22877. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22878. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22879. var layer = _a[_i];
  22880. if (!layer.hasMesh(mesh)) {
  22881. continue;
  22882. }
  22883. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22884. var subMesh = _c[_b];
  22885. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22886. return false;
  22887. }
  22888. }
  22889. }
  22890. }
  22891. return true;
  22892. };
  22893. Scene.prototype.resetCachedMaterial = function () {
  22894. this._cachedMaterial = null;
  22895. this._cachedEffect = null;
  22896. this._cachedVisibility = null;
  22897. };
  22898. Scene.prototype.registerBeforeRender = function (func) {
  22899. this.onBeforeRenderObservable.add(func);
  22900. };
  22901. Scene.prototype.unregisterBeforeRender = function (func) {
  22902. this.onBeforeRenderObservable.removeCallback(func);
  22903. };
  22904. Scene.prototype.registerAfterRender = function (func) {
  22905. this.onAfterRenderObservable.add(func);
  22906. };
  22907. Scene.prototype.unregisterAfterRender = function (func) {
  22908. this.onAfterRenderObservable.removeCallback(func);
  22909. };
  22910. Scene.prototype._executeOnceBeforeRender = function (func) {
  22911. var _this = this;
  22912. var execFunc = function () {
  22913. func();
  22914. setTimeout(function () {
  22915. _this.unregisterBeforeRender(execFunc);
  22916. });
  22917. };
  22918. this.registerBeforeRender(execFunc);
  22919. };
  22920. /**
  22921. * The provided function will run before render once and will be disposed afterwards.
  22922. * A timeout delay can be provided so that the function will be executed in N ms.
  22923. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22924. * @param func The function to be executed.
  22925. * @param timeout optional delay in ms
  22926. */
  22927. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22928. var _this = this;
  22929. if (timeout !== undefined) {
  22930. setTimeout(function () {
  22931. _this._executeOnceBeforeRender(func);
  22932. }, timeout);
  22933. }
  22934. else {
  22935. this._executeOnceBeforeRender(func);
  22936. }
  22937. };
  22938. Scene.prototype._addPendingData = function (data) {
  22939. this._pendingData.push(data);
  22940. };
  22941. Scene.prototype._removePendingData = function (data) {
  22942. var wasLoading = this.isLoading;
  22943. var index = this._pendingData.indexOf(data);
  22944. if (index !== -1) {
  22945. this._pendingData.splice(index, 1);
  22946. }
  22947. if (wasLoading && !this.isLoading) {
  22948. this.onDataLoadedObservable.notifyObservers(this);
  22949. }
  22950. };
  22951. Scene.prototype.getWaitingItemsCount = function () {
  22952. return this._pendingData.length;
  22953. };
  22954. Object.defineProperty(Scene.prototype, "isLoading", {
  22955. get: function () {
  22956. return this._pendingData.length > 0;
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. /**
  22962. * Registers a function to be executed when the scene is ready.
  22963. * @param {Function} func - the function to be executed.
  22964. */
  22965. Scene.prototype.executeWhenReady = function (func) {
  22966. var _this = this;
  22967. this.onReadyObservable.add(func);
  22968. if (this._executeWhenReadyTimeoutId !== -1) {
  22969. return;
  22970. }
  22971. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22972. _this._checkIsReady();
  22973. }, 150);
  22974. };
  22975. /**
  22976. * Returns a promise that resolves when the scene is ready.
  22977. * @returns A promise that resolves when the scene is ready.
  22978. */
  22979. Scene.prototype.whenReadyAsync = function () {
  22980. var _this = this;
  22981. return new Promise(function (resolve) {
  22982. _this.executeWhenReady(function () {
  22983. resolve();
  22984. });
  22985. });
  22986. };
  22987. Scene.prototype._checkIsReady = function () {
  22988. var _this = this;
  22989. if (this.isReady()) {
  22990. this.onReadyObservable.notifyObservers(this);
  22991. this.onReadyObservable.clear();
  22992. this._executeWhenReadyTimeoutId = -1;
  22993. return;
  22994. }
  22995. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22996. _this._checkIsReady();
  22997. }, 150);
  22998. };
  22999. // Animations
  23000. /**
  23001. * Will start the animation sequence of a given target
  23002. * @param target - the target
  23003. * @param {number} from - from which frame should animation start
  23004. * @param {number} to - till which frame should animation run.
  23005. * @param {boolean} [loop] - should the animation loop
  23006. * @param {number} [speedRatio] - the speed in which to run the animation
  23007. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23008. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23009. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23010. * See BABYLON.Animatable
  23011. */
  23012. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23013. if (speedRatio === void 0) { speedRatio = 1.0; }
  23014. if (from > to && speedRatio > 0) {
  23015. speedRatio *= -1;
  23016. }
  23017. this.stopAnimation(target);
  23018. if (!animatable) {
  23019. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23020. }
  23021. // Local animations
  23022. if (target.animations) {
  23023. animatable.appendAnimations(target, target.animations);
  23024. }
  23025. // Children animations
  23026. if (target.getAnimatables) {
  23027. var animatables = target.getAnimatables();
  23028. for (var index = 0; index < animatables.length; index++) {
  23029. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23030. }
  23031. }
  23032. animatable.reset();
  23033. return animatable;
  23034. };
  23035. /**
  23036. * Begin a new animation on a given node
  23037. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23038. * @param {BABYLON.Animation[]} defines the list of animations to start
  23039. * @param {number} from defines the initial value
  23040. * @param {number} to defines the final value
  23041. * @param {boolean} loop defines if you want animation to loop (off by default)
  23042. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23043. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23044. * @returns the list of created animatables
  23045. */
  23046. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23047. if (speedRatio === undefined) {
  23048. speedRatio = 1.0;
  23049. }
  23050. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23051. return animatable;
  23052. };
  23053. /**
  23054. * Begin a new animation on a given node and its hierarchy
  23055. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23056. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  23057. * @param {BABYLON.Animation[]} defines the list of animations to start
  23058. * @param {number} from defines the initial value
  23059. * @param {number} to defines the final value
  23060. * @param {boolean} loop defines if you want animation to loop (off by default)
  23061. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23062. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23063. * @returns the list of animatables created for all nodes
  23064. */
  23065. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23066. var children = target.getDescendants(directDescendantsOnly);
  23067. var result = [];
  23068. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23069. var child = children_1[_i];
  23070. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23071. }
  23072. return result;
  23073. };
  23074. Scene.prototype.getAnimatableByTarget = function (target) {
  23075. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23076. if (this._activeAnimatables[index].target === target) {
  23077. return this._activeAnimatables[index];
  23078. }
  23079. }
  23080. return null;
  23081. };
  23082. Object.defineProperty(Scene.prototype, "animatables", {
  23083. get: function () {
  23084. return this._activeAnimatables;
  23085. },
  23086. enumerable: true,
  23087. configurable: true
  23088. });
  23089. /**
  23090. * Will stop the animation of the given target
  23091. * @param target - the target
  23092. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23093. * @see beginAnimation
  23094. */
  23095. Scene.prototype.stopAnimation = function (target, animationName) {
  23096. var animatable = this.getAnimatableByTarget(target);
  23097. if (animatable) {
  23098. animatable.stop(animationName);
  23099. }
  23100. };
  23101. /**
  23102. * Stops and removes all animations that have been applied to the scene
  23103. */
  23104. Scene.prototype.stopAllAnimations = function () {
  23105. if (this._activeAnimatables) {
  23106. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23107. this._activeAnimatables[i].stop();
  23108. }
  23109. this._activeAnimatables = [];
  23110. }
  23111. };
  23112. Scene.prototype._animate = function () {
  23113. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23114. return;
  23115. }
  23116. // Getting time
  23117. var now = BABYLON.Tools.Now;
  23118. if (!this._animationTimeLast) {
  23119. if (this._pendingData.length > 0) {
  23120. return;
  23121. }
  23122. this._animationTimeLast = now;
  23123. }
  23124. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23125. this._animationTime += deltaTime;
  23126. this._animationTimeLast = now;
  23127. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23128. this._activeAnimatables[index]._animate(this._animationTime);
  23129. }
  23130. };
  23131. // Matrix
  23132. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23133. this._useAlternateCameraConfiguration = active;
  23134. };
  23135. Scene.prototype.getViewMatrix = function () {
  23136. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23137. };
  23138. Scene.prototype.getProjectionMatrix = function () {
  23139. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23140. };
  23141. Scene.prototype.getTransformMatrix = function () {
  23142. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23143. };
  23144. Scene.prototype.setTransformMatrix = function (view, projection) {
  23145. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23146. return;
  23147. }
  23148. this._viewUpdateFlag = view.updateFlag;
  23149. this._projectionUpdateFlag = projection.updateFlag;
  23150. this._viewMatrix = view;
  23151. this._projectionMatrix = projection;
  23152. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23153. // Update frustum
  23154. if (!this._frustumPlanes) {
  23155. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23156. }
  23157. else {
  23158. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23159. }
  23160. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23161. var otherCamera = this.activeCamera._alternateCamera;
  23162. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23163. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23164. }
  23165. if (this._sceneUbo.useUbo) {
  23166. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23167. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23168. this._sceneUbo.update();
  23169. }
  23170. };
  23171. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23172. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23173. return;
  23174. }
  23175. this._alternateViewUpdateFlag = view.updateFlag;
  23176. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23177. this._alternateViewMatrix = view;
  23178. this._alternateProjectionMatrix = projection;
  23179. if (!this._alternateTransformMatrix) {
  23180. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23181. }
  23182. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23183. if (!this._alternateSceneUbo) {
  23184. this._createAlternateUbo();
  23185. }
  23186. if (this._alternateSceneUbo.useUbo) {
  23187. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23188. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23189. this._alternateSceneUbo.update();
  23190. }
  23191. };
  23192. Scene.prototype.getSceneUniformBuffer = function () {
  23193. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23194. };
  23195. // Methods
  23196. Scene.prototype.getUniqueId = function () {
  23197. var result = Scene._uniqueIdCounter;
  23198. Scene._uniqueIdCounter++;
  23199. return result;
  23200. };
  23201. Scene.prototype.addMesh = function (newMesh) {
  23202. this.meshes.push(newMesh);
  23203. //notify the collision coordinator
  23204. if (this.collisionCoordinator) {
  23205. this.collisionCoordinator.onMeshAdded(newMesh);
  23206. }
  23207. newMesh._resyncLightSources();
  23208. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23209. };
  23210. Scene.prototype.removeMesh = function (toRemove) {
  23211. var index = this.meshes.indexOf(toRemove);
  23212. if (index !== -1) {
  23213. // Remove from the scene if mesh found
  23214. this.meshes.splice(index, 1);
  23215. }
  23216. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23217. return index;
  23218. };
  23219. Scene.prototype.addTransformNode = function (newTransformNode) {
  23220. this.transformNodes.push(newTransformNode);
  23221. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23222. };
  23223. Scene.prototype.removeTransformNode = function (toRemove) {
  23224. var index = this.transformNodes.indexOf(toRemove);
  23225. if (index !== -1) {
  23226. // Remove from the scene if found
  23227. this.transformNodes.splice(index, 1);
  23228. }
  23229. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23230. return index;
  23231. };
  23232. Scene.prototype.removeSkeleton = function (toRemove) {
  23233. var index = this.skeletons.indexOf(toRemove);
  23234. if (index !== -1) {
  23235. // Remove from the scene if found
  23236. this.skeletons.splice(index, 1);
  23237. }
  23238. return index;
  23239. };
  23240. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23241. var index = this.morphTargetManagers.indexOf(toRemove);
  23242. if (index !== -1) {
  23243. // Remove from the scene if found
  23244. this.morphTargetManagers.splice(index, 1);
  23245. }
  23246. return index;
  23247. };
  23248. Scene.prototype.removeLight = function (toRemove) {
  23249. var index = this.lights.indexOf(toRemove);
  23250. if (index !== -1) {
  23251. // Remove from meshes
  23252. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23253. var mesh = _a[_i];
  23254. mesh._removeLightSource(toRemove);
  23255. }
  23256. // Remove from the scene if mesh found
  23257. this.lights.splice(index, 1);
  23258. this.sortLightsByPriority();
  23259. }
  23260. this.onLightRemovedObservable.notifyObservers(toRemove);
  23261. return index;
  23262. };
  23263. Scene.prototype.removeCamera = function (toRemove) {
  23264. var index = this.cameras.indexOf(toRemove);
  23265. if (index !== -1) {
  23266. // Remove from the scene if mesh found
  23267. this.cameras.splice(index, 1);
  23268. }
  23269. // Remove from activeCameras
  23270. var index2 = this.activeCameras.indexOf(toRemove);
  23271. if (index2 !== -1) {
  23272. // Remove from the scene if mesh found
  23273. this.activeCameras.splice(index2, 1);
  23274. }
  23275. // Reset the activeCamera
  23276. if (this.activeCamera === toRemove) {
  23277. if (this.cameras.length > 0) {
  23278. this.activeCamera = this.cameras[0];
  23279. }
  23280. else {
  23281. this.activeCamera = null;
  23282. }
  23283. }
  23284. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23285. return index;
  23286. };
  23287. Scene.prototype.removeParticleSystem = function (toRemove) {
  23288. var index = this.particleSystems.indexOf(toRemove);
  23289. if (index !== -1) {
  23290. this.particleSystems.splice(index, 1);
  23291. }
  23292. return index;
  23293. };
  23294. ;
  23295. Scene.prototype.removeAnimation = function (toRemove) {
  23296. var index = this.animations.indexOf(toRemove);
  23297. if (index !== -1) {
  23298. this.animations.splice(index, 1);
  23299. }
  23300. return index;
  23301. };
  23302. ;
  23303. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23304. var index = this.multiMaterials.indexOf(toRemove);
  23305. if (index !== -1) {
  23306. this.multiMaterials.splice(index, 1);
  23307. }
  23308. return index;
  23309. };
  23310. ;
  23311. Scene.prototype.removeMaterial = function (toRemove) {
  23312. var index = this.materials.indexOf(toRemove);
  23313. if (index !== -1) {
  23314. this.materials.splice(index, 1);
  23315. }
  23316. return index;
  23317. };
  23318. ;
  23319. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23320. var index = this.lensFlareSystems.indexOf(toRemove);
  23321. if (index !== -1) {
  23322. this.lensFlareSystems.splice(index, 1);
  23323. }
  23324. return index;
  23325. };
  23326. ;
  23327. Scene.prototype.removeActionManager = function (toRemove) {
  23328. var index = this._actionManagers.indexOf(toRemove);
  23329. if (index !== -1) {
  23330. this._actionManagers.splice(index, 1);
  23331. }
  23332. return index;
  23333. };
  23334. ;
  23335. Scene.prototype.addLight = function (newLight) {
  23336. this.lights.push(newLight);
  23337. this.sortLightsByPriority();
  23338. // Add light to all meshes (To support if the light is removed and then readded)
  23339. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23340. var mesh = _a[_i];
  23341. if (mesh._lightSources.indexOf(newLight) === -1) {
  23342. mesh._lightSources.push(newLight);
  23343. mesh._resyncLightSources();
  23344. }
  23345. }
  23346. this.onNewLightAddedObservable.notifyObservers(newLight);
  23347. };
  23348. Scene.prototype.sortLightsByPriority = function () {
  23349. if (this.requireLightSorting) {
  23350. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23351. }
  23352. };
  23353. Scene.prototype.addCamera = function (newCamera) {
  23354. this.cameras.push(newCamera);
  23355. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23356. };
  23357. Scene.prototype.addSkeleton = function (newSkeleton) {
  23358. this.skeletons.push(newSkeleton);
  23359. };
  23360. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23361. this.particleSystems.push(newParticleSystem);
  23362. };
  23363. Scene.prototype.addAnimation = function (newAnimation) {
  23364. this.animations.push(newAnimation);
  23365. };
  23366. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23367. this.multiMaterials.push(newMultiMaterial);
  23368. };
  23369. Scene.prototype.addMaterial = function (newMaterial) {
  23370. this.materials.push(newMaterial);
  23371. };
  23372. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23373. this.morphTargetManagers.push(newMorphTargetManager);
  23374. };
  23375. Scene.prototype.addGeometry = function (newGeometrie) {
  23376. this._geometries.push(newGeometrie);
  23377. };
  23378. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23379. this.lensFlareSystems.push(newLensFlareSystem);
  23380. };
  23381. Scene.prototype.addActionManager = function (newActionManager) {
  23382. this._actionManagers.push(newActionManager);
  23383. };
  23384. /**
  23385. * Switch active camera
  23386. * @param {Camera} newCamera - new active camera
  23387. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23388. */
  23389. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23390. if (attachControl === void 0) { attachControl = true; }
  23391. var canvas = this._engine.getRenderingCanvas();
  23392. if (!canvas) {
  23393. return;
  23394. }
  23395. if (this.activeCamera) {
  23396. this.activeCamera.detachControl(canvas);
  23397. }
  23398. this.activeCamera = newCamera;
  23399. if (attachControl) {
  23400. newCamera.attachControl(canvas);
  23401. }
  23402. };
  23403. /**
  23404. * sets the active camera of the scene using its ID
  23405. * @param {string} id - the camera's ID
  23406. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23407. * @see activeCamera
  23408. */
  23409. Scene.prototype.setActiveCameraByID = function (id) {
  23410. var camera = this.getCameraByID(id);
  23411. if (camera) {
  23412. this.activeCamera = camera;
  23413. return camera;
  23414. }
  23415. return null;
  23416. };
  23417. /**
  23418. * sets the active camera of the scene using its name
  23419. * @param {string} name - the camera's name
  23420. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23421. * @see activeCamera
  23422. */
  23423. Scene.prototype.setActiveCameraByName = function (name) {
  23424. var camera = this.getCameraByName(name);
  23425. if (camera) {
  23426. this.activeCamera = camera;
  23427. return camera;
  23428. }
  23429. return null;
  23430. };
  23431. /**
  23432. * get an animation group using its name
  23433. * @param {string} the material's name
  23434. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23435. */
  23436. Scene.prototype.getAnimationGroupByName = function (name) {
  23437. for (var index = 0; index < this.animationGroups.length; index++) {
  23438. if (this.animationGroups[index].name === name) {
  23439. return this.animationGroups[index];
  23440. }
  23441. }
  23442. return null;
  23443. };
  23444. /**
  23445. * get a material using its id
  23446. * @param {string} the material's ID
  23447. * @return {BABYLON.Material|null} the material or null if none found.
  23448. */
  23449. Scene.prototype.getMaterialByID = function (id) {
  23450. for (var index = 0; index < this.materials.length; index++) {
  23451. if (this.materials[index].id === id) {
  23452. return this.materials[index];
  23453. }
  23454. }
  23455. return null;
  23456. };
  23457. /**
  23458. * get a material using its name
  23459. * @param {string} the material's name
  23460. * @return {BABYLON.Material|null} the material or null if none found.
  23461. */
  23462. Scene.prototype.getMaterialByName = function (name) {
  23463. for (var index = 0; index < this.materials.length; index++) {
  23464. if (this.materials[index].name === name) {
  23465. return this.materials[index];
  23466. }
  23467. }
  23468. return null;
  23469. };
  23470. Scene.prototype.getLensFlareSystemByName = function (name) {
  23471. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23472. if (this.lensFlareSystems[index].name === name) {
  23473. return this.lensFlareSystems[index];
  23474. }
  23475. }
  23476. return null;
  23477. };
  23478. Scene.prototype.getLensFlareSystemByID = function (id) {
  23479. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23480. if (this.lensFlareSystems[index].id === id) {
  23481. return this.lensFlareSystems[index];
  23482. }
  23483. }
  23484. return null;
  23485. };
  23486. Scene.prototype.getCameraByID = function (id) {
  23487. for (var index = 0; index < this.cameras.length; index++) {
  23488. if (this.cameras[index].id === id) {
  23489. return this.cameras[index];
  23490. }
  23491. }
  23492. return null;
  23493. };
  23494. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23495. for (var index = 0; index < this.cameras.length; index++) {
  23496. if (this.cameras[index].uniqueId === uniqueId) {
  23497. return this.cameras[index];
  23498. }
  23499. }
  23500. return null;
  23501. };
  23502. /**
  23503. * get a camera using its name
  23504. * @param {string} the camera's name
  23505. * @return {BABYLON.Camera|null} the camera or null if none found.
  23506. */
  23507. Scene.prototype.getCameraByName = function (name) {
  23508. for (var index = 0; index < this.cameras.length; index++) {
  23509. if (this.cameras[index].name === name) {
  23510. return this.cameras[index];
  23511. }
  23512. }
  23513. return null;
  23514. };
  23515. /**
  23516. * get a bone using its id
  23517. * @param {string} the bone's id
  23518. * @return {BABYLON.Bone|null} the bone or null if not found
  23519. */
  23520. Scene.prototype.getBoneByID = function (id) {
  23521. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23522. var skeleton = this.skeletons[skeletonIndex];
  23523. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23524. if (skeleton.bones[boneIndex].id === id) {
  23525. return skeleton.bones[boneIndex];
  23526. }
  23527. }
  23528. }
  23529. return null;
  23530. };
  23531. /**
  23532. * get a bone using its id
  23533. * @param {string} the bone's name
  23534. * @return {BABYLON.Bone|null} the bone or null if not found
  23535. */
  23536. Scene.prototype.getBoneByName = function (name) {
  23537. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23538. var skeleton = this.skeletons[skeletonIndex];
  23539. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23540. if (skeleton.bones[boneIndex].name === name) {
  23541. return skeleton.bones[boneIndex];
  23542. }
  23543. }
  23544. }
  23545. return null;
  23546. };
  23547. /**
  23548. * get a light node using its name
  23549. * @param {string} the light's name
  23550. * @return {BABYLON.Light|null} the light or null if none found.
  23551. */
  23552. Scene.prototype.getLightByName = function (name) {
  23553. for (var index = 0; index < this.lights.length; index++) {
  23554. if (this.lights[index].name === name) {
  23555. return this.lights[index];
  23556. }
  23557. }
  23558. return null;
  23559. };
  23560. /**
  23561. * get a light node using its ID
  23562. * @param {string} the light's id
  23563. * @return {BABYLON.Light|null} the light or null if none found.
  23564. */
  23565. Scene.prototype.getLightByID = function (id) {
  23566. for (var index = 0; index < this.lights.length; index++) {
  23567. if (this.lights[index].id === id) {
  23568. return this.lights[index];
  23569. }
  23570. }
  23571. return null;
  23572. };
  23573. /**
  23574. * get a light node using its scene-generated unique ID
  23575. * @param {number} the light's unique id
  23576. * @return {BABYLON.Light|null} the light or null if none found.
  23577. */
  23578. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23579. for (var index = 0; index < this.lights.length; index++) {
  23580. if (this.lights[index].uniqueId === uniqueId) {
  23581. return this.lights[index];
  23582. }
  23583. }
  23584. return null;
  23585. };
  23586. /**
  23587. * get a particle system by id
  23588. * @param id {number} the particle system id
  23589. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23590. */
  23591. Scene.prototype.getParticleSystemByID = function (id) {
  23592. for (var index = 0; index < this.particleSystems.length; index++) {
  23593. if (this.particleSystems[index].id === id) {
  23594. return this.particleSystems[index];
  23595. }
  23596. }
  23597. return null;
  23598. };
  23599. /**
  23600. * get a geometry using its ID
  23601. * @param {string} the geometry's id
  23602. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23603. */
  23604. Scene.prototype.getGeometryByID = function (id) {
  23605. for (var index = 0; index < this._geometries.length; index++) {
  23606. if (this._geometries[index].id === id) {
  23607. return this._geometries[index];
  23608. }
  23609. }
  23610. return null;
  23611. };
  23612. /**
  23613. * add a new geometry to this scene.
  23614. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23615. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23616. * @return {boolean} was the geometry added or not
  23617. */
  23618. Scene.prototype.pushGeometry = function (geometry, force) {
  23619. if (!force && this.getGeometryByID(geometry.id)) {
  23620. return false;
  23621. }
  23622. this._geometries.push(geometry);
  23623. //notify the collision coordinator
  23624. if (this.collisionCoordinator) {
  23625. this.collisionCoordinator.onGeometryAdded(geometry);
  23626. }
  23627. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23628. return true;
  23629. };
  23630. /**
  23631. * Removes an existing geometry
  23632. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23633. * @return {boolean} was the geometry removed or not
  23634. */
  23635. Scene.prototype.removeGeometry = function (geometry) {
  23636. var index = this._geometries.indexOf(geometry);
  23637. if (index > -1) {
  23638. this._geometries.splice(index, 1);
  23639. //notify the collision coordinator
  23640. if (this.collisionCoordinator) {
  23641. this.collisionCoordinator.onGeometryDeleted(geometry);
  23642. }
  23643. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23644. return true;
  23645. }
  23646. return false;
  23647. };
  23648. Scene.prototype.getGeometries = function () {
  23649. return this._geometries;
  23650. };
  23651. /**
  23652. * Get the first added mesh found of a given ID
  23653. * @param {string} id - the id to search for
  23654. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23655. */
  23656. Scene.prototype.getMeshByID = function (id) {
  23657. for (var index = 0; index < this.meshes.length; index++) {
  23658. if (this.meshes[index].id === id) {
  23659. return this.meshes[index];
  23660. }
  23661. }
  23662. return null;
  23663. };
  23664. Scene.prototype.getMeshesByID = function (id) {
  23665. return this.meshes.filter(function (m) {
  23666. return m.id === id;
  23667. });
  23668. };
  23669. /**
  23670. * Get the first added transform node found of a given ID
  23671. * @param {string} id - the id to search for
  23672. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23673. */
  23674. Scene.prototype.getTransformNodeByID = function (id) {
  23675. for (var index = 0; index < this.transformNodes.length; index++) {
  23676. if (this.transformNodes[index].id === id) {
  23677. return this.transformNodes[index];
  23678. }
  23679. }
  23680. return null;
  23681. };
  23682. Scene.prototype.getTransformNodesByID = function (id) {
  23683. return this.transformNodes.filter(function (m) {
  23684. return m.id === id;
  23685. });
  23686. };
  23687. /**
  23688. * Get a mesh with its auto-generated unique id
  23689. * @param {number} uniqueId - the unique id to search for
  23690. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23691. */
  23692. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23693. for (var index = 0; index < this.meshes.length; index++) {
  23694. if (this.meshes[index].uniqueId === uniqueId) {
  23695. return this.meshes[index];
  23696. }
  23697. }
  23698. return null;
  23699. };
  23700. /**
  23701. * Get a the last added mesh found of a given ID
  23702. * @param {string} id - the id to search for
  23703. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23704. */
  23705. Scene.prototype.getLastMeshByID = function (id) {
  23706. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23707. if (this.meshes[index].id === id) {
  23708. return this.meshes[index];
  23709. }
  23710. }
  23711. return null;
  23712. };
  23713. /**
  23714. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23715. * @param {string} id - the id to search for
  23716. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23717. */
  23718. Scene.prototype.getLastEntryByID = function (id) {
  23719. var index;
  23720. for (index = this.meshes.length - 1; index >= 0; index--) {
  23721. if (this.meshes[index].id === id) {
  23722. return this.meshes[index];
  23723. }
  23724. }
  23725. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23726. if (this.transformNodes[index].id === id) {
  23727. return this.transformNodes[index];
  23728. }
  23729. }
  23730. for (index = this.cameras.length - 1; index >= 0; index--) {
  23731. if (this.cameras[index].id === id) {
  23732. return this.cameras[index];
  23733. }
  23734. }
  23735. for (index = this.lights.length - 1; index >= 0; index--) {
  23736. if (this.lights[index].id === id) {
  23737. return this.lights[index];
  23738. }
  23739. }
  23740. return null;
  23741. };
  23742. Scene.prototype.getNodeByID = function (id) {
  23743. var mesh = this.getMeshByID(id);
  23744. if (mesh) {
  23745. return mesh;
  23746. }
  23747. var light = this.getLightByID(id);
  23748. if (light) {
  23749. return light;
  23750. }
  23751. var camera = this.getCameraByID(id);
  23752. if (camera) {
  23753. return camera;
  23754. }
  23755. var bone = this.getBoneByID(id);
  23756. return bone;
  23757. };
  23758. Scene.prototype.getNodeByName = function (name) {
  23759. var mesh = this.getMeshByName(name);
  23760. if (mesh) {
  23761. return mesh;
  23762. }
  23763. var light = this.getLightByName(name);
  23764. if (light) {
  23765. return light;
  23766. }
  23767. var camera = this.getCameraByName(name);
  23768. if (camera) {
  23769. return camera;
  23770. }
  23771. var bone = this.getBoneByName(name);
  23772. return bone;
  23773. };
  23774. Scene.prototype.getMeshByName = function (name) {
  23775. for (var index = 0; index < this.meshes.length; index++) {
  23776. if (this.meshes[index].name === name) {
  23777. return this.meshes[index];
  23778. }
  23779. }
  23780. return null;
  23781. };
  23782. Scene.prototype.getTransformNodeByName = function (name) {
  23783. for (var index = 0; index < this.transformNodes.length; index++) {
  23784. if (this.transformNodes[index].name === name) {
  23785. return this.transformNodes[index];
  23786. }
  23787. }
  23788. return null;
  23789. };
  23790. Scene.prototype.getSoundByName = function (name) {
  23791. var index;
  23792. if (BABYLON.AudioEngine) {
  23793. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23794. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23795. return this.mainSoundTrack.soundCollection[index];
  23796. }
  23797. }
  23798. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23799. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23800. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23801. return this.soundTracks[sdIndex].soundCollection[index];
  23802. }
  23803. }
  23804. }
  23805. }
  23806. return null;
  23807. };
  23808. Scene.prototype.getLastSkeletonByID = function (id) {
  23809. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23810. if (this.skeletons[index].id === id) {
  23811. return this.skeletons[index];
  23812. }
  23813. }
  23814. return null;
  23815. };
  23816. Scene.prototype.getSkeletonById = function (id) {
  23817. for (var index = 0; index < this.skeletons.length; index++) {
  23818. if (this.skeletons[index].id === id) {
  23819. return this.skeletons[index];
  23820. }
  23821. }
  23822. return null;
  23823. };
  23824. Scene.prototype.getSkeletonByName = function (name) {
  23825. for (var index = 0; index < this.skeletons.length; index++) {
  23826. if (this.skeletons[index].name === name) {
  23827. return this.skeletons[index];
  23828. }
  23829. }
  23830. return null;
  23831. };
  23832. Scene.prototype.getMorphTargetManagerById = function (id) {
  23833. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23834. if (this.morphTargetManagers[index].uniqueId === id) {
  23835. return this.morphTargetManagers[index];
  23836. }
  23837. }
  23838. return null;
  23839. };
  23840. Scene.prototype.isActiveMesh = function (mesh) {
  23841. return (this._activeMeshes.indexOf(mesh) !== -1);
  23842. };
  23843. /**
  23844. * Return a the first highlight layer of the scene with a given name.
  23845. * @param name The name of the highlight layer to look for.
  23846. * @return The highlight layer if found otherwise null.
  23847. */
  23848. Scene.prototype.getHighlightLayerByName = function (name) {
  23849. for (var index = 0; index < this.effectLayers.length; index++) {
  23850. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23851. return this.effectLayers[index];
  23852. }
  23853. }
  23854. return null;
  23855. };
  23856. /**
  23857. * Return a the first highlight layer of the scene with a given name.
  23858. * @param name The name of the highlight layer to look for.
  23859. * @return The highlight layer if found otherwise null.
  23860. */
  23861. Scene.prototype.getGlowLayerByName = function (name) {
  23862. for (var index = 0; index < this.effectLayers.length; index++) {
  23863. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23864. return this.effectLayers[index];
  23865. }
  23866. }
  23867. return null;
  23868. };
  23869. Object.defineProperty(Scene.prototype, "uid", {
  23870. /**
  23871. * Return a unique id as a string which can serve as an identifier for the scene
  23872. */
  23873. get: function () {
  23874. if (!this._uid) {
  23875. this._uid = BABYLON.Tools.RandomId();
  23876. }
  23877. return this._uid;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. /**
  23883. * Add an externaly attached data from its key.
  23884. * This method call will fail and return false, if such key already exists.
  23885. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23886. * @param key the unique key that identifies the data
  23887. * @param data the data object to associate to the key for this Engine instance
  23888. * @return true if no such key were already present and the data was added successfully, false otherwise
  23889. */
  23890. Scene.prototype.addExternalData = function (key, data) {
  23891. if (!this._externalData) {
  23892. this._externalData = new BABYLON.StringDictionary();
  23893. }
  23894. return this._externalData.add(key, data);
  23895. };
  23896. /**
  23897. * Get an externaly attached data from its key
  23898. * @param key the unique key that identifies the data
  23899. * @return the associated data, if present (can be null), or undefined if not present
  23900. */
  23901. Scene.prototype.getExternalData = function (key) {
  23902. if (!this._externalData) {
  23903. return null;
  23904. }
  23905. return this._externalData.get(key);
  23906. };
  23907. /**
  23908. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23909. * @param key the unique key that identifies the data
  23910. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23911. * @return the associated data, can be null if the factory returned null.
  23912. */
  23913. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23914. if (!this._externalData) {
  23915. this._externalData = new BABYLON.StringDictionary();
  23916. }
  23917. return this._externalData.getOrAddWithFactory(key, factory);
  23918. };
  23919. /**
  23920. * Remove an externaly attached data from the Engine instance
  23921. * @param key the unique key that identifies the data
  23922. * @return true if the data was successfully removed, false if it doesn't exist
  23923. */
  23924. Scene.prototype.removeExternalData = function (key) {
  23925. return this._externalData.remove(key);
  23926. };
  23927. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23928. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23929. if (mesh.showSubMeshesBoundingBox) {
  23930. var boundingInfo = subMesh.getBoundingInfo();
  23931. if (boundingInfo !== null && boundingInfo !== undefined) {
  23932. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23933. }
  23934. }
  23935. var material = subMesh.getMaterial();
  23936. if (material !== null && material !== undefined) {
  23937. // Render targets
  23938. if (material.getRenderTargetTextures !== undefined) {
  23939. if (this._processedMaterials.indexOf(material) === -1) {
  23940. this._processedMaterials.push(material);
  23941. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23942. }
  23943. }
  23944. // Dispatch
  23945. this._activeIndices.addCount(subMesh.indexCount, false);
  23946. this._renderingManager.dispatch(subMesh, mesh, material);
  23947. }
  23948. }
  23949. };
  23950. /**
  23951. * Clear the processed materials smart array preventing retention point in material dispose.
  23952. */
  23953. Scene.prototype.freeProcessedMaterials = function () {
  23954. this._processedMaterials.dispose();
  23955. };
  23956. /**
  23957. * Clear the active meshes smart array preventing retention point in mesh dispose.
  23958. */
  23959. Scene.prototype.freeActiveMeshes = function () {
  23960. this._activeMeshes.dispose();
  23961. if (this.activeCamera && this.activeCamera._activeMeshes) {
  23962. this.activeCamera._activeMeshes.dispose();
  23963. }
  23964. if (this.activeCameras) {
  23965. for (var i = 0; i < this.activeCameras.length; i++) {
  23966. var activeCamera = this.activeCameras[i];
  23967. if (activeCamera && activeCamera._activeMeshes) {
  23968. activeCamera._activeMeshes.dispose();
  23969. }
  23970. }
  23971. }
  23972. };
  23973. /**
  23974. * Clear the info related to rendering groups preventing retention points during dispose.
  23975. */
  23976. Scene.prototype.freeRenderingGroups = function () {
  23977. if (this._renderingManager) {
  23978. this._renderingManager.freeRenderingGroups();
  23979. }
  23980. if (this.textures) {
  23981. for (var i = 0; i < this.textures.length; i++) {
  23982. var texture = this.textures[i];
  23983. if (texture && texture.isRenderTarget) {
  23984. texture.freeRenderingGroups();
  23985. }
  23986. }
  23987. }
  23988. };
  23989. Scene.prototype._isInIntermediateRendering = function () {
  23990. return this._intermediateRendering;
  23991. };
  23992. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23993. this._activeMeshCandidateProvider = provider;
  23994. };
  23995. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23996. return this._activeMeshCandidateProvider;
  23997. };
  23998. /**
  23999. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24000. */
  24001. Scene.prototype.freezeActiveMeshes = function () {
  24002. this._evaluateActiveMeshes();
  24003. this._activeMeshesFrozen = true;
  24004. return this;
  24005. };
  24006. /**
  24007. * Use this function to restart evaluating active meshes on every frame
  24008. */
  24009. Scene.prototype.unfreezeActiveMeshes = function () {
  24010. this._activeMeshesFrozen = false;
  24011. return this;
  24012. };
  24013. Scene.prototype._evaluateActiveMeshes = function () {
  24014. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24015. return;
  24016. }
  24017. if (!this.activeCamera) {
  24018. return;
  24019. }
  24020. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24021. this.activeCamera._activeMeshes.reset();
  24022. this._activeMeshes.reset();
  24023. this._renderingManager.reset();
  24024. this._processedMaterials.reset();
  24025. this._activeParticleSystems.reset();
  24026. this._activeSkeletons.reset();
  24027. this._softwareSkinnedMeshes.reset();
  24028. if (this._boundingBoxRenderer) {
  24029. this._boundingBoxRenderer.reset();
  24030. }
  24031. // Meshes
  24032. var meshes;
  24033. var len;
  24034. var checkIsEnabled = true;
  24035. // Determine mesh candidates
  24036. if (this._activeMeshCandidateProvider !== undefined) {
  24037. // Use _activeMeshCandidateProvider
  24038. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24039. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24040. if (meshes !== undefined) {
  24041. len = meshes.length;
  24042. }
  24043. else {
  24044. len = 0;
  24045. }
  24046. }
  24047. else if (this._selectionOctree !== undefined) {
  24048. // Octree
  24049. var selection = this._selectionOctree.select(this._frustumPlanes);
  24050. meshes = selection.data;
  24051. len = selection.length;
  24052. }
  24053. else {
  24054. // Full scene traversal
  24055. len = this.meshes.length;
  24056. meshes = this.meshes;
  24057. }
  24058. // Check each mesh
  24059. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24060. mesh = meshes[meshIndex];
  24061. if (mesh.isBlocked) {
  24062. continue;
  24063. }
  24064. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24065. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24066. continue;
  24067. }
  24068. mesh.computeWorldMatrix();
  24069. // Intersections
  24070. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24071. this._meshesForIntersections.pushNoDuplicate(mesh);
  24072. }
  24073. // Switch to current LOD
  24074. meshLOD = mesh.getLOD(this.activeCamera);
  24075. if (meshLOD === undefined || meshLOD === null) {
  24076. continue;
  24077. }
  24078. mesh._preActivate();
  24079. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24080. this._activeMeshes.push(mesh);
  24081. this.activeCamera._activeMeshes.push(mesh);
  24082. mesh._activate(this._renderId);
  24083. if (meshLOD !== mesh) {
  24084. meshLOD._activate(this._renderId);
  24085. }
  24086. this._activeMesh(mesh, meshLOD);
  24087. }
  24088. }
  24089. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24090. // Particle systems
  24091. if (this.particlesEnabled) {
  24092. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24093. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24094. var particleSystem = this.particleSystems[particleIndex];
  24095. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24096. continue;
  24097. }
  24098. var emitter = particleSystem.emitter;
  24099. if (!emitter.position || emitter.isEnabled()) {
  24100. this._activeParticleSystems.push(particleSystem);
  24101. particleSystem.animate();
  24102. this._renderingManager.dispatchParticles(particleSystem);
  24103. }
  24104. }
  24105. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24106. }
  24107. };
  24108. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24109. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24110. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24111. mesh.skeleton.prepare();
  24112. }
  24113. if (!mesh.computeBonesUsingShaders) {
  24114. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24115. }
  24116. }
  24117. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24118. var boundingInfo = sourceMesh.getBoundingInfo();
  24119. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24120. }
  24121. if (mesh !== undefined && mesh !== null
  24122. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24123. // Submeshes Octrees
  24124. var len;
  24125. var subMeshes;
  24126. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24127. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24128. len = intersections.length;
  24129. subMeshes = intersections.data;
  24130. }
  24131. else {
  24132. subMeshes = mesh.subMeshes;
  24133. len = subMeshes.length;
  24134. }
  24135. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24136. subMesh = subMeshes[subIndex];
  24137. this._evaluateSubMesh(subMesh, mesh);
  24138. }
  24139. }
  24140. };
  24141. Scene.prototype.updateTransformMatrix = function (force) {
  24142. if (!this.activeCamera) {
  24143. return;
  24144. }
  24145. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24146. };
  24147. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24148. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24149. };
  24150. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24151. if (camera && camera._skipRendering) {
  24152. return;
  24153. }
  24154. var engine = this._engine;
  24155. this.activeCamera = camera;
  24156. if (!this.activeCamera)
  24157. throw new Error("Active camera not set");
  24158. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24159. // Viewport
  24160. engine.setViewport(this.activeCamera.viewport);
  24161. // Camera
  24162. this.resetCachedMaterial();
  24163. this._renderId++;
  24164. this.updateTransformMatrix();
  24165. if (camera._alternateCamera) {
  24166. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24167. this._alternateRendering = true;
  24168. }
  24169. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24170. // Meshes
  24171. this._evaluateActiveMeshes();
  24172. // Software skinning
  24173. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24174. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24175. mesh.applySkeleton(mesh.skeleton);
  24176. }
  24177. // Render targets
  24178. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24179. var needsRestoreFrameBuffer = false;
  24180. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24181. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24182. }
  24183. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24184. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24185. }
  24186. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24187. this._intermediateRendering = true;
  24188. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24189. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24190. var renderTarget = this._renderTargets.data[renderIndex];
  24191. if (renderTarget._shouldRender()) {
  24192. this._renderId++;
  24193. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24194. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24195. }
  24196. }
  24197. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24198. this._intermediateRendering = false;
  24199. this._renderId++;
  24200. needsRestoreFrameBuffer = true; // Restore back buffer
  24201. }
  24202. // Render EffecttLayer Texture
  24203. var stencilState = this._engine.getStencilBuffer();
  24204. var renderEffects = false;
  24205. var needStencil = false;
  24206. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24207. this._intermediateRendering = true;
  24208. for (var i = 0; i < this.effectLayers.length; i++) {
  24209. var effectLayer = this.effectLayers[i];
  24210. if (effectLayer.shouldRender() &&
  24211. (!effectLayer.camera ||
  24212. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24213. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24214. renderEffects = true;
  24215. needStencil = needStencil || effectLayer.needStencil();
  24216. var renderTarget = effectLayer._mainTexture;
  24217. if (renderTarget._shouldRender()) {
  24218. this._renderId++;
  24219. renderTarget.render(false, false);
  24220. needsRestoreFrameBuffer = true;
  24221. }
  24222. }
  24223. }
  24224. this._intermediateRendering = false;
  24225. this._renderId++;
  24226. }
  24227. if (needsRestoreFrameBuffer) {
  24228. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24229. }
  24230. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24231. // Prepare Frame
  24232. this.postProcessManager._prepareFrame();
  24233. // Backgrounds
  24234. var layerIndex;
  24235. var layer;
  24236. if (this.layers.length) {
  24237. engine.setDepthBuffer(false);
  24238. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24239. layer = this.layers[layerIndex];
  24240. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24241. layer.render();
  24242. }
  24243. }
  24244. engine.setDepthBuffer(true);
  24245. }
  24246. // Activate effect Layer stencil
  24247. if (needStencil) {
  24248. this._engine.setStencilBuffer(true);
  24249. }
  24250. // Render
  24251. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24252. this._renderingManager.render(null, null, true, true);
  24253. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24254. // Restore effect Layer stencil
  24255. if (needStencil) {
  24256. this._engine.setStencilBuffer(stencilState);
  24257. }
  24258. // Bounding boxes
  24259. if (this._boundingBoxRenderer) {
  24260. this._boundingBoxRenderer.render();
  24261. }
  24262. // Lens flares
  24263. if (this.lensFlaresEnabled) {
  24264. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24265. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24266. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24267. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24268. lensFlareSystem.render();
  24269. }
  24270. }
  24271. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24272. }
  24273. // Foregrounds
  24274. if (this.layers.length) {
  24275. engine.setDepthBuffer(false);
  24276. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24277. layer = this.layers[layerIndex];
  24278. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24279. layer.render();
  24280. }
  24281. }
  24282. engine.setDepthBuffer(true);
  24283. }
  24284. // Effect Layer
  24285. if (renderEffects) {
  24286. engine.setDepthBuffer(false);
  24287. for (var i = 0; i < this.effectLayers.length; i++) {
  24288. if (this.effectLayers[i].shouldRender()) {
  24289. this.effectLayers[i].render();
  24290. }
  24291. }
  24292. engine.setDepthBuffer(true);
  24293. }
  24294. // Finalize frame
  24295. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24296. // Reset some special arrays
  24297. this._renderTargets.reset();
  24298. this._alternateRendering = false;
  24299. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24300. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24301. };
  24302. Scene.prototype._processSubCameras = function (camera) {
  24303. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24304. this._renderForCamera(camera);
  24305. return;
  24306. }
  24307. // rig cameras
  24308. for (var index = 0; index < camera._rigCameras.length; index++) {
  24309. this._renderForCamera(camera._rigCameras[index], camera);
  24310. }
  24311. this.activeCamera = camera;
  24312. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24313. };
  24314. Scene.prototype._checkIntersections = function () {
  24315. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24316. var sourceMesh = this._meshesForIntersections.data[index];
  24317. if (!sourceMesh.actionManager) {
  24318. continue;
  24319. }
  24320. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24321. var action = sourceMesh.actionManager.actions[actionIndex];
  24322. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24323. var parameters = action.getTriggerParameter();
  24324. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24325. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24326. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24327. if (areIntersecting && currentIntersectionInProgress === -1) {
  24328. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24329. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24330. sourceMesh._intersectionsInProgress.push(otherMesh);
  24331. }
  24332. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24333. sourceMesh._intersectionsInProgress.push(otherMesh);
  24334. }
  24335. }
  24336. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24337. //They intersected, and now they don't.
  24338. //is this trigger an exit trigger? execute an event.
  24339. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24340. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24341. }
  24342. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24343. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24344. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24345. }
  24346. }
  24347. }
  24348. }
  24349. }
  24350. };
  24351. Scene.prototype.render = function () {
  24352. if (this.isDisposed) {
  24353. return;
  24354. }
  24355. this._activeParticles.fetchNewFrame();
  24356. this._totalVertices.fetchNewFrame();
  24357. this._activeIndices.fetchNewFrame();
  24358. this._activeBones.fetchNewFrame();
  24359. this._meshesForIntersections.reset();
  24360. this.resetCachedMaterial();
  24361. this.onBeforeAnimationsObservable.notifyObservers(this);
  24362. // Actions
  24363. if (this.actionManager) {
  24364. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24365. }
  24366. //Simplification Queue
  24367. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24368. this.simplificationQueue.executeNext();
  24369. }
  24370. if (this._engine.isDeterministicLockStep()) {
  24371. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24372. var defaultFPS = (60.0 / 1000.0);
  24373. var defaultFrameTime = 1000 / 60; // frame time in MS
  24374. if (this._physicsEngine) {
  24375. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24376. }
  24377. var stepsTaken = 0;
  24378. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24379. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24380. internalSteps = Math.min(internalSteps, maxSubSteps);
  24381. do {
  24382. this.onBeforeStepObservable.notifyObservers(this);
  24383. // Animations
  24384. this._animationRatio = defaultFrameTime * defaultFPS;
  24385. this._animate();
  24386. this.onAfterAnimationsObservable.notifyObservers(this);
  24387. // Physics
  24388. if (this._physicsEngine) {
  24389. this.onBeforePhysicsObservable.notifyObservers(this);
  24390. this._physicsEngine._step(defaultFrameTime / 1000);
  24391. this.onAfterPhysicsObservable.notifyObservers(this);
  24392. }
  24393. this.onAfterStepObservable.notifyObservers(this);
  24394. this._currentStepId++;
  24395. stepsTaken++;
  24396. deltaTime -= defaultFrameTime;
  24397. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24398. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24399. }
  24400. else {
  24401. // Animations
  24402. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24403. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24404. this._animate();
  24405. this.onAfterAnimationsObservable.notifyObservers(this);
  24406. // Physics
  24407. if (this._physicsEngine) {
  24408. this.onBeforePhysicsObservable.notifyObservers(this);
  24409. this._physicsEngine._step(deltaTime / 1000.0);
  24410. this.onAfterPhysicsObservable.notifyObservers(this);
  24411. }
  24412. }
  24413. // update gamepad manager
  24414. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24415. this._gamepadManager._checkGamepadsStatus();
  24416. }
  24417. // Update Cameras
  24418. if (this.activeCameras.length > 0) {
  24419. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24420. var camera = this.activeCameras[cameraIndex];
  24421. camera.update();
  24422. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24423. // rig cameras
  24424. for (var index = 0; index < camera._rigCameras.length; index++) {
  24425. camera._rigCameras[index].update();
  24426. }
  24427. }
  24428. }
  24429. }
  24430. else if (this.activeCamera) {
  24431. this.activeCamera.update();
  24432. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24433. // rig cameras
  24434. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24435. this.activeCamera._rigCameras[index].update();
  24436. }
  24437. }
  24438. }
  24439. // Before render
  24440. this.onBeforeRenderObservable.notifyObservers(this);
  24441. // Customs render targets
  24442. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24443. var engine = this.getEngine();
  24444. var currentActiveCamera = this.activeCamera;
  24445. if (this.renderTargetsEnabled) {
  24446. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24447. this._intermediateRendering = true;
  24448. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24449. var renderTarget = this.customRenderTargets[customIndex];
  24450. if (renderTarget._shouldRender()) {
  24451. this._renderId++;
  24452. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24453. if (!this.activeCamera)
  24454. throw new Error("Active camera not set");
  24455. // Viewport
  24456. engine.setViewport(this.activeCamera.viewport);
  24457. // Camera
  24458. this.updateTransformMatrix();
  24459. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24460. }
  24461. }
  24462. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24463. this._intermediateRendering = false;
  24464. this._renderId++;
  24465. }
  24466. // Restore back buffer
  24467. if (this.customRenderTargets.length > 0) {
  24468. engine.restoreDefaultFramebuffer();
  24469. }
  24470. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24471. this.activeCamera = currentActiveCamera;
  24472. // Procedural textures
  24473. if (this.proceduralTexturesEnabled) {
  24474. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24475. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24476. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24477. if (proceduralTexture._shouldRender()) {
  24478. proceduralTexture.render();
  24479. }
  24480. }
  24481. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24482. }
  24483. // Clear
  24484. if (this.autoClearDepthAndStencil || this.autoClear) {
  24485. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24486. }
  24487. // Shadows
  24488. if (this.shadowsEnabled) {
  24489. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24490. var light = this.lights[lightIndex];
  24491. var shadowGenerator = light.getShadowGenerator();
  24492. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24493. var shadowMap = (shadowGenerator.getShadowMap());
  24494. if (this.textures.indexOf(shadowMap) !== -1) {
  24495. this._renderTargets.push(shadowMap);
  24496. }
  24497. }
  24498. }
  24499. }
  24500. // Depth renderer
  24501. for (var key in this._depthRenderer) {
  24502. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24503. }
  24504. // Geometry renderer
  24505. if (this._geometryBufferRenderer) {
  24506. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24507. }
  24508. // RenderPipeline
  24509. if (this._postProcessRenderPipelineManager) {
  24510. this._postProcessRenderPipelineManager.update();
  24511. }
  24512. // Multi-cameras?
  24513. if (this.activeCameras.length > 0) {
  24514. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24515. if (cameraIndex > 0) {
  24516. this._engine.clear(null, false, true, true);
  24517. }
  24518. this._processSubCameras(this.activeCameras[cameraIndex]);
  24519. }
  24520. }
  24521. else {
  24522. if (!this.activeCamera) {
  24523. throw new Error("No camera defined");
  24524. }
  24525. this._processSubCameras(this.activeCamera);
  24526. }
  24527. // Intersection checks
  24528. this._checkIntersections();
  24529. // Update the audio listener attached to the camera
  24530. if (BABYLON.AudioEngine) {
  24531. this._updateAudioParameters();
  24532. }
  24533. // After render
  24534. if (this.afterRender) {
  24535. this.afterRender();
  24536. }
  24537. this.onAfterRenderObservable.notifyObservers(this);
  24538. // Cleaning
  24539. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24540. var data = this._toBeDisposed.data[index];
  24541. if (data) {
  24542. data.dispose();
  24543. }
  24544. this._toBeDisposed[index] = null;
  24545. }
  24546. this._toBeDisposed.reset();
  24547. if (this.dumpNextRenderTargets) {
  24548. this.dumpNextRenderTargets = false;
  24549. }
  24550. this._activeBones.addCount(0, true);
  24551. this._activeIndices.addCount(0, true);
  24552. this._activeParticles.addCount(0, true);
  24553. };
  24554. Scene.prototype._updateAudioParameters = function () {
  24555. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24556. return;
  24557. }
  24558. var listeningCamera;
  24559. var audioEngine = BABYLON.Engine.audioEngine;
  24560. if (this.activeCameras.length > 0) {
  24561. listeningCamera = this.activeCameras[0];
  24562. }
  24563. else {
  24564. listeningCamera = this.activeCamera;
  24565. }
  24566. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24567. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24568. // for VR cameras
  24569. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24570. listeningCamera = listeningCamera.rigCameras[0];
  24571. }
  24572. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24573. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24574. cameraDirection.normalize();
  24575. // To avoid some errors on GearVR
  24576. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24577. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24578. }
  24579. var i;
  24580. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24581. var sound = this.mainSoundTrack.soundCollection[i];
  24582. if (sound.useCustomAttenuation) {
  24583. sound.updateDistanceFromListener();
  24584. }
  24585. }
  24586. for (i = 0; i < this.soundTracks.length; i++) {
  24587. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24588. sound = this.soundTracks[i].soundCollection[j];
  24589. if (sound.useCustomAttenuation) {
  24590. sound.updateDistanceFromListener();
  24591. }
  24592. }
  24593. }
  24594. }
  24595. };
  24596. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24597. // Audio
  24598. get: function () {
  24599. return this._audioEnabled;
  24600. },
  24601. set: function (value) {
  24602. this._audioEnabled = value;
  24603. if (BABYLON.AudioEngine) {
  24604. if (this._audioEnabled) {
  24605. this._enableAudio();
  24606. }
  24607. else {
  24608. this._disableAudio();
  24609. }
  24610. }
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Scene.prototype._disableAudio = function () {
  24616. var i;
  24617. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24618. this.mainSoundTrack.soundCollection[i].pause();
  24619. }
  24620. for (i = 0; i < this.soundTracks.length; i++) {
  24621. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24622. this.soundTracks[i].soundCollection[j].pause();
  24623. }
  24624. }
  24625. };
  24626. Scene.prototype._enableAudio = function () {
  24627. var i;
  24628. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24629. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24630. this.mainSoundTrack.soundCollection[i].play();
  24631. }
  24632. }
  24633. for (i = 0; i < this.soundTracks.length; i++) {
  24634. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24635. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24636. this.soundTracks[i].soundCollection[j].play();
  24637. }
  24638. }
  24639. }
  24640. };
  24641. Object.defineProperty(Scene.prototype, "headphone", {
  24642. get: function () {
  24643. return this._headphone;
  24644. },
  24645. set: function (value) {
  24646. this._headphone = value;
  24647. if (BABYLON.AudioEngine) {
  24648. if (this._headphone) {
  24649. this._switchAudioModeForHeadphones();
  24650. }
  24651. else {
  24652. this._switchAudioModeForNormalSpeakers();
  24653. }
  24654. }
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Scene.prototype._switchAudioModeForHeadphones = function () {
  24660. this.mainSoundTrack.switchPanningModelToHRTF();
  24661. for (var i = 0; i < this.soundTracks.length; i++) {
  24662. this.soundTracks[i].switchPanningModelToHRTF();
  24663. }
  24664. };
  24665. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24666. this.mainSoundTrack.switchPanningModelToEqualPower();
  24667. for (var i = 0; i < this.soundTracks.length; i++) {
  24668. this.soundTracks[i].switchPanningModelToEqualPower();
  24669. }
  24670. };
  24671. /**
  24672. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24673. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24674. * @returns the created depth renderer
  24675. */
  24676. Scene.prototype.enableDepthRenderer = function (camera) {
  24677. camera = camera || this.activeCamera;
  24678. if (!camera) {
  24679. throw "No camera available to enable depth renderer";
  24680. }
  24681. if (!this._depthRenderer[camera.id]) {
  24682. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24683. }
  24684. return this._depthRenderer[camera.id];
  24685. };
  24686. /**
  24687. * Disables a depth renderer for a given camera
  24688. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24689. */
  24690. Scene.prototype.disableDepthRenderer = function (camera) {
  24691. camera = camera || this.activeCamera;
  24692. if (!camera || !this._depthRenderer[camera.id]) {
  24693. return;
  24694. }
  24695. this._depthRenderer[camera.id].dispose();
  24696. delete this._depthRenderer[camera.id];
  24697. };
  24698. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24699. if (ratio === void 0) { ratio = 1; }
  24700. if (this._geometryBufferRenderer) {
  24701. return this._geometryBufferRenderer;
  24702. }
  24703. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24704. if (!this._geometryBufferRenderer.isSupported) {
  24705. this._geometryBufferRenderer = null;
  24706. }
  24707. return this._geometryBufferRenderer;
  24708. };
  24709. Scene.prototype.disableGeometryBufferRenderer = function () {
  24710. if (!this._geometryBufferRenderer) {
  24711. return;
  24712. }
  24713. this._geometryBufferRenderer.dispose();
  24714. this._geometryBufferRenderer = null;
  24715. };
  24716. Scene.prototype.freezeMaterials = function () {
  24717. for (var i = 0; i < this.materials.length; i++) {
  24718. this.materials[i].freeze();
  24719. }
  24720. };
  24721. Scene.prototype.unfreezeMaterials = function () {
  24722. for (var i = 0; i < this.materials.length; i++) {
  24723. this.materials[i].unfreeze();
  24724. }
  24725. };
  24726. Scene.prototype.dispose = function () {
  24727. this.beforeRender = null;
  24728. this.afterRender = null;
  24729. this.skeletons = [];
  24730. this.morphTargetManagers = [];
  24731. this.importedMeshesFiles = new Array();
  24732. this.stopAllAnimations();
  24733. this.resetCachedMaterial();
  24734. for (var key in this._depthRenderer) {
  24735. this._depthRenderer[key].dispose();
  24736. }
  24737. if (this._gamepadManager) {
  24738. this._gamepadManager.dispose();
  24739. this._gamepadManager = null;
  24740. }
  24741. // Smart arrays
  24742. if (this.activeCamera) {
  24743. this.activeCamera._activeMeshes.dispose();
  24744. this.activeCamera = null;
  24745. }
  24746. this._activeMeshes.dispose();
  24747. this._renderingManager.dispose();
  24748. this._processedMaterials.dispose();
  24749. this._activeParticleSystems.dispose();
  24750. this._activeSkeletons.dispose();
  24751. this._softwareSkinnedMeshes.dispose();
  24752. this._renderTargets.dispose();
  24753. if (this._boundingBoxRenderer) {
  24754. this._boundingBoxRenderer.dispose();
  24755. }
  24756. this._meshesForIntersections.dispose();
  24757. this._toBeDisposed.dispose();
  24758. // Abort active requests
  24759. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24760. var request = _a[_i];
  24761. request.abort();
  24762. }
  24763. // Debug layer
  24764. if (this._debugLayer) {
  24765. this._debugLayer.hide();
  24766. }
  24767. // Events
  24768. this.onDisposeObservable.notifyObservers(this);
  24769. this.onDisposeObservable.clear();
  24770. this.onBeforeRenderObservable.clear();
  24771. this.onAfterRenderObservable.clear();
  24772. this.OnBeforeRenderTargetsRenderObservable.clear();
  24773. this.OnAfterRenderTargetsRenderObservable.clear();
  24774. this.onAfterStepObservable.clear();
  24775. this.onBeforeStepObservable.clear();
  24776. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24777. this.onAfterActiveMeshesEvaluationObservable.clear();
  24778. this.onBeforeParticlesRenderingObservable.clear();
  24779. this.onAfterParticlesRenderingObservable.clear();
  24780. this.onBeforeSpritesRenderingObservable.clear();
  24781. this.onAfterSpritesRenderingObservable.clear();
  24782. this.onBeforeDrawPhaseObservable.clear();
  24783. this.onAfterDrawPhaseObservable.clear();
  24784. this.onBeforePhysicsObservable.clear();
  24785. this.onAfterPhysicsObservable.clear();
  24786. this.onBeforeAnimationsObservable.clear();
  24787. this.onAfterAnimationsObservable.clear();
  24788. this.onDataLoadedObservable.clear();
  24789. this.detachControl();
  24790. // Release sounds & sounds tracks
  24791. if (BABYLON.AudioEngine) {
  24792. this.disposeSounds();
  24793. }
  24794. // VR Helper
  24795. if (this.VRHelper) {
  24796. this.VRHelper.dispose();
  24797. }
  24798. // Detach cameras
  24799. var canvas = this._engine.getRenderingCanvas();
  24800. if (canvas) {
  24801. var index;
  24802. for (index = 0; index < this.cameras.length; index++) {
  24803. this.cameras[index].detachControl(canvas);
  24804. }
  24805. }
  24806. // Release animation groups
  24807. while (this.animationGroups.length) {
  24808. this.animationGroups[0].dispose();
  24809. }
  24810. // Release lights
  24811. while (this.lights.length) {
  24812. this.lights[0].dispose();
  24813. }
  24814. // Release meshes
  24815. while (this.meshes.length) {
  24816. this.meshes[0].dispose(true);
  24817. }
  24818. while (this.transformNodes.length) {
  24819. this.removeTransformNode(this.transformNodes[0]);
  24820. }
  24821. // Release cameras
  24822. while (this.cameras.length) {
  24823. this.cameras[0].dispose();
  24824. }
  24825. // Release materials
  24826. if (this.defaultMaterial) {
  24827. this.defaultMaterial.dispose();
  24828. }
  24829. while (this.multiMaterials.length) {
  24830. this.multiMaterials[0].dispose();
  24831. }
  24832. while (this.materials.length) {
  24833. this.materials[0].dispose();
  24834. }
  24835. // Release particles
  24836. while (this.particleSystems.length) {
  24837. this.particleSystems[0].dispose();
  24838. }
  24839. // Release sprites
  24840. while (this.spriteManagers.length) {
  24841. this.spriteManagers[0].dispose();
  24842. }
  24843. // Release postProcesses
  24844. while (this.postProcesses.length) {
  24845. this.postProcesses[0].dispose();
  24846. }
  24847. // Release layers
  24848. while (this.layers.length) {
  24849. this.layers[0].dispose();
  24850. }
  24851. while (this.effectLayers.length) {
  24852. this.effectLayers[0].dispose();
  24853. }
  24854. // Release textures
  24855. while (this.textures.length) {
  24856. this.textures[0].dispose();
  24857. }
  24858. // Release UBO
  24859. this._sceneUbo.dispose();
  24860. if (this._alternateSceneUbo) {
  24861. this._alternateSceneUbo.dispose();
  24862. }
  24863. // Post-processes
  24864. this.postProcessManager.dispose();
  24865. if (this._postProcessRenderPipelineManager) {
  24866. this._postProcessRenderPipelineManager.dispose();
  24867. }
  24868. // Physics
  24869. if (this._physicsEngine) {
  24870. this.disablePhysicsEngine();
  24871. }
  24872. // Remove from engine
  24873. index = this._engine.scenes.indexOf(this);
  24874. if (index > -1) {
  24875. this._engine.scenes.splice(index, 1);
  24876. }
  24877. this._engine.wipeCaches(true);
  24878. this._isDisposed = true;
  24879. };
  24880. Object.defineProperty(Scene.prototype, "isDisposed", {
  24881. get: function () {
  24882. return this._isDisposed;
  24883. },
  24884. enumerable: true,
  24885. configurable: true
  24886. });
  24887. // Release sounds & sounds tracks
  24888. Scene.prototype.disposeSounds = function () {
  24889. if (!this._mainSoundTrack) {
  24890. return;
  24891. }
  24892. this.mainSoundTrack.dispose();
  24893. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24894. this.soundTracks[scIndex].dispose();
  24895. }
  24896. };
  24897. // Octrees
  24898. /**
  24899. * Get the world extend vectors with an optional filter
  24900. *
  24901. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24902. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24903. */
  24904. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24905. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24906. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24907. filterPredicate = filterPredicate || (function () { return true; });
  24908. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24909. mesh.computeWorldMatrix(true);
  24910. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24911. return;
  24912. }
  24913. var boundingInfo = mesh.getBoundingInfo();
  24914. var minBox = boundingInfo.boundingBox.minimumWorld;
  24915. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24916. BABYLON.Tools.CheckExtends(minBox, min, max);
  24917. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24918. });
  24919. return {
  24920. min: min,
  24921. max: max
  24922. };
  24923. };
  24924. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24925. if (maxCapacity === void 0) { maxCapacity = 64; }
  24926. if (maxDepth === void 0) { maxDepth = 2; }
  24927. if (!this._selectionOctree) {
  24928. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24929. }
  24930. var worldExtends = this.getWorldExtends();
  24931. // Update octree
  24932. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24933. return this._selectionOctree;
  24934. };
  24935. // Picking
  24936. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24937. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24938. var result = BABYLON.Ray.Zero();
  24939. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24940. return result;
  24941. };
  24942. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24943. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24944. var engine = this._engine;
  24945. if (!camera) {
  24946. if (!this.activeCamera)
  24947. throw new Error("Active camera not set");
  24948. camera = this.activeCamera;
  24949. }
  24950. var cameraViewport = camera.viewport;
  24951. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24952. // Moving coordinates to local viewport world
  24953. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24954. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24955. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24956. return this;
  24957. };
  24958. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24959. var result = BABYLON.Ray.Zero();
  24960. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24961. return result;
  24962. };
  24963. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24964. if (!BABYLON.PickingInfo) {
  24965. return this;
  24966. }
  24967. var engine = this._engine;
  24968. if (!camera) {
  24969. if (!this.activeCamera)
  24970. throw new Error("Active camera not set");
  24971. camera = this.activeCamera;
  24972. }
  24973. var cameraViewport = camera.viewport;
  24974. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24975. var identity = BABYLON.Matrix.Identity();
  24976. // Moving coordinates to local viewport world
  24977. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24978. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24979. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24980. return this;
  24981. };
  24982. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24983. if (!BABYLON.PickingInfo) {
  24984. return null;
  24985. }
  24986. var pickingInfo = null;
  24987. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24988. var mesh = this.meshes[meshIndex];
  24989. if (predicate) {
  24990. if (!predicate(mesh)) {
  24991. continue;
  24992. }
  24993. }
  24994. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24995. continue;
  24996. }
  24997. var world = mesh.getWorldMatrix();
  24998. var ray = rayFunction(world);
  24999. var result = mesh.intersects(ray, fastCheck);
  25000. if (!result || !result.hit)
  25001. continue;
  25002. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25003. continue;
  25004. pickingInfo = result;
  25005. if (fastCheck) {
  25006. break;
  25007. }
  25008. }
  25009. return pickingInfo || new BABYLON.PickingInfo();
  25010. };
  25011. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25012. if (!BABYLON.PickingInfo) {
  25013. return null;
  25014. }
  25015. var pickingInfos = new Array();
  25016. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25017. var mesh = this.meshes[meshIndex];
  25018. if (predicate) {
  25019. if (!predicate(mesh)) {
  25020. continue;
  25021. }
  25022. }
  25023. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25024. continue;
  25025. }
  25026. var world = mesh.getWorldMatrix();
  25027. var ray = rayFunction(world);
  25028. var result = mesh.intersects(ray, false);
  25029. if (!result || !result.hit)
  25030. continue;
  25031. pickingInfos.push(result);
  25032. }
  25033. return pickingInfos;
  25034. };
  25035. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25036. if (!BABYLON.PickingInfo) {
  25037. return null;
  25038. }
  25039. var pickingInfo = null;
  25040. if (!camera) {
  25041. if (!this.activeCamera) {
  25042. return null;
  25043. }
  25044. camera = this.activeCamera;
  25045. }
  25046. if (this.spriteManagers.length > 0) {
  25047. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25048. var spriteManager = this.spriteManagers[spriteIndex];
  25049. if (!spriteManager.isPickable) {
  25050. continue;
  25051. }
  25052. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25053. if (!result || !result.hit)
  25054. continue;
  25055. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25056. continue;
  25057. pickingInfo = result;
  25058. if (fastCheck) {
  25059. break;
  25060. }
  25061. }
  25062. }
  25063. return pickingInfo || new BABYLON.PickingInfo();
  25064. };
  25065. /** Launch a ray to try to pick a mesh in the scene
  25066. * @param x position on screen
  25067. * @param y position on screen
  25068. * @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
  25069. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25070. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25071. */
  25072. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25073. var _this = this;
  25074. if (!BABYLON.PickingInfo) {
  25075. return null;
  25076. }
  25077. return this._internalPick(function (world) {
  25078. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25079. return _this._tempPickingRay;
  25080. }, predicate, fastCheck);
  25081. };
  25082. /** Launch a ray to try to pick a sprite in the scene
  25083. * @param x position on screen
  25084. * @param y position on screen
  25085. * @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
  25086. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25087. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25088. */
  25089. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25090. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25091. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25092. };
  25093. /** Use the given ray to pick a mesh in the scene
  25094. * @param ray The ray to use to pick meshes
  25095. * @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
  25096. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25097. */
  25098. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25099. var _this = this;
  25100. return this._internalPick(function (world) {
  25101. if (!_this._pickWithRayInverseMatrix) {
  25102. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25103. }
  25104. world.invertToRef(_this._pickWithRayInverseMatrix);
  25105. if (!_this._cachedRayForTransform) {
  25106. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25107. }
  25108. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25109. return _this._cachedRayForTransform;
  25110. }, predicate, fastCheck);
  25111. };
  25112. /**
  25113. * Launch a ray to try to pick a mesh in the scene
  25114. * @param x X position on screen
  25115. * @param y Y position on screen
  25116. * @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
  25117. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25118. */
  25119. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25120. var _this = this;
  25121. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25122. };
  25123. /**
  25124. * Launch a ray to try to pick a mesh in the scene
  25125. * @param ray Ray to use
  25126. * @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
  25127. */
  25128. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25129. var _this = this;
  25130. return this._internalMultiPick(function (world) {
  25131. if (!_this._pickWithRayInverseMatrix) {
  25132. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25133. }
  25134. world.invertToRef(_this._pickWithRayInverseMatrix);
  25135. if (!_this._cachedRayForTransform) {
  25136. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25137. }
  25138. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25139. return _this._cachedRayForTransform;
  25140. }, predicate);
  25141. };
  25142. Scene.prototype.setPointerOverMesh = function (mesh) {
  25143. if (this._pointerOverMesh === mesh) {
  25144. return;
  25145. }
  25146. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25147. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25148. }
  25149. this._pointerOverMesh = mesh;
  25150. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25151. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25152. }
  25153. };
  25154. Scene.prototype.getPointerOverMesh = function () {
  25155. return this._pointerOverMesh;
  25156. };
  25157. Scene.prototype.setPointerOverSprite = function (sprite) {
  25158. if (this._pointerOverSprite === sprite) {
  25159. return;
  25160. }
  25161. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25162. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25163. }
  25164. this._pointerOverSprite = sprite;
  25165. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25166. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25167. }
  25168. };
  25169. Scene.prototype.getPointerOverSprite = function () {
  25170. return this._pointerOverSprite;
  25171. };
  25172. // Physics
  25173. Scene.prototype.getPhysicsEngine = function () {
  25174. return this._physicsEngine;
  25175. };
  25176. /**
  25177. * Enables physics to the current scene
  25178. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25179. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25180. * @return {boolean} was the physics engine initialized
  25181. */
  25182. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25183. if (gravity === void 0) { gravity = null; }
  25184. if (this._physicsEngine) {
  25185. return true;
  25186. }
  25187. try {
  25188. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25189. return true;
  25190. }
  25191. catch (e) {
  25192. BABYLON.Tools.Error(e.message);
  25193. return false;
  25194. }
  25195. };
  25196. Scene.prototype.disablePhysicsEngine = function () {
  25197. if (!this._physicsEngine) {
  25198. return;
  25199. }
  25200. this._physicsEngine.dispose();
  25201. this._physicsEngine = null;
  25202. };
  25203. Scene.prototype.isPhysicsEnabled = function () {
  25204. return this._physicsEngine !== undefined;
  25205. };
  25206. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25207. var mesh = compound.parts[0].mesh;
  25208. if (mesh.physicsImpostor) {
  25209. mesh.physicsImpostor.dispose();
  25210. mesh.physicsImpostor = null;
  25211. }
  25212. };
  25213. // Misc.
  25214. Scene.prototype._rebuildGeometries = function () {
  25215. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25216. var geometry = _a[_i];
  25217. geometry._rebuild();
  25218. }
  25219. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25220. var mesh = _c[_b];
  25221. mesh._rebuild();
  25222. }
  25223. if (this.postProcessManager) {
  25224. this.postProcessManager._rebuild();
  25225. }
  25226. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25227. var layer = _e[_d];
  25228. layer._rebuild();
  25229. }
  25230. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25231. var effectLayer = _g[_f];
  25232. effectLayer._rebuild();
  25233. }
  25234. if (this._boundingBoxRenderer) {
  25235. this._boundingBoxRenderer._rebuild();
  25236. }
  25237. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25238. var system = _j[_h];
  25239. system.rebuild();
  25240. }
  25241. if (this._postProcessRenderPipelineManager) {
  25242. this._postProcessRenderPipelineManager._rebuild();
  25243. }
  25244. };
  25245. Scene.prototype._rebuildTextures = function () {
  25246. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25247. var texture = _a[_i];
  25248. texture._rebuild();
  25249. }
  25250. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25251. };
  25252. /**
  25253. * Creates a default light for the scene.
  25254. * @param replace Whether to replace the existing lights in the scene.
  25255. */
  25256. Scene.prototype.createDefaultLight = function (replace) {
  25257. if (replace === void 0) { replace = false; }
  25258. // Dispose existing light in replace mode.
  25259. if (replace) {
  25260. if (this.lights) {
  25261. for (var i = 0; i < this.lights.length; i++) {
  25262. this.lights[i].dispose();
  25263. }
  25264. }
  25265. }
  25266. // Light
  25267. if (this.lights.length === 0) {
  25268. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25269. }
  25270. };
  25271. /**
  25272. * Creates a default camera for the scene.
  25273. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25274. * @param replace Whether to replace the existing active camera in the scene.
  25275. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25276. */
  25277. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25278. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25279. if (replace === void 0) { replace = false; }
  25280. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25281. // Dispose existing camera in replace mode.
  25282. if (replace) {
  25283. if (this.activeCamera) {
  25284. this.activeCamera.dispose();
  25285. this.activeCamera = null;
  25286. }
  25287. }
  25288. // Camera
  25289. if (!this.activeCamera) {
  25290. var worldExtends = this.getWorldExtends();
  25291. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25292. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25293. var camera;
  25294. var radius = worldSize.length() * 1.5;
  25295. // empty scene scenario!
  25296. if (!isFinite(radius)) {
  25297. radius = 1;
  25298. worldCenter.copyFromFloats(0, 0, 0);
  25299. }
  25300. if (createArcRotateCamera) {
  25301. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25302. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25303. arcRotateCamera.wheelPrecision = 100 / radius;
  25304. camera = arcRotateCamera;
  25305. }
  25306. else {
  25307. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25308. freeCamera.setTarget(worldCenter);
  25309. camera = freeCamera;
  25310. }
  25311. camera.minZ = radius * 0.01;
  25312. camera.maxZ = radius * 1000;
  25313. camera.speed = radius * 0.2;
  25314. this.activeCamera = camera;
  25315. var canvas = this.getEngine().getRenderingCanvas();
  25316. if (attachCameraControls && canvas) {
  25317. camera.attachControl(canvas);
  25318. }
  25319. }
  25320. };
  25321. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25322. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25323. if (replace === void 0) { replace = false; }
  25324. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25325. this.createDefaultLight(replace);
  25326. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25327. };
  25328. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25329. if (pbr === void 0) { pbr = false; }
  25330. if (scale === void 0) { scale = 1000; }
  25331. if (blur === void 0) { blur = 0; }
  25332. if (environmentTexture) {
  25333. this.environmentTexture = environmentTexture;
  25334. }
  25335. if (!this.environmentTexture) {
  25336. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25337. return null;
  25338. }
  25339. // Skybox
  25340. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25341. if (pbr) {
  25342. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25343. hdrSkyboxMaterial.backFaceCulling = false;
  25344. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25345. if (hdrSkyboxMaterial.reflectionTexture) {
  25346. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25347. }
  25348. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25349. hdrSkyboxMaterial.disableLighting = true;
  25350. hdrSkyboxMaterial.twoSidedLighting = true;
  25351. hdrSkybox.infiniteDistance = true;
  25352. hdrSkybox.material = hdrSkyboxMaterial;
  25353. }
  25354. else {
  25355. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25356. skyboxMaterial.backFaceCulling = false;
  25357. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25358. if (skyboxMaterial.reflectionTexture) {
  25359. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25360. }
  25361. skyboxMaterial.disableLighting = true;
  25362. hdrSkybox.infiniteDistance = true;
  25363. hdrSkybox.material = skyboxMaterial;
  25364. }
  25365. return hdrSkybox;
  25366. };
  25367. Scene.prototype.createDefaultEnvironment = function (options) {
  25368. if (BABYLON.EnvironmentHelper) {
  25369. return new BABYLON.EnvironmentHelper(options, this);
  25370. }
  25371. return null;
  25372. };
  25373. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25374. if (webVROptions === void 0) { webVROptions = {}; }
  25375. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25376. };
  25377. // Tags
  25378. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25379. if (tagsQuery === undefined) {
  25380. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25381. return list;
  25382. }
  25383. var listByTags = [];
  25384. forEach = forEach || (function (item) { return; });
  25385. for (var i in list) {
  25386. var item = list[i];
  25387. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25388. listByTags.push(item);
  25389. forEach(item);
  25390. }
  25391. }
  25392. return listByTags;
  25393. };
  25394. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25395. return this._getByTags(this.meshes, tagsQuery, forEach);
  25396. };
  25397. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25398. return this._getByTags(this.cameras, tagsQuery, forEach);
  25399. };
  25400. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25401. return this._getByTags(this.lights, tagsQuery, forEach);
  25402. };
  25403. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25404. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25405. };
  25406. /**
  25407. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25408. * This allowed control for front to back rendering or reversly depending of the special needs.
  25409. *
  25410. * @param renderingGroupId The rendering group id corresponding to its index
  25411. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25412. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25413. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25414. */
  25415. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25416. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25417. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25418. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25419. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25420. };
  25421. /**
  25422. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25423. *
  25424. * @param renderingGroupId The rendering group id corresponding to its index
  25425. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25426. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25427. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25428. */
  25429. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25430. if (depth === void 0) { depth = true; }
  25431. if (stencil === void 0) { stencil = true; }
  25432. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25433. };
  25434. /**
  25435. * Will flag all materials as dirty to trigger new shader compilation
  25436. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25437. */
  25438. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25439. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25440. var material = _a[_i];
  25441. if (predicate && !predicate(material)) {
  25442. continue;
  25443. }
  25444. material.markAsDirty(flag);
  25445. }
  25446. };
  25447. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25448. var _this = this;
  25449. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25450. this._activeRequests.push(request);
  25451. request.onCompleteObservable.add(function (request) {
  25452. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25453. });
  25454. return request;
  25455. };
  25456. /** @ignore */
  25457. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25458. var _this = this;
  25459. return new Promise(function (resolve, reject) {
  25460. _this._loadFile(url, function (data) {
  25461. resolve(data);
  25462. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25463. reject(exception);
  25464. });
  25465. });
  25466. };
  25467. // Statics
  25468. Scene._FOGMODE_NONE = 0;
  25469. Scene._FOGMODE_EXP = 1;
  25470. Scene._FOGMODE_EXP2 = 2;
  25471. Scene._FOGMODE_LINEAR = 3;
  25472. Scene._uniqueIdCounter = 0;
  25473. Scene.MinDeltaTime = 1.0;
  25474. Scene.MaxDeltaTime = 1000.0;
  25475. /** The distance in pixel that you have to move to prevent some events */
  25476. Scene.DragMovementThreshold = 10; // in pixels
  25477. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25478. Scene.LongPressDelay = 500; // in milliseconds
  25479. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25480. Scene.DoubleClickDelay = 300; // in milliseconds
  25481. /** If you need to check double click without raising a single click at first click, enable this flag */
  25482. Scene.ExclusiveDoubleClickMode = false;
  25483. return Scene;
  25484. }());
  25485. BABYLON.Scene = Scene;
  25486. })(BABYLON || (BABYLON = {}));
  25487. //# sourceMappingURL=babylon.scene.js.map
  25488. var BABYLON;
  25489. (function (BABYLON) {
  25490. /**
  25491. * Set of assets to keep when moving a scene into an asset container.
  25492. */
  25493. var KeepAssets = /** @class */ (function () {
  25494. function KeepAssets() {
  25495. /**
  25496. * Cameras to keep.
  25497. */
  25498. this.cameras = new Array();
  25499. /**
  25500. * Lights to keep.
  25501. */
  25502. this.lights = new Array();
  25503. /**
  25504. * Meshes to keep.
  25505. */
  25506. this.meshes = new Array();
  25507. /**
  25508. * Skeletons to keep.
  25509. */
  25510. this.skeletons = new Array();
  25511. /**
  25512. * ParticleSystems to keep.
  25513. */
  25514. this.particleSystems = new Array();
  25515. /**
  25516. * Animations to keep.
  25517. */
  25518. this.animations = new Array();
  25519. /**
  25520. * MultiMaterials to keep.
  25521. */
  25522. this.multiMaterials = new Array();
  25523. /**
  25524. * Materials to keep.
  25525. */
  25526. this.materials = new Array();
  25527. /**
  25528. * MorphTargetManagers to keep.
  25529. */
  25530. this.morphTargetManagers = new Array();
  25531. /**
  25532. * Geometries to keep.
  25533. */
  25534. this.geometries = new Array();
  25535. /**
  25536. * TransformNodes to keep.
  25537. */
  25538. this.transformNodes = new Array();
  25539. /**
  25540. * LensFlareSystems to keep.
  25541. */
  25542. this.lensFlareSystems = new Array();
  25543. /**
  25544. * ShadowGenerators to keep.
  25545. */
  25546. this.shadowGenerators = new Array();
  25547. /**
  25548. * ActionManagers to keep.
  25549. */
  25550. this.actionManagers = new Array();
  25551. /**
  25552. * Sounds to keep.
  25553. */
  25554. this.sounds = new Array();
  25555. }
  25556. return KeepAssets;
  25557. }());
  25558. BABYLON.KeepAssets = KeepAssets;
  25559. /**
  25560. * Container with a set of assets that can be added or removed from a scene.
  25561. */
  25562. var AssetContainer = /** @class */ (function () {
  25563. /**
  25564. * Instantiates an AssetContainer.
  25565. * @param scene The scene the AssetContainer belongs to.
  25566. */
  25567. function AssetContainer(scene) {
  25568. // Objects
  25569. /**
  25570. * Cameras populated in the container.
  25571. */
  25572. this.cameras = new Array();
  25573. /**
  25574. * Lights populated in the container.
  25575. */
  25576. this.lights = new Array();
  25577. /**
  25578. * Meshes populated in the container.
  25579. */
  25580. this.meshes = new Array();
  25581. /**
  25582. * Skeletons populated in the container.
  25583. */
  25584. this.skeletons = new Array();
  25585. /**
  25586. * ParticleSystems populated in the container.
  25587. */
  25588. this.particleSystems = new Array();
  25589. /**
  25590. * Animations populated in the container.
  25591. */
  25592. this.animations = new Array();
  25593. /**
  25594. * MultiMaterials populated in the container.
  25595. */
  25596. this.multiMaterials = new Array();
  25597. /**
  25598. * Materials populated in the container.
  25599. */
  25600. this.materials = new Array();
  25601. /**
  25602. * MorphTargetManagers populated in the container.
  25603. */
  25604. this.morphTargetManagers = new Array();
  25605. /**
  25606. * Geometries populated in the container.
  25607. */
  25608. this.geometries = new Array();
  25609. /**
  25610. * TransformNodes populated in the container.
  25611. */
  25612. this.transformNodes = new Array();
  25613. /**
  25614. * LensFlareSystems populated in the container.
  25615. */
  25616. this.lensFlareSystems = new Array();
  25617. /**
  25618. * ShadowGenerators populated in the container.
  25619. */
  25620. this.shadowGenerators = new Array();
  25621. /**
  25622. * ActionManagers populated in the container.
  25623. */
  25624. this.actionManagers = new Array();
  25625. /**
  25626. * Sounds populated in the container.
  25627. */
  25628. this.sounds = new Array();
  25629. this.scene = scene;
  25630. }
  25631. /**
  25632. * Adds all the assets from the container to the scene.
  25633. */
  25634. AssetContainer.prototype.addAllToScene = function () {
  25635. var _this = this;
  25636. this.cameras.forEach(function (o) {
  25637. _this.scene.addCamera(o);
  25638. });
  25639. this.lights.forEach(function (o) {
  25640. _this.scene.addLight(o);
  25641. });
  25642. this.meshes.forEach(function (o) {
  25643. _this.scene.addMesh(o);
  25644. });
  25645. this.skeletons.forEach(function (o) {
  25646. _this.scene.addSkeleton(o);
  25647. });
  25648. this.particleSystems.forEach(function (o) {
  25649. _this.scene.addParticleSystem(o);
  25650. });
  25651. this.animations.forEach(function (o) {
  25652. _this.scene.addAnimation(o);
  25653. });
  25654. this.multiMaterials.forEach(function (o) {
  25655. _this.scene.addMultiMaterial(o);
  25656. });
  25657. this.materials.forEach(function (o) {
  25658. _this.scene.addMaterial(o);
  25659. });
  25660. this.morphTargetManagers.forEach(function (o) {
  25661. _this.scene.addMorphTargetManager(o);
  25662. });
  25663. this.geometries.forEach(function (o) {
  25664. _this.scene.addGeometry(o);
  25665. });
  25666. this.transformNodes.forEach(function (o) {
  25667. _this.scene.addTransformNode(o);
  25668. });
  25669. this.lensFlareSystems.forEach(function (o) {
  25670. _this.scene.addLensFlareSystem(o);
  25671. });
  25672. this.actionManagers.forEach(function (o) {
  25673. _this.scene.addActionManager(o);
  25674. });
  25675. this.sounds.forEach(function (o) {
  25676. o.play();
  25677. o.autoplay = true;
  25678. _this.scene.mainSoundTrack.AddSound(o);
  25679. });
  25680. };
  25681. /**
  25682. * Removes all the assets in the container from the scene
  25683. */
  25684. AssetContainer.prototype.removeAllFromScene = function () {
  25685. var _this = this;
  25686. this.cameras.forEach(function (o) {
  25687. _this.scene.removeCamera(o);
  25688. });
  25689. this.lights.forEach(function (o) {
  25690. _this.scene.removeLight(o);
  25691. });
  25692. this.meshes.forEach(function (o) {
  25693. _this.scene.removeMesh(o);
  25694. });
  25695. this.skeletons.forEach(function (o) {
  25696. _this.scene.removeSkeleton(o);
  25697. });
  25698. this.particleSystems.forEach(function (o) {
  25699. _this.scene.removeParticleSystem(o);
  25700. });
  25701. this.animations.forEach(function (o) {
  25702. _this.scene.removeAnimation(o);
  25703. });
  25704. this.multiMaterials.forEach(function (o) {
  25705. _this.scene.removeMultiMaterial(o);
  25706. });
  25707. this.materials.forEach(function (o) {
  25708. _this.scene.removeMaterial(o);
  25709. });
  25710. this.morphTargetManagers.forEach(function (o) {
  25711. _this.scene.removeMorphTargetManager(o);
  25712. });
  25713. this.geometries.forEach(function (o) {
  25714. _this.scene.removeGeometry(o);
  25715. });
  25716. this.transformNodes.forEach(function (o) {
  25717. _this.scene.removeTransformNode(o);
  25718. });
  25719. this.lensFlareSystems.forEach(function (o) {
  25720. _this.scene.removeLensFlareSystem(o);
  25721. });
  25722. this.actionManagers.forEach(function (o) {
  25723. _this.scene.removeActionManager(o);
  25724. });
  25725. this.sounds.forEach(function (o) {
  25726. o.stop();
  25727. o.autoplay = false;
  25728. _this.scene.mainSoundTrack.RemoveSound(o);
  25729. });
  25730. };
  25731. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25732. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25733. var asset = sourceAssets_1[_i];
  25734. var move = true;
  25735. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25736. var keepAsset = keepAssets_1[_a];
  25737. if (asset === keepAsset) {
  25738. move = false;
  25739. break;
  25740. }
  25741. }
  25742. if (move) {
  25743. targetAssets.push(asset);
  25744. }
  25745. }
  25746. };
  25747. /**
  25748. * Removes all the assets contained in the scene and adds them to the container.
  25749. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25750. */
  25751. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25752. if (keepAssets === undefined) {
  25753. keepAssets = new KeepAssets();
  25754. }
  25755. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25756. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25757. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25758. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25759. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25760. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25761. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25762. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25763. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25764. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25765. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25766. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25767. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25768. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25769. this.removeAllFromScene();
  25770. };
  25771. return AssetContainer;
  25772. }());
  25773. BABYLON.AssetContainer = AssetContainer;
  25774. })(BABYLON || (BABYLON = {}));
  25775. //# sourceMappingURL=babylon.assetContainer.js.map
  25776. var BABYLON;
  25777. (function (BABYLON) {
  25778. var Buffer = /** @class */ (function () {
  25779. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25780. if (instanced === void 0) { instanced = false; }
  25781. if (engine instanceof BABYLON.Mesh) {
  25782. this._engine = engine.getScene().getEngine();
  25783. }
  25784. else {
  25785. this._engine = engine;
  25786. }
  25787. this._updatable = updatable;
  25788. this._instanced = instanced;
  25789. this._data = data;
  25790. this._strideSize = stride;
  25791. if (!postponeInternalCreation) {
  25792. this.create();
  25793. }
  25794. }
  25795. /**
  25796. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25797. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25798. * @param offset defines offset in the buffer (0 by default)
  25799. * @param size defines the size in floats of attributes (position is 3 for instance)
  25800. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25801. * @param instanced defines if the vertex buffer contains indexed data
  25802. * @returns the new vertex buffer
  25803. */
  25804. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25805. // a lot of these parameters are ignored as they are overriden by the buffer
  25806. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25807. };
  25808. // Properties
  25809. Buffer.prototype.isUpdatable = function () {
  25810. return this._updatable;
  25811. };
  25812. Buffer.prototype.getData = function () {
  25813. return this._data;
  25814. };
  25815. Buffer.prototype.getBuffer = function () {
  25816. return this._buffer;
  25817. };
  25818. Buffer.prototype.getStrideSize = function () {
  25819. return this._strideSize;
  25820. };
  25821. // public getIsInstanced(): boolean {
  25822. // return this._instanced;
  25823. // }
  25824. // public get instanceDivisor(): number {
  25825. // return this._instanceDivisor;
  25826. // }
  25827. // public set instanceDivisor(value: number) {
  25828. // this._instanceDivisor = value;
  25829. // if (value == 0) {
  25830. // this._instanced = false;
  25831. // } else {
  25832. // this._instanced = true;
  25833. // }
  25834. // }
  25835. // Methods
  25836. Buffer.prototype.create = function (data) {
  25837. if (data === void 0) { data = null; }
  25838. if (!data && this._buffer) {
  25839. return; // nothing to do
  25840. }
  25841. data = data || this._data;
  25842. if (!data) {
  25843. return;
  25844. }
  25845. if (!this._buffer) {
  25846. if (this._updatable) {
  25847. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25848. this._data = data;
  25849. }
  25850. else {
  25851. this._buffer = this._engine.createVertexBuffer(data);
  25852. }
  25853. }
  25854. else if (this._updatable) {
  25855. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25856. this._data = data;
  25857. }
  25858. };
  25859. Buffer.prototype._rebuild = function () {
  25860. this._buffer = null;
  25861. this.create(this._data);
  25862. };
  25863. Buffer.prototype.update = function (data) {
  25864. this.create(data);
  25865. };
  25866. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25867. if (!this._buffer) {
  25868. return;
  25869. }
  25870. if (this._updatable) {
  25871. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25872. this._data = null;
  25873. }
  25874. };
  25875. Buffer.prototype.dispose = function () {
  25876. if (!this._buffer) {
  25877. return;
  25878. }
  25879. if (this._engine._releaseBuffer(this._buffer)) {
  25880. this._buffer = null;
  25881. }
  25882. };
  25883. return Buffer;
  25884. }());
  25885. BABYLON.Buffer = Buffer;
  25886. })(BABYLON || (BABYLON = {}));
  25887. //# sourceMappingURL=babylon.buffer.js.map
  25888. var BABYLON;
  25889. (function (BABYLON) {
  25890. var VertexBuffer = /** @class */ (function () {
  25891. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25892. if (data instanceof BABYLON.Buffer) {
  25893. if (!stride) {
  25894. stride = data.getStrideSize();
  25895. }
  25896. this._buffer = data;
  25897. this._ownsBuffer = false;
  25898. }
  25899. else {
  25900. if (!stride) {
  25901. stride = VertexBuffer.DeduceStride(kind);
  25902. }
  25903. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25904. this._ownsBuffer = true;
  25905. }
  25906. this._stride = stride;
  25907. this._instanced = instanced !== undefined ? instanced : false;
  25908. this._instanceDivisor = instanced ? 1 : 0;
  25909. this._offset = offset ? offset : 0;
  25910. this._size = size ? size : stride;
  25911. this._kind = kind;
  25912. }
  25913. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25914. /**
  25915. * Gets or sets the instance divisor when in instanced mode
  25916. */
  25917. get: function () {
  25918. return this._instanceDivisor;
  25919. },
  25920. set: function (value) {
  25921. this._instanceDivisor = value;
  25922. if (value == 0) {
  25923. this._instanced = false;
  25924. }
  25925. else {
  25926. this._instanced = true;
  25927. }
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. VertexBuffer.prototype._rebuild = function () {
  25933. if (!this._buffer) {
  25934. return;
  25935. }
  25936. this._buffer._rebuild();
  25937. };
  25938. /**
  25939. * Returns the kind of the VertexBuffer (string).
  25940. */
  25941. VertexBuffer.prototype.getKind = function () {
  25942. return this._kind;
  25943. };
  25944. // Properties
  25945. /**
  25946. * Boolean : is the VertexBuffer updatable ?
  25947. */
  25948. VertexBuffer.prototype.isUpdatable = function () {
  25949. return this._buffer.isUpdatable();
  25950. };
  25951. /**
  25952. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25953. */
  25954. VertexBuffer.prototype.getData = function () {
  25955. return this._buffer.getData();
  25956. };
  25957. /**
  25958. * Returns the WebGLBuffer associated to the VertexBuffer.
  25959. */
  25960. VertexBuffer.prototype.getBuffer = function () {
  25961. return this._buffer.getBuffer();
  25962. };
  25963. /**
  25964. * Returns the stride of the VertexBuffer (integer).
  25965. */
  25966. VertexBuffer.prototype.getStrideSize = function () {
  25967. return this._stride;
  25968. };
  25969. /**
  25970. * Returns the offset (integer).
  25971. */
  25972. VertexBuffer.prototype.getOffset = function () {
  25973. return this._offset;
  25974. };
  25975. /**
  25976. * Returns the VertexBuffer total size (integer).
  25977. */
  25978. VertexBuffer.prototype.getSize = function () {
  25979. return this._size;
  25980. };
  25981. /**
  25982. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25983. */
  25984. VertexBuffer.prototype.getIsInstanced = function () {
  25985. return this._instanced;
  25986. };
  25987. /**
  25988. * Returns the instancing divisor, zero for non-instanced (integer).
  25989. */
  25990. VertexBuffer.prototype.getInstanceDivisor = function () {
  25991. return this._instanceDivisor;
  25992. };
  25993. // Methods
  25994. /**
  25995. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25996. * Returns the created WebGLBuffer.
  25997. */
  25998. VertexBuffer.prototype.create = function (data) {
  25999. return this._buffer.create(data);
  26000. };
  26001. /**
  26002. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26003. * This function will create a new buffer if the current one is not updatable
  26004. * Returns the updated WebGLBuffer.
  26005. */
  26006. VertexBuffer.prototype.update = function (data) {
  26007. return this._buffer.update(data);
  26008. };
  26009. /**
  26010. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26011. * Returns the directly updated WebGLBuffer.
  26012. */
  26013. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26014. return this._buffer.updateDirectly(data, offset);
  26015. };
  26016. /**
  26017. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26018. */
  26019. VertexBuffer.prototype.dispose = function () {
  26020. if (this._ownsBuffer) {
  26021. this._buffer.dispose();
  26022. }
  26023. };
  26024. Object.defineProperty(VertexBuffer, "PositionKind", {
  26025. get: function () {
  26026. return VertexBuffer._PositionKind;
  26027. },
  26028. enumerable: true,
  26029. configurable: true
  26030. });
  26031. Object.defineProperty(VertexBuffer, "NormalKind", {
  26032. get: function () {
  26033. return VertexBuffer._NormalKind;
  26034. },
  26035. enumerable: true,
  26036. configurable: true
  26037. });
  26038. Object.defineProperty(VertexBuffer, "TangentKind", {
  26039. get: function () {
  26040. return VertexBuffer._TangentKind;
  26041. },
  26042. enumerable: true,
  26043. configurable: true
  26044. });
  26045. Object.defineProperty(VertexBuffer, "UVKind", {
  26046. get: function () {
  26047. return VertexBuffer._UVKind;
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26053. get: function () {
  26054. return VertexBuffer._UV2Kind;
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26060. get: function () {
  26061. return VertexBuffer._UV3Kind;
  26062. },
  26063. enumerable: true,
  26064. configurable: true
  26065. });
  26066. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26067. get: function () {
  26068. return VertexBuffer._UV4Kind;
  26069. },
  26070. enumerable: true,
  26071. configurable: true
  26072. });
  26073. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26074. get: function () {
  26075. return VertexBuffer._UV5Kind;
  26076. },
  26077. enumerable: true,
  26078. configurable: true
  26079. });
  26080. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26081. get: function () {
  26082. return VertexBuffer._UV6Kind;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. Object.defineProperty(VertexBuffer, "ColorKind", {
  26088. get: function () {
  26089. return VertexBuffer._ColorKind;
  26090. },
  26091. enumerable: true,
  26092. configurable: true
  26093. });
  26094. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26095. get: function () {
  26096. return VertexBuffer._MatricesIndicesKind;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26102. get: function () {
  26103. return VertexBuffer._MatricesWeightsKind;
  26104. },
  26105. enumerable: true,
  26106. configurable: true
  26107. });
  26108. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26109. get: function () {
  26110. return VertexBuffer._MatricesIndicesExtraKind;
  26111. },
  26112. enumerable: true,
  26113. configurable: true
  26114. });
  26115. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26116. get: function () {
  26117. return VertexBuffer._MatricesWeightsExtraKind;
  26118. },
  26119. enumerable: true,
  26120. configurable: true
  26121. });
  26122. /**
  26123. * Deduces the stride given a kind.
  26124. * @param kind The kind string to deduce
  26125. * @returns The deduced stride
  26126. */
  26127. VertexBuffer.DeduceStride = function (kind) {
  26128. switch (kind) {
  26129. case VertexBuffer.UVKind:
  26130. case VertexBuffer.UV2Kind:
  26131. case VertexBuffer.UV3Kind:
  26132. case VertexBuffer.UV4Kind:
  26133. case VertexBuffer.UV5Kind:
  26134. case VertexBuffer.UV6Kind:
  26135. return 2;
  26136. case VertexBuffer.NormalKind:
  26137. case VertexBuffer.PositionKind:
  26138. return 3;
  26139. case VertexBuffer.ColorKind:
  26140. case VertexBuffer.MatricesIndicesKind:
  26141. case VertexBuffer.MatricesIndicesExtraKind:
  26142. case VertexBuffer.MatricesWeightsKind:
  26143. case VertexBuffer.MatricesWeightsExtraKind:
  26144. case VertexBuffer.TangentKind:
  26145. return 4;
  26146. default:
  26147. throw new Error("Invalid kind '" + kind + "'");
  26148. }
  26149. };
  26150. // Enums
  26151. VertexBuffer._PositionKind = "position";
  26152. VertexBuffer._NormalKind = "normal";
  26153. VertexBuffer._TangentKind = "tangent";
  26154. VertexBuffer._UVKind = "uv";
  26155. VertexBuffer._UV2Kind = "uv2";
  26156. VertexBuffer._UV3Kind = "uv3";
  26157. VertexBuffer._UV4Kind = "uv4";
  26158. VertexBuffer._UV5Kind = "uv5";
  26159. VertexBuffer._UV6Kind = "uv6";
  26160. VertexBuffer._ColorKind = "color";
  26161. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26162. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26163. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26164. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26165. return VertexBuffer;
  26166. }());
  26167. BABYLON.VertexBuffer = VertexBuffer;
  26168. })(BABYLON || (BABYLON = {}));
  26169. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26170. var BABYLON;
  26171. (function (BABYLON) {
  26172. /**
  26173. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26174. */
  26175. var DummyInternalTextureTracker = /** @class */ (function () {
  26176. function DummyInternalTextureTracker() {
  26177. /**
  26178. * Gets or set the previous tracker in the list
  26179. */
  26180. this.previous = null;
  26181. /**
  26182. * Gets or set the next tracker in the list
  26183. */
  26184. this.next = null;
  26185. }
  26186. return DummyInternalTextureTracker;
  26187. }());
  26188. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26189. })(BABYLON || (BABYLON = {}));
  26190. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26191. var BABYLON;
  26192. (function (BABYLON) {
  26193. /**
  26194. * Class used to store data associated with WebGL texture data for the engine
  26195. * This class should not be used directly
  26196. */
  26197. var InternalTexture = /** @class */ (function () {
  26198. /**
  26199. * Creates a new InternalTexture
  26200. * @param engine defines the engine to use
  26201. * @param dataSource defines the type of data that will be used
  26202. */
  26203. function InternalTexture(engine, dataSource) {
  26204. /**
  26205. * Observable called when the texture is loaded
  26206. */
  26207. this.onLoadedObservable = new BABYLON.Observable();
  26208. /**
  26209. * Gets or set the previous tracker in the list
  26210. */
  26211. this.previous = null;
  26212. /**
  26213. * Gets or set the next tracker in the list
  26214. */
  26215. this.next = null;
  26216. // Private
  26217. /** @ignore */
  26218. this._initialSlot = -1;
  26219. /** @ignore */
  26220. this._designatedSlot = -1;
  26221. /** @ignore */
  26222. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26223. /** @ignore */
  26224. this._comparisonFunction = 0;
  26225. /** @ignore */
  26226. this._references = 1;
  26227. this._engine = engine;
  26228. this._dataSource = dataSource;
  26229. this._webGLTexture = engine._createTexture();
  26230. }
  26231. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26232. /**
  26233. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26234. */
  26235. get: function () {
  26236. return this._dataSource;
  26237. },
  26238. enumerable: true,
  26239. configurable: true
  26240. });
  26241. /**
  26242. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26243. */
  26244. InternalTexture.prototype.incrementReferences = function () {
  26245. this._references++;
  26246. };
  26247. /**
  26248. * Change the size of the texture (not the size of the content)
  26249. * @param width defines the new width
  26250. * @param height defines the new height
  26251. * @param depth defines the new depth (1 by default)
  26252. */
  26253. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26254. if (depth === void 0) { depth = 1; }
  26255. this.width = width;
  26256. this.height = height;
  26257. this.depth = depth;
  26258. this.baseWidth = width;
  26259. this.baseHeight = height;
  26260. this.baseDepth = depth;
  26261. this._size = width * height * depth;
  26262. };
  26263. /** @ignore */
  26264. InternalTexture.prototype._rebuild = function () {
  26265. var _this = this;
  26266. var proxy;
  26267. this.isReady = false;
  26268. this._cachedCoordinatesMode = null;
  26269. this._cachedWrapU = null;
  26270. this._cachedWrapV = null;
  26271. this._cachedAnisotropicFilteringLevel = null;
  26272. switch (this._dataSource) {
  26273. case InternalTexture.DATASOURCE_TEMP:
  26274. return;
  26275. case InternalTexture.DATASOURCE_URL:
  26276. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26277. _this.isReady = true;
  26278. }, null, this._buffer, undefined, this.format);
  26279. proxy._swapAndDie(this);
  26280. return;
  26281. case InternalTexture.DATASOURCE_RAW:
  26282. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26283. proxy._swapAndDie(this);
  26284. this.isReady = true;
  26285. return;
  26286. case InternalTexture.DATASOURCE_RAW3D:
  26287. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26288. proxy._swapAndDie(this);
  26289. this.isReady = true;
  26290. return;
  26291. case InternalTexture.DATASOURCE_DYNAMIC:
  26292. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26293. proxy._swapAndDie(this);
  26294. // The engine will make sure to update content so no need to flag it as isReady = true
  26295. return;
  26296. case InternalTexture.DATASOURCE_RENDERTARGET:
  26297. var options = new BABYLON.RenderTargetCreationOptions();
  26298. options.generateDepthBuffer = this._generateDepthBuffer;
  26299. options.generateMipMaps = this.generateMipMaps;
  26300. options.generateStencilBuffer = this._generateStencilBuffer;
  26301. options.samplingMode = this.samplingMode;
  26302. options.type = this.type;
  26303. if (this.isCube) {
  26304. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26305. }
  26306. else {
  26307. var size = {
  26308. width: this.width,
  26309. height: this.height
  26310. };
  26311. proxy = this._engine.createRenderTargetTexture(size, options);
  26312. }
  26313. proxy._swapAndDie(this);
  26314. this.isReady = true;
  26315. return;
  26316. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26317. var depthTextureOptions = {
  26318. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26319. comparisonFunction: this._comparisonFunction,
  26320. generateStencil: this._generateStencilBuffer,
  26321. };
  26322. if (this.isCube) {
  26323. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26324. }
  26325. else {
  26326. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26327. }
  26328. proxy._swapAndDie(this);
  26329. this.isReady = true;
  26330. return;
  26331. case InternalTexture.DATASOURCE_CUBE:
  26332. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26333. _this.isReady = true;
  26334. }, null, this.format, this._extension);
  26335. proxy._swapAndDie(this);
  26336. return;
  26337. case InternalTexture.DATASOURCE_CUBERAW:
  26338. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26339. proxy._swapAndDie(this);
  26340. this.isReady = true;
  26341. return;
  26342. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26343. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26344. if (proxy) {
  26345. proxy._swapAndDie(_this);
  26346. }
  26347. _this.isReady = true;
  26348. }, null, this.format, this._extension);
  26349. return;
  26350. }
  26351. };
  26352. InternalTexture.prototype._swapAndDie = function (target) {
  26353. target._webGLTexture = this._webGLTexture;
  26354. if (this._framebuffer) {
  26355. target._framebuffer = this._framebuffer;
  26356. }
  26357. if (this._depthStencilBuffer) {
  26358. target._depthStencilBuffer = this._depthStencilBuffer;
  26359. }
  26360. if (this._lodTextureHigh) {
  26361. if (target._lodTextureHigh) {
  26362. target._lodTextureHigh.dispose();
  26363. }
  26364. target._lodTextureHigh = this._lodTextureHigh;
  26365. }
  26366. if (this._lodTextureMid) {
  26367. if (target._lodTextureMid) {
  26368. target._lodTextureMid.dispose();
  26369. }
  26370. target._lodTextureMid = this._lodTextureMid;
  26371. }
  26372. if (this._lodTextureLow) {
  26373. if (target._lodTextureLow) {
  26374. target._lodTextureLow.dispose();
  26375. }
  26376. target._lodTextureLow = this._lodTextureLow;
  26377. }
  26378. var cache = this._engine.getLoadedTexturesCache();
  26379. var index = cache.indexOf(this);
  26380. if (index !== -1) {
  26381. cache.splice(index, 1);
  26382. }
  26383. };
  26384. /**
  26385. * Dispose the current allocated resources
  26386. */
  26387. InternalTexture.prototype.dispose = function () {
  26388. if (!this._webGLTexture) {
  26389. return;
  26390. }
  26391. this._references--;
  26392. if (this._references === 0) {
  26393. this._engine._releaseTexture(this);
  26394. this._webGLTexture = null;
  26395. this.previous = null;
  26396. this.next = null;
  26397. }
  26398. };
  26399. /**
  26400. * The source of the texture data is unknown
  26401. */
  26402. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26403. /**
  26404. * Texture data comes from an URL
  26405. */
  26406. InternalTexture.DATASOURCE_URL = 1;
  26407. /**
  26408. * Texture data is only used for temporary storage
  26409. */
  26410. InternalTexture.DATASOURCE_TEMP = 2;
  26411. /**
  26412. * Texture data comes from raw data (ArrayBuffer)
  26413. */
  26414. InternalTexture.DATASOURCE_RAW = 3;
  26415. /**
  26416. * Texture content is dynamic (video or dynamic texture)
  26417. */
  26418. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26419. /**
  26420. * Texture content is generated by rendering to it
  26421. */
  26422. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26423. /**
  26424. * Texture content is part of a multi render target process
  26425. */
  26426. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26427. /**
  26428. * Texture data comes from a cube data file
  26429. */
  26430. InternalTexture.DATASOURCE_CUBE = 7;
  26431. /**
  26432. * Texture data comes from a raw cube data
  26433. */
  26434. InternalTexture.DATASOURCE_CUBERAW = 8;
  26435. /**
  26436. * Texture data come from a prefiltered cube data file
  26437. */
  26438. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26439. /**
  26440. * Texture content is raw 3D data
  26441. */
  26442. InternalTexture.DATASOURCE_RAW3D = 10;
  26443. /**
  26444. * Texture content is a depth texture
  26445. */
  26446. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26447. return InternalTexture;
  26448. }());
  26449. BABYLON.InternalTexture = InternalTexture;
  26450. })(BABYLON || (BABYLON = {}));
  26451. //# sourceMappingURL=babylon.internalTexture.js.map
  26452. var BABYLON;
  26453. (function (BABYLON) {
  26454. var BaseTexture = /** @class */ (function () {
  26455. function BaseTexture(scene) {
  26456. this._hasAlpha = false;
  26457. this.getAlphaFromRGB = false;
  26458. this.level = 1;
  26459. this.coordinatesIndex = 0;
  26460. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26461. /**
  26462. * | Value | Type | Description |
  26463. * | ----- | ------------------ | ----------- |
  26464. * | 0 | CLAMP_ADDRESSMODE | |
  26465. * | 1 | WRAP_ADDRESSMODE | |
  26466. * | 2 | MIRROR_ADDRESSMODE | |
  26467. */
  26468. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26469. /**
  26470. * | Value | Type | Description |
  26471. * | ----- | ------------------ | ----------- |
  26472. * | 0 | CLAMP_ADDRESSMODE | |
  26473. * | 1 | WRAP_ADDRESSMODE | |
  26474. * | 2 | MIRROR_ADDRESSMODE | |
  26475. */
  26476. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26477. /**
  26478. * | Value | Type | Description |
  26479. * | ----- | ------------------ | ----------- |
  26480. * | 0 | CLAMP_ADDRESSMODE | |
  26481. * | 1 | WRAP_ADDRESSMODE | |
  26482. * | 2 | MIRROR_ADDRESSMODE | |
  26483. */
  26484. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26485. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26486. this.isCube = false;
  26487. this.is3D = false;
  26488. this.gammaSpace = true;
  26489. this.invertZ = false;
  26490. this.lodLevelInAlpha = false;
  26491. this.lodGenerationOffset = 0.0;
  26492. this.lodGenerationScale = 0.8;
  26493. this.isRenderTarget = false;
  26494. this.animations = new Array();
  26495. /**
  26496. * An event triggered when the texture is disposed.
  26497. * @type {BABYLON.Observable}
  26498. */
  26499. this.onDisposeObservable = new BABYLON.Observable();
  26500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26501. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26502. if (this._scene) {
  26503. this._scene.textures.push(this);
  26504. }
  26505. this._uid = null;
  26506. }
  26507. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26508. get: function () {
  26509. return this._hasAlpha;
  26510. },
  26511. set: function (value) {
  26512. if (this._hasAlpha === value) {
  26513. return;
  26514. }
  26515. this._hasAlpha = value;
  26516. if (this._scene) {
  26517. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26518. }
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26524. get: function () {
  26525. return this._coordinatesMode;
  26526. },
  26527. /**
  26528. * How a texture is mapped.
  26529. *
  26530. * | Value | Type | Description |
  26531. * | ----- | ----------------------------------- | ----------- |
  26532. * | 0 | EXPLICIT_MODE | |
  26533. * | 1 | SPHERICAL_MODE | |
  26534. * | 2 | PLANAR_MODE | |
  26535. * | 3 | CUBIC_MODE | |
  26536. * | 4 | PROJECTION_MODE | |
  26537. * | 5 | SKYBOX_MODE | |
  26538. * | 6 | INVCUBIC_MODE | |
  26539. * | 7 | EQUIRECTANGULAR_MODE | |
  26540. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26541. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26542. */
  26543. set: function (value) {
  26544. if (this._coordinatesMode === value) {
  26545. return;
  26546. }
  26547. this._coordinatesMode = value;
  26548. if (this._scene) {
  26549. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26550. }
  26551. },
  26552. enumerable: true,
  26553. configurable: true
  26554. });
  26555. Object.defineProperty(BaseTexture.prototype, "uid", {
  26556. get: function () {
  26557. if (!this._uid) {
  26558. this._uid = BABYLON.Tools.RandomId();
  26559. }
  26560. return this._uid;
  26561. },
  26562. enumerable: true,
  26563. configurable: true
  26564. });
  26565. BaseTexture.prototype.toString = function () {
  26566. return this.name;
  26567. };
  26568. BaseTexture.prototype.getClassName = function () {
  26569. return "BaseTexture";
  26570. };
  26571. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26572. set: function (callback) {
  26573. if (this._onDisposeObserver) {
  26574. this.onDisposeObservable.remove(this._onDisposeObserver);
  26575. }
  26576. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26577. },
  26578. enumerable: true,
  26579. configurable: true
  26580. });
  26581. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26582. get: function () {
  26583. return true;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. BaseTexture.prototype.getScene = function () {
  26589. return this._scene;
  26590. };
  26591. BaseTexture.prototype.getTextureMatrix = function () {
  26592. return BABYLON.Matrix.IdentityReadOnly;
  26593. };
  26594. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26595. return BABYLON.Matrix.IdentityReadOnly;
  26596. };
  26597. BaseTexture.prototype.getInternalTexture = function () {
  26598. return this._texture;
  26599. };
  26600. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26601. return !this.isBlocking || this.isReady();
  26602. };
  26603. BaseTexture.prototype.isReady = function () {
  26604. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26605. this.delayLoad();
  26606. return false;
  26607. }
  26608. if (this._texture) {
  26609. return this._texture.isReady;
  26610. }
  26611. return false;
  26612. };
  26613. BaseTexture.prototype.getSize = function () {
  26614. if (this._texture && this._texture.width) {
  26615. return new BABYLON.Size(this._texture.width, this._texture.height);
  26616. }
  26617. if (this._texture && this._texture._size) {
  26618. return new BABYLON.Size(this._texture._size, this._texture._size);
  26619. }
  26620. return BABYLON.Size.Zero();
  26621. };
  26622. BaseTexture.prototype.getBaseSize = function () {
  26623. if (!this.isReady() || !this._texture)
  26624. return BABYLON.Size.Zero();
  26625. if (this._texture._size) {
  26626. return new BABYLON.Size(this._texture._size, this._texture._size);
  26627. }
  26628. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26629. };
  26630. BaseTexture.prototype.scale = function (ratio) {
  26631. };
  26632. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26633. get: function () {
  26634. return false;
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26640. if (!this._scene) {
  26641. return null;
  26642. }
  26643. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26644. for (var index = 0; index < texturesCache.length; index++) {
  26645. var texturesCacheEntry = texturesCache[index];
  26646. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26647. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26648. texturesCacheEntry.incrementReferences();
  26649. return texturesCacheEntry;
  26650. }
  26651. }
  26652. }
  26653. return null;
  26654. };
  26655. BaseTexture.prototype._rebuild = function () {
  26656. };
  26657. BaseTexture.prototype.delayLoad = function () {
  26658. };
  26659. BaseTexture.prototype.clone = function () {
  26660. return null;
  26661. };
  26662. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26663. get: function () {
  26664. if (!this._texture) {
  26665. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26666. }
  26667. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26673. get: function () {
  26674. if (!this._texture) {
  26675. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26676. }
  26677. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26678. },
  26679. enumerable: true,
  26680. configurable: true
  26681. });
  26682. BaseTexture.prototype.readPixels = function (faceIndex) {
  26683. if (faceIndex === void 0) { faceIndex = 0; }
  26684. if (!this._texture) {
  26685. return null;
  26686. }
  26687. var size = this.getSize();
  26688. var scene = this.getScene();
  26689. if (!scene) {
  26690. return null;
  26691. }
  26692. var engine = scene.getEngine();
  26693. if (this._texture.isCube) {
  26694. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26695. }
  26696. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26697. };
  26698. BaseTexture.prototype.releaseInternalTexture = function () {
  26699. if (this._texture) {
  26700. this._texture.dispose();
  26701. this._texture = null;
  26702. }
  26703. };
  26704. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26705. get: function () {
  26706. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26707. return null;
  26708. }
  26709. if (!this._texture._sphericalPolynomial) {
  26710. this._texture._sphericalPolynomial =
  26711. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26712. }
  26713. return this._texture._sphericalPolynomial;
  26714. },
  26715. set: function (value) {
  26716. if (this._texture) {
  26717. this._texture._sphericalPolynomial = value;
  26718. }
  26719. },
  26720. enumerable: true,
  26721. configurable: true
  26722. });
  26723. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26724. get: function () {
  26725. if (this._texture) {
  26726. return this._texture._lodTextureHigh;
  26727. }
  26728. return null;
  26729. },
  26730. enumerable: true,
  26731. configurable: true
  26732. });
  26733. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26734. get: function () {
  26735. if (this._texture) {
  26736. return this._texture._lodTextureMid;
  26737. }
  26738. return null;
  26739. },
  26740. enumerable: true,
  26741. configurable: true
  26742. });
  26743. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26744. get: function () {
  26745. if (this._texture) {
  26746. return this._texture._lodTextureLow;
  26747. }
  26748. return null;
  26749. },
  26750. enumerable: true,
  26751. configurable: true
  26752. });
  26753. BaseTexture.prototype.dispose = function () {
  26754. if (!this._scene) {
  26755. return;
  26756. }
  26757. // Animations
  26758. this._scene.stopAnimation(this);
  26759. // Remove from scene
  26760. this._scene._removePendingData(this);
  26761. var index = this._scene.textures.indexOf(this);
  26762. if (index >= 0) {
  26763. this._scene.textures.splice(index, 1);
  26764. }
  26765. if (this._texture === undefined) {
  26766. return;
  26767. }
  26768. // Release
  26769. this.releaseInternalTexture();
  26770. // Callback
  26771. this.onDisposeObservable.notifyObservers(this);
  26772. this.onDisposeObservable.clear();
  26773. };
  26774. BaseTexture.prototype.serialize = function () {
  26775. if (!this.name) {
  26776. return null;
  26777. }
  26778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26779. // Animations
  26780. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26781. return serializationObject;
  26782. };
  26783. BaseTexture.WhenAllReady = function (textures, callback) {
  26784. var numRemaining = textures.length;
  26785. if (numRemaining === 0) {
  26786. callback();
  26787. return;
  26788. }
  26789. var _loop_1 = function () {
  26790. texture = textures[i];
  26791. if (texture.isReady()) {
  26792. if (--numRemaining === 0) {
  26793. callback();
  26794. }
  26795. }
  26796. else {
  26797. onLoadObservable = texture.onLoadObservable;
  26798. var onLoadCallback_1 = function () {
  26799. onLoadObservable.removeCallback(onLoadCallback_1);
  26800. if (--numRemaining === 0) {
  26801. callback();
  26802. }
  26803. };
  26804. onLoadObservable.add(onLoadCallback_1);
  26805. }
  26806. };
  26807. var texture, onLoadObservable;
  26808. for (var i = 0; i < textures.length; i++) {
  26809. _loop_1();
  26810. }
  26811. };
  26812. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26813. __decorate([
  26814. BABYLON.serialize()
  26815. ], BaseTexture.prototype, "name", void 0);
  26816. __decorate([
  26817. BABYLON.serialize("hasAlpha")
  26818. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26819. __decorate([
  26820. BABYLON.serialize()
  26821. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26822. __decorate([
  26823. BABYLON.serialize()
  26824. ], BaseTexture.prototype, "level", void 0);
  26825. __decorate([
  26826. BABYLON.serialize()
  26827. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26828. __decorate([
  26829. BABYLON.serialize("coordinatesMode")
  26830. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26831. __decorate([
  26832. BABYLON.serialize()
  26833. ], BaseTexture.prototype, "wrapU", void 0);
  26834. __decorate([
  26835. BABYLON.serialize()
  26836. ], BaseTexture.prototype, "wrapV", void 0);
  26837. __decorate([
  26838. BABYLON.serialize()
  26839. ], BaseTexture.prototype, "wrapR", void 0);
  26840. __decorate([
  26841. BABYLON.serialize()
  26842. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26843. __decorate([
  26844. BABYLON.serialize()
  26845. ], BaseTexture.prototype, "isCube", void 0);
  26846. __decorate([
  26847. BABYLON.serialize()
  26848. ], BaseTexture.prototype, "is3D", void 0);
  26849. __decorate([
  26850. BABYLON.serialize()
  26851. ], BaseTexture.prototype, "gammaSpace", void 0);
  26852. __decorate([
  26853. BABYLON.serialize()
  26854. ], BaseTexture.prototype, "invertZ", void 0);
  26855. __decorate([
  26856. BABYLON.serialize()
  26857. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26858. __decorate([
  26859. BABYLON.serialize()
  26860. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26861. __decorate([
  26862. BABYLON.serialize()
  26863. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26864. __decorate([
  26865. BABYLON.serialize()
  26866. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26867. return BaseTexture;
  26868. }());
  26869. BABYLON.BaseTexture = BaseTexture;
  26870. })(BABYLON || (BABYLON = {}));
  26871. //# sourceMappingURL=babylon.baseTexture.js.map
  26872. var BABYLON;
  26873. (function (BABYLON) {
  26874. var Texture = /** @class */ (function (_super) {
  26875. __extends(Texture, _super);
  26876. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26877. if (noMipmap === void 0) { noMipmap = false; }
  26878. if (invertY === void 0) { invertY = true; }
  26879. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26880. if (onLoad === void 0) { onLoad = null; }
  26881. if (onError === void 0) { onError = null; }
  26882. if (buffer === void 0) { buffer = null; }
  26883. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26884. var _this = _super.call(this, scene) || this;
  26885. _this.uOffset = 0;
  26886. _this.vOffset = 0;
  26887. _this.uScale = 1.0;
  26888. _this.vScale = 1.0;
  26889. _this.uAng = 0;
  26890. _this.vAng = 0;
  26891. _this.wAng = 0;
  26892. _this._isBlocking = true;
  26893. _this.name = url || "";
  26894. _this.url = url;
  26895. _this._noMipmap = noMipmap;
  26896. _this._invertY = invertY;
  26897. _this._samplingMode = samplingMode;
  26898. _this._buffer = buffer;
  26899. _this._deleteBuffer = deleteBuffer;
  26900. if (format) {
  26901. _this._format = format;
  26902. }
  26903. scene = _this.getScene();
  26904. if (!scene) {
  26905. return _this;
  26906. }
  26907. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26908. var load = function () {
  26909. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26910. _this.onLoadObservable.notifyObservers(_this);
  26911. }
  26912. if (onLoad) {
  26913. onLoad();
  26914. }
  26915. if (!_this.isBlocking && scene) {
  26916. scene.resetCachedMaterial();
  26917. }
  26918. };
  26919. if (!_this.url) {
  26920. _this._delayedOnLoad = load;
  26921. _this._delayedOnError = onError;
  26922. return _this;
  26923. }
  26924. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26925. if (!_this._texture) {
  26926. if (!scene.useDelayedTextureLoading) {
  26927. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26928. if (deleteBuffer) {
  26929. delete _this._buffer;
  26930. }
  26931. }
  26932. else {
  26933. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26934. _this._delayedOnLoad = load;
  26935. _this._delayedOnError = onError;
  26936. }
  26937. }
  26938. else {
  26939. if (_this._texture.isReady) {
  26940. BABYLON.Tools.SetImmediate(function () { return load(); });
  26941. }
  26942. else {
  26943. _this._texture.onLoadedObservable.add(load);
  26944. }
  26945. }
  26946. return _this;
  26947. }
  26948. Object.defineProperty(Texture.prototype, "noMipmap", {
  26949. get: function () {
  26950. return this._noMipmap;
  26951. },
  26952. enumerable: true,
  26953. configurable: true
  26954. });
  26955. Object.defineProperty(Texture.prototype, "isBlocking", {
  26956. get: function () {
  26957. return this._isBlocking;
  26958. },
  26959. set: function (value) {
  26960. this._isBlocking = value;
  26961. },
  26962. enumerable: true,
  26963. configurable: true
  26964. });
  26965. Object.defineProperty(Texture.prototype, "samplingMode", {
  26966. get: function () {
  26967. return this._samplingMode;
  26968. },
  26969. enumerable: true,
  26970. configurable: true
  26971. });
  26972. Texture.prototype.updateURL = function (url) {
  26973. this.url = url;
  26974. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26975. this.delayLoad();
  26976. };
  26977. Texture.prototype.delayLoad = function () {
  26978. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26979. return;
  26980. }
  26981. var scene = this.getScene();
  26982. if (!scene) {
  26983. return;
  26984. }
  26985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26986. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26987. if (!this._texture) {
  26988. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26989. if (this._deleteBuffer) {
  26990. delete this._buffer;
  26991. }
  26992. }
  26993. else {
  26994. if (this._delayedOnLoad) {
  26995. if (this._texture.isReady) {
  26996. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26997. }
  26998. else {
  26999. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27000. }
  27001. }
  27002. }
  27003. this._delayedOnLoad = null;
  27004. this._delayedOnError = null;
  27005. };
  27006. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27007. if (!this._texture) {
  27008. return;
  27009. }
  27010. var scene = this.getScene();
  27011. if (!scene) {
  27012. return;
  27013. }
  27014. this._samplingMode = samplingMode;
  27015. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27016. };
  27017. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27018. x *= this.uScale;
  27019. y *= this.vScale;
  27020. x -= 0.5 * this.uScale;
  27021. y -= 0.5 * this.vScale;
  27022. z -= 0.5;
  27023. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27024. t.x += 0.5 * this.uScale + this.uOffset;
  27025. t.y += 0.5 * this.vScale + this.vOffset;
  27026. t.z += 0.5;
  27027. };
  27028. Texture.prototype.getTextureMatrix = function () {
  27029. var _this = this;
  27030. if (this.uOffset === this._cachedUOffset &&
  27031. this.vOffset === this._cachedVOffset &&
  27032. this.uScale === this._cachedUScale &&
  27033. this.vScale === this._cachedVScale &&
  27034. this.uAng === this._cachedUAng &&
  27035. this.vAng === this._cachedVAng &&
  27036. this.wAng === this._cachedWAng) {
  27037. return this._cachedTextureMatrix;
  27038. }
  27039. this._cachedUOffset = this.uOffset;
  27040. this._cachedVOffset = this.vOffset;
  27041. this._cachedUScale = this.uScale;
  27042. this._cachedVScale = this.vScale;
  27043. this._cachedUAng = this.uAng;
  27044. this._cachedVAng = this.vAng;
  27045. this._cachedWAng = this.wAng;
  27046. if (!this._cachedTextureMatrix) {
  27047. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27048. this._rowGenerationMatrix = new BABYLON.Matrix();
  27049. this._t0 = BABYLON.Vector3.Zero();
  27050. this._t1 = BABYLON.Vector3.Zero();
  27051. this._t2 = BABYLON.Vector3.Zero();
  27052. }
  27053. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27054. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27055. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27056. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27057. this._t1.subtractInPlace(this._t0);
  27058. this._t2.subtractInPlace(this._t0);
  27059. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27060. this._cachedTextureMatrix.m[0] = this._t1.x;
  27061. this._cachedTextureMatrix.m[1] = this._t1.y;
  27062. this._cachedTextureMatrix.m[2] = this._t1.z;
  27063. this._cachedTextureMatrix.m[4] = this._t2.x;
  27064. this._cachedTextureMatrix.m[5] = this._t2.y;
  27065. this._cachedTextureMatrix.m[6] = this._t2.z;
  27066. this._cachedTextureMatrix.m[8] = this._t0.x;
  27067. this._cachedTextureMatrix.m[9] = this._t0.y;
  27068. this._cachedTextureMatrix.m[10] = this._t0.z;
  27069. var scene = this.getScene();
  27070. if (!scene) {
  27071. return this._cachedTextureMatrix;
  27072. }
  27073. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27074. return mat.hasTexture(_this);
  27075. });
  27076. return this._cachedTextureMatrix;
  27077. };
  27078. Texture.prototype.getReflectionTextureMatrix = function () {
  27079. var _this = this;
  27080. var scene = this.getScene();
  27081. if (!scene) {
  27082. return this._cachedTextureMatrix;
  27083. }
  27084. if (this.uOffset === this._cachedUOffset &&
  27085. this.vOffset === this._cachedVOffset &&
  27086. this.uScale === this._cachedUScale &&
  27087. this.vScale === this._cachedVScale &&
  27088. this.coordinatesMode === this._cachedCoordinatesMode) {
  27089. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27090. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27091. return this._cachedTextureMatrix;
  27092. }
  27093. }
  27094. else {
  27095. return this._cachedTextureMatrix;
  27096. }
  27097. }
  27098. if (!this._cachedTextureMatrix) {
  27099. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27100. }
  27101. if (!this._projectionModeMatrix) {
  27102. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27103. }
  27104. this._cachedUOffset = this.uOffset;
  27105. this._cachedVOffset = this.vOffset;
  27106. this._cachedUScale = this.uScale;
  27107. this._cachedVScale = this.vScale;
  27108. this._cachedCoordinatesMode = this.coordinatesMode;
  27109. switch (this.coordinatesMode) {
  27110. case Texture.PLANAR_MODE:
  27111. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27112. this._cachedTextureMatrix[0] = this.uScale;
  27113. this._cachedTextureMatrix[5] = this.vScale;
  27114. this._cachedTextureMatrix[12] = this.uOffset;
  27115. this._cachedTextureMatrix[13] = this.vOffset;
  27116. break;
  27117. case Texture.PROJECTION_MODE:
  27118. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27119. this._projectionModeMatrix.m[0] = 0.5;
  27120. this._projectionModeMatrix.m[5] = -0.5;
  27121. this._projectionModeMatrix.m[10] = 0.0;
  27122. this._projectionModeMatrix.m[12] = 0.5;
  27123. this._projectionModeMatrix.m[13] = 0.5;
  27124. this._projectionModeMatrix.m[14] = 1.0;
  27125. this._projectionModeMatrix.m[15] = 1.0;
  27126. var projectionMatrix = scene.getProjectionMatrix();
  27127. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27128. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27129. break;
  27130. default:
  27131. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27132. break;
  27133. }
  27134. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27135. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27136. });
  27137. return this._cachedTextureMatrix;
  27138. };
  27139. Texture.prototype.clone = function () {
  27140. var _this = this;
  27141. return BABYLON.SerializationHelper.Clone(function () {
  27142. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27143. }, this);
  27144. };
  27145. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27146. get: function () {
  27147. if (!this._onLoadObservable) {
  27148. this._onLoadObservable = new BABYLON.Observable();
  27149. }
  27150. return this._onLoadObservable;
  27151. },
  27152. enumerable: true,
  27153. configurable: true
  27154. });
  27155. Texture.prototype.serialize = function () {
  27156. var serializationObject = _super.prototype.serialize.call(this);
  27157. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27158. serializationObject.base64String = this._buffer;
  27159. serializationObject.name = serializationObject.name.replace("data:", "");
  27160. }
  27161. return serializationObject;
  27162. };
  27163. Texture.prototype.getClassName = function () {
  27164. return "Texture";
  27165. };
  27166. Texture.prototype.dispose = function () {
  27167. _super.prototype.dispose.call(this);
  27168. if (this.onLoadObservable) {
  27169. this.onLoadObservable.clear();
  27170. this._onLoadObservable = null;
  27171. }
  27172. this._delayedOnLoad = null;
  27173. this._delayedOnError = null;
  27174. };
  27175. // Statics
  27176. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27177. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27178. if (onLoad === void 0) { onLoad = null; }
  27179. if (onError === void 0) { onError = null; }
  27180. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27181. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27182. };
  27183. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27184. if (parsedTexture.customType) {
  27185. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27186. // Update Sampling Mode
  27187. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27188. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27189. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27190. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27191. }
  27192. }
  27193. return parsedCustomTexture;
  27194. }
  27195. if (parsedTexture.isCube) {
  27196. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27197. }
  27198. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27199. return null;
  27200. }
  27201. var texture = BABYLON.SerializationHelper.Parse(function () {
  27202. var generateMipMaps = true;
  27203. if (parsedTexture.noMipmap) {
  27204. generateMipMaps = false;
  27205. }
  27206. if (parsedTexture.mirrorPlane) {
  27207. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27208. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27209. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27210. return mirrorTexture;
  27211. }
  27212. else if (parsedTexture.isRenderTarget) {
  27213. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27214. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27215. return renderTargetTexture;
  27216. }
  27217. else {
  27218. var texture;
  27219. if (parsedTexture.base64String) {
  27220. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27221. }
  27222. else {
  27223. var url = rootUrl + parsedTexture.name;
  27224. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27225. url = parsedTexture.url;
  27226. }
  27227. texture = new Texture(url, scene, !generateMipMaps);
  27228. }
  27229. return texture;
  27230. }
  27231. }, parsedTexture, scene);
  27232. // Update Sampling Mode
  27233. if (parsedTexture.samplingMode) {
  27234. var sampling = parsedTexture.samplingMode;
  27235. if (texture._samplingMode !== sampling) {
  27236. texture.updateSamplingMode(sampling);
  27237. }
  27238. }
  27239. // Animations
  27240. if (parsedTexture.animations) {
  27241. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27242. var parsedAnimation = parsedTexture.animations[animationIndex];
  27243. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27244. }
  27245. }
  27246. return texture;
  27247. };
  27248. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27249. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27250. if (noMipmap === void 0) { noMipmap = false; }
  27251. if (invertY === void 0) { invertY = true; }
  27252. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27253. if (onLoad === void 0) { onLoad = null; }
  27254. if (onError === void 0) { onError = null; }
  27255. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27256. if (name.substr(0, 5) !== "data:") {
  27257. name = "data:" + name;
  27258. }
  27259. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27260. };
  27261. // Constants
  27262. Texture.NEAREST_SAMPLINGMODE = 1;
  27263. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27264. Texture.BILINEAR_SAMPLINGMODE = 2;
  27265. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27266. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27267. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27268. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27269. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27270. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27271. Texture.NEAREST_LINEAR = 7;
  27272. Texture.NEAREST_NEAREST = 8;
  27273. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27274. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27275. Texture.LINEAR_LINEAR = 11;
  27276. Texture.LINEAR_NEAREST = 12;
  27277. Texture.EXPLICIT_MODE = 0;
  27278. Texture.SPHERICAL_MODE = 1;
  27279. Texture.PLANAR_MODE = 2;
  27280. Texture.CUBIC_MODE = 3;
  27281. Texture.PROJECTION_MODE = 4;
  27282. Texture.SKYBOX_MODE = 5;
  27283. Texture.INVCUBIC_MODE = 6;
  27284. Texture.EQUIRECTANGULAR_MODE = 7;
  27285. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27286. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27287. Texture.CLAMP_ADDRESSMODE = 0;
  27288. Texture.WRAP_ADDRESSMODE = 1;
  27289. Texture.MIRROR_ADDRESSMODE = 2;
  27290. /**
  27291. * 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
  27292. */
  27293. Texture.UseSerializedUrlIfAny = false;
  27294. __decorate([
  27295. BABYLON.serialize()
  27296. ], Texture.prototype, "url", void 0);
  27297. __decorate([
  27298. BABYLON.serialize()
  27299. ], Texture.prototype, "uOffset", void 0);
  27300. __decorate([
  27301. BABYLON.serialize()
  27302. ], Texture.prototype, "vOffset", void 0);
  27303. __decorate([
  27304. BABYLON.serialize()
  27305. ], Texture.prototype, "uScale", void 0);
  27306. __decorate([
  27307. BABYLON.serialize()
  27308. ], Texture.prototype, "vScale", void 0);
  27309. __decorate([
  27310. BABYLON.serialize()
  27311. ], Texture.prototype, "uAng", void 0);
  27312. __decorate([
  27313. BABYLON.serialize()
  27314. ], Texture.prototype, "vAng", void 0);
  27315. __decorate([
  27316. BABYLON.serialize()
  27317. ], Texture.prototype, "wAng", void 0);
  27318. __decorate([
  27319. BABYLON.serialize()
  27320. ], Texture.prototype, "isBlocking", null);
  27321. return Texture;
  27322. }(BABYLON.BaseTexture));
  27323. BABYLON.Texture = Texture;
  27324. })(BABYLON || (BABYLON = {}));
  27325. //# sourceMappingURL=babylon.texture.js.map
  27326. var BABYLON;
  27327. (function (BABYLON) {
  27328. var _InstancesBatch = /** @class */ (function () {
  27329. function _InstancesBatch() {
  27330. this.mustReturn = false;
  27331. this.visibleInstances = new Array();
  27332. this.renderSelf = new Array();
  27333. }
  27334. return _InstancesBatch;
  27335. }());
  27336. BABYLON._InstancesBatch = _InstancesBatch;
  27337. var Mesh = /** @class */ (function (_super) {
  27338. __extends(Mesh, _super);
  27339. /**
  27340. * @constructor
  27341. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27342. * @param {Scene} scene The scene to add this mesh to.
  27343. * @param {Node} parent The parent of this mesh, if it has one
  27344. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27345. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27346. * When false, achieved by calling a clone(), also passing False.
  27347. * This will make creation of children, recursive.
  27348. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27349. */
  27350. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27351. if (scene === void 0) { scene = null; }
  27352. if (parent === void 0) { parent = null; }
  27353. if (source === void 0) { source = null; }
  27354. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27355. var _this = _super.call(this, name, scene) || this;
  27356. // Events
  27357. /**
  27358. * An event triggered before rendering the mesh
  27359. * @type {BABYLON.Observable}
  27360. */
  27361. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27362. /**
  27363. * An event triggered after rendering the mesh
  27364. * @type {BABYLON.Observable}
  27365. */
  27366. _this.onAfterRenderObservable = new BABYLON.Observable();
  27367. /**
  27368. * An event triggered before drawing the mesh
  27369. * @type {BABYLON.Observable}
  27370. */
  27371. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27372. // Members
  27373. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27374. _this.instances = new Array();
  27375. _this._LODLevels = new Array();
  27376. _this._visibleInstances = {};
  27377. _this._renderIdForInstances = new Array();
  27378. _this._batchCache = new _InstancesBatch();
  27379. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27380. // Use by builder only to know what orientation were the mesh build in.
  27381. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27382. _this.overrideMaterialSideOrientation = null;
  27383. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27384. // Will be used to save a source mesh reference, If any
  27385. _this._source = null;
  27386. scene = _this.getScene();
  27387. if (source) {
  27388. // Source mesh
  27389. _this._source = source;
  27390. // Geometry
  27391. if (source._geometry) {
  27392. source._geometry.applyToMesh(_this);
  27393. }
  27394. // Deep copy
  27395. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27396. // Metadata
  27397. if (source.metadata && source.metadata.clone) {
  27398. _this.metadata = source.metadata.clone();
  27399. }
  27400. else {
  27401. _this.metadata = source.metadata;
  27402. }
  27403. // Tags
  27404. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27405. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27406. }
  27407. // Parent
  27408. _this.parent = source.parent;
  27409. // Pivot
  27410. _this.setPivotMatrix(source.getPivotMatrix());
  27411. _this.id = name + "." + source.id;
  27412. // Material
  27413. _this.material = source.material;
  27414. var index;
  27415. if (!doNotCloneChildren) {
  27416. // Children
  27417. var directDescendants = source.getDescendants(true);
  27418. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27419. var child = directDescendants[index_1];
  27420. if (child.clone) {
  27421. child.clone(name + "." + child.name, _this);
  27422. }
  27423. }
  27424. }
  27425. // Physics clone
  27426. var physicsEngine = _this.getScene().getPhysicsEngine();
  27427. if (clonePhysicsImpostor && physicsEngine) {
  27428. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27429. if (impostor) {
  27430. _this.physicsImpostor = impostor.clone(_this);
  27431. }
  27432. }
  27433. // Particles
  27434. for (index = 0; index < scene.particleSystems.length; index++) {
  27435. var system = scene.particleSystems[index];
  27436. if (system.emitter === source) {
  27437. system.clone(system.name, _this);
  27438. }
  27439. }
  27440. _this.computeWorldMatrix(true);
  27441. }
  27442. // Parent
  27443. if (parent !== null) {
  27444. _this.parent = parent;
  27445. }
  27446. return _this;
  27447. }
  27448. Object.defineProperty(Mesh, "FRONTSIDE", {
  27449. /**
  27450. * Mesh side orientation : usually the external or front surface
  27451. */
  27452. get: function () {
  27453. return Mesh._FRONTSIDE;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. Object.defineProperty(Mesh, "BACKSIDE", {
  27459. /**
  27460. * Mesh side orientation : usually the internal or back surface
  27461. */
  27462. get: function () {
  27463. return Mesh._BACKSIDE;
  27464. },
  27465. enumerable: true,
  27466. configurable: true
  27467. });
  27468. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27469. /**
  27470. * Mesh side orientation : both internal and external or front and back surfaces
  27471. */
  27472. get: function () {
  27473. return Mesh._DOUBLESIDE;
  27474. },
  27475. enumerable: true,
  27476. configurable: true
  27477. });
  27478. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27479. /**
  27480. * Mesh side orientation : by default, `FRONTSIDE`
  27481. */
  27482. get: function () {
  27483. return Mesh._DEFAULTSIDE;
  27484. },
  27485. enumerable: true,
  27486. configurable: true
  27487. });
  27488. Object.defineProperty(Mesh, "NO_CAP", {
  27489. /**
  27490. * Mesh cap setting : no cap
  27491. */
  27492. get: function () {
  27493. return Mesh._NO_CAP;
  27494. },
  27495. enumerable: true,
  27496. configurable: true
  27497. });
  27498. Object.defineProperty(Mesh, "CAP_START", {
  27499. /**
  27500. * Mesh cap setting : one cap at the beginning of the mesh
  27501. */
  27502. get: function () {
  27503. return Mesh._CAP_START;
  27504. },
  27505. enumerable: true,
  27506. configurable: true
  27507. });
  27508. Object.defineProperty(Mesh, "CAP_END", {
  27509. /**
  27510. * Mesh cap setting : one cap at the end of the mesh
  27511. */
  27512. get: function () {
  27513. return Mesh._CAP_END;
  27514. },
  27515. enumerable: true,
  27516. configurable: true
  27517. });
  27518. Object.defineProperty(Mesh, "CAP_ALL", {
  27519. /**
  27520. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27521. */
  27522. get: function () {
  27523. return Mesh._CAP_ALL;
  27524. },
  27525. enumerable: true,
  27526. configurable: true
  27527. });
  27528. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27529. set: function (callback) {
  27530. if (this._onBeforeDrawObserver) {
  27531. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27532. }
  27533. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27534. },
  27535. enumerable: true,
  27536. configurable: true
  27537. });
  27538. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27539. get: function () {
  27540. return this._morphTargetManager;
  27541. },
  27542. set: function (value) {
  27543. if (this._morphTargetManager === value) {
  27544. return;
  27545. }
  27546. this._morphTargetManager = value;
  27547. this._syncGeometryWithMorphTargetManager();
  27548. },
  27549. enumerable: true,
  27550. configurable: true
  27551. });
  27552. Object.defineProperty(Mesh.prototype, "source", {
  27553. get: function () {
  27554. return this._source;
  27555. },
  27556. enumerable: true,
  27557. configurable: true
  27558. });
  27559. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27560. get: function () {
  27561. return this._unIndexed;
  27562. },
  27563. set: function (value) {
  27564. if (this._unIndexed !== value) {
  27565. this._unIndexed = value;
  27566. this._markSubMeshesAsAttributesDirty();
  27567. }
  27568. },
  27569. enumerable: true,
  27570. configurable: true
  27571. });
  27572. // Methods
  27573. /**
  27574. * Returns the string "Mesh".
  27575. */
  27576. Mesh.prototype.getClassName = function () {
  27577. return "Mesh";
  27578. };
  27579. /**
  27580. * Returns a string.
  27581. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27582. */
  27583. Mesh.prototype.toString = function (fullDetails) {
  27584. var ret = _super.prototype.toString.call(this, fullDetails);
  27585. ret += ", n vertices: " + this.getTotalVertices();
  27586. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27587. if (this.animations) {
  27588. for (var i = 0; i < this.animations.length; i++) {
  27589. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27590. }
  27591. }
  27592. if (fullDetails) {
  27593. if (this._geometry) {
  27594. var ib = this.getIndices();
  27595. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27596. if (vb && ib) {
  27597. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27598. }
  27599. }
  27600. else {
  27601. ret += ", flat shading: UNKNOWN";
  27602. }
  27603. }
  27604. return ret;
  27605. };
  27606. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27607. /**
  27608. * True if the mesh has some Levels Of Details (LOD).
  27609. * Returns a boolean.
  27610. */
  27611. get: function () {
  27612. return this._LODLevels.length > 0;
  27613. },
  27614. enumerable: true,
  27615. configurable: true
  27616. });
  27617. /**
  27618. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27619. * @returns an array of {BABYLON.MeshLODLevel}
  27620. */
  27621. Mesh.prototype.getLODLevels = function () {
  27622. return this._LODLevels;
  27623. };
  27624. Mesh.prototype._sortLODLevels = function () {
  27625. this._LODLevels.sort(function (a, b) {
  27626. if (a.distance < b.distance) {
  27627. return 1;
  27628. }
  27629. if (a.distance > b.distance) {
  27630. return -1;
  27631. }
  27632. return 0;
  27633. });
  27634. };
  27635. /**
  27636. * Add a mesh as LOD level triggered at the given distance.
  27637. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27638. * @param {number} distance The distance from the center of the object to show this level
  27639. * @param {Mesh} mesh The mesh to be added as LOD level
  27640. * @return {Mesh} This mesh (for chaining)
  27641. */
  27642. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27643. if (mesh && mesh._masterMesh) {
  27644. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27645. return this;
  27646. }
  27647. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27648. this._LODLevels.push(level);
  27649. if (mesh) {
  27650. mesh._masterMesh = this;
  27651. }
  27652. this._sortLODLevels();
  27653. return this;
  27654. };
  27655. /**
  27656. * Returns the LOD level mesh at the passed distance or null if not found.
  27657. * It is related to the method `addLODLevel(distance, mesh)`.
  27658. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27659. * Returns an object Mesh or `null`.
  27660. */
  27661. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27662. for (var index = 0; index < this._LODLevels.length; index++) {
  27663. var level = this._LODLevels[index];
  27664. if (level.distance === distance) {
  27665. return level.mesh;
  27666. }
  27667. }
  27668. return null;
  27669. };
  27670. /**
  27671. * Remove a mesh from the LOD array
  27672. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27673. * @param {Mesh} mesh The mesh to be removed.
  27674. * @return {Mesh} This mesh (for chaining)
  27675. */
  27676. Mesh.prototype.removeLODLevel = function (mesh) {
  27677. for (var index = 0; index < this._LODLevels.length; index++) {
  27678. if (this._LODLevels[index].mesh === mesh) {
  27679. this._LODLevels.splice(index, 1);
  27680. if (mesh) {
  27681. mesh._masterMesh = null;
  27682. }
  27683. }
  27684. }
  27685. this._sortLODLevels();
  27686. return this;
  27687. };
  27688. /**
  27689. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27690. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27691. */
  27692. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27693. if (!this._LODLevels || this._LODLevels.length === 0) {
  27694. return this;
  27695. }
  27696. var bSphere;
  27697. if (boundingSphere) {
  27698. bSphere = boundingSphere;
  27699. }
  27700. else {
  27701. var boundingInfo = this.getBoundingInfo();
  27702. bSphere = boundingInfo.boundingSphere;
  27703. }
  27704. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27705. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27706. if (this.onLODLevelSelection) {
  27707. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27708. }
  27709. return this;
  27710. }
  27711. for (var index = 0; index < this._LODLevels.length; index++) {
  27712. var level = this._LODLevels[index];
  27713. if (level.distance < distanceToCamera) {
  27714. if (level.mesh) {
  27715. level.mesh._preActivate();
  27716. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27717. }
  27718. if (this.onLODLevelSelection) {
  27719. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27720. }
  27721. return level.mesh;
  27722. }
  27723. }
  27724. if (this.onLODLevelSelection) {
  27725. this.onLODLevelSelection(distanceToCamera, this, this);
  27726. }
  27727. return this;
  27728. };
  27729. Object.defineProperty(Mesh.prototype, "geometry", {
  27730. /**
  27731. * Returns the mesh internal Geometry object.
  27732. */
  27733. get: function () {
  27734. return this._geometry;
  27735. },
  27736. enumerable: true,
  27737. configurable: true
  27738. });
  27739. /**
  27740. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27741. */
  27742. Mesh.prototype.getTotalVertices = function () {
  27743. if (this._geometry === null || this._geometry === undefined) {
  27744. return 0;
  27745. }
  27746. return this._geometry.getTotalVertices();
  27747. };
  27748. /**
  27749. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27750. * 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.
  27751. * You can force the copy with forceCopy === true
  27752. * Returns null if the mesh has no geometry or no vertex buffer.
  27753. * Possible `kind` values :
  27754. * - BABYLON.VertexBuffer.PositionKind
  27755. * - BABYLON.VertexBuffer.UVKind
  27756. * - BABYLON.VertexBuffer.UV2Kind
  27757. * - BABYLON.VertexBuffer.UV3Kind
  27758. * - BABYLON.VertexBuffer.UV4Kind
  27759. * - BABYLON.VertexBuffer.UV5Kind
  27760. * - BABYLON.VertexBuffer.UV6Kind
  27761. * - BABYLON.VertexBuffer.ColorKind
  27762. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27763. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27764. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27765. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27766. */
  27767. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27768. if (!this._geometry) {
  27769. return null;
  27770. }
  27771. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27772. };
  27773. /**
  27774. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27775. * Returns `null` if the mesh has no geometry.
  27776. * Possible `kind` values :
  27777. * - BABYLON.VertexBuffer.PositionKind
  27778. * - BABYLON.VertexBuffer.UVKind
  27779. * - BABYLON.VertexBuffer.UV2Kind
  27780. * - BABYLON.VertexBuffer.UV3Kind
  27781. * - BABYLON.VertexBuffer.UV4Kind
  27782. * - BABYLON.VertexBuffer.UV5Kind
  27783. * - BABYLON.VertexBuffer.UV6Kind
  27784. * - BABYLON.VertexBuffer.ColorKind
  27785. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27786. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27787. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27788. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27789. */
  27790. Mesh.prototype.getVertexBuffer = function (kind) {
  27791. if (!this._geometry) {
  27792. return null;
  27793. }
  27794. return this._geometry.getVertexBuffer(kind);
  27795. };
  27796. /**
  27797. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27798. * Possible `kind` values :
  27799. * - BABYLON.VertexBuffer.PositionKind
  27800. * - BABYLON.VertexBuffer.UVKind
  27801. * - BABYLON.VertexBuffer.UV2Kind
  27802. * - BABYLON.VertexBuffer.UV3Kind
  27803. * - BABYLON.VertexBuffer.UV4Kind
  27804. * - BABYLON.VertexBuffer.UV5Kind
  27805. * - BABYLON.VertexBuffer.UV6Kind
  27806. * - BABYLON.VertexBuffer.ColorKind
  27807. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27808. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27809. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27810. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27811. */
  27812. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27813. if (!this._geometry) {
  27814. if (this._delayInfo) {
  27815. return this._delayInfo.indexOf(kind) !== -1;
  27816. }
  27817. return false;
  27818. }
  27819. return this._geometry.isVerticesDataPresent(kind);
  27820. };
  27821. /**
  27822. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27823. * Possible `kind` values :
  27824. * - BABYLON.VertexBuffer.PositionKind
  27825. * - BABYLON.VertexBuffer.UVKind
  27826. * - BABYLON.VertexBuffer.UV2Kind
  27827. * - BABYLON.VertexBuffer.UV3Kind
  27828. * - BABYLON.VertexBuffer.UV4Kind
  27829. * - BABYLON.VertexBuffer.UV5Kind
  27830. * - BABYLON.VertexBuffer.UV6Kind
  27831. * - BABYLON.VertexBuffer.ColorKind
  27832. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27833. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27834. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27835. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27836. */
  27837. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27838. if (!this._geometry) {
  27839. if (this._delayInfo) {
  27840. return this._delayInfo.indexOf(kind) !== -1;
  27841. }
  27842. return false;
  27843. }
  27844. return this._geometry.isVertexBufferUpdatable(kind);
  27845. };
  27846. /**
  27847. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27848. * Possible `kind` values :
  27849. * - BABYLON.VertexBuffer.PositionKind
  27850. * - BABYLON.VertexBuffer.UVKind
  27851. * - BABYLON.VertexBuffer.UV2Kind
  27852. * - BABYLON.VertexBuffer.UV3Kind
  27853. * - BABYLON.VertexBuffer.UV4Kind
  27854. * - BABYLON.VertexBuffer.UV5Kind
  27855. * - BABYLON.VertexBuffer.UV6Kind
  27856. * - BABYLON.VertexBuffer.ColorKind
  27857. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27858. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27859. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27860. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27861. */
  27862. Mesh.prototype.getVerticesDataKinds = function () {
  27863. if (!this._geometry) {
  27864. var result = new Array();
  27865. if (this._delayInfo) {
  27866. this._delayInfo.forEach(function (kind, index, array) {
  27867. result.push(kind);
  27868. });
  27869. }
  27870. return result;
  27871. }
  27872. return this._geometry.getVerticesDataKinds();
  27873. };
  27874. /**
  27875. * Returns a positive integer : the total number of indices in this mesh geometry.
  27876. * Returns zero if the mesh has no geometry.
  27877. */
  27878. Mesh.prototype.getTotalIndices = function () {
  27879. if (!this._geometry) {
  27880. return 0;
  27881. }
  27882. return this._geometry.getTotalIndices();
  27883. };
  27884. /**
  27885. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27886. * 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.
  27887. * Returns an empty array if the mesh has no geometry.
  27888. */
  27889. Mesh.prototype.getIndices = function (copyWhenShared) {
  27890. if (!this._geometry) {
  27891. return [];
  27892. }
  27893. return this._geometry.getIndices(copyWhenShared);
  27894. };
  27895. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27896. get: function () {
  27897. return this._masterMesh !== null && this._masterMesh !== undefined;
  27898. },
  27899. enumerable: true,
  27900. configurable: true
  27901. });
  27902. /**
  27903. * Determine if the current mesh is ready to be rendered
  27904. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27905. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27906. * @returns true if all associated assets are ready (material, textures, shaders)
  27907. */
  27908. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27909. if (completeCheck === void 0) { completeCheck = false; }
  27910. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27911. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27912. return false;
  27913. }
  27914. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27915. return false;
  27916. }
  27917. if (!this.subMeshes || this.subMeshes.length === 0) {
  27918. return true;
  27919. }
  27920. if (!completeCheck) {
  27921. return true;
  27922. }
  27923. var engine = this.getEngine();
  27924. var scene = this.getScene();
  27925. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27926. this.computeWorldMatrix();
  27927. var mat = this.material || scene.defaultMaterial;
  27928. if (mat) {
  27929. if (mat.storeEffectOnSubMeshes) {
  27930. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27931. var subMesh = _a[_i];
  27932. var effectiveMaterial = subMesh.getMaterial();
  27933. if (effectiveMaterial) {
  27934. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27935. return false;
  27936. }
  27937. }
  27938. }
  27939. }
  27940. else {
  27941. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27942. return false;
  27943. }
  27944. }
  27945. }
  27946. // Shadows
  27947. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27948. var light = _c[_b];
  27949. var generator = light.getShadowGenerator();
  27950. if (generator) {
  27951. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27952. var subMesh = _e[_d];
  27953. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27954. return false;
  27955. }
  27956. }
  27957. }
  27958. }
  27959. // LOD
  27960. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27961. var lod = _g[_f];
  27962. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27963. return false;
  27964. }
  27965. }
  27966. return true;
  27967. };
  27968. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27969. /**
  27970. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27971. * This property is pertinent only for updatable parametric shapes.
  27972. */
  27973. get: function () {
  27974. return this._areNormalsFrozen;
  27975. },
  27976. enumerable: true,
  27977. configurable: true
  27978. });
  27979. /**
  27980. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27981. * It has no effect at all on other shapes.
  27982. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27983. * Returns the Mesh.
  27984. */
  27985. Mesh.prototype.freezeNormals = function () {
  27986. this._areNormalsFrozen = true;
  27987. return this;
  27988. };
  27989. /**
  27990. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27991. * It has no effect at all on other shapes.
  27992. * It reactivates the mesh normals computation if it was previously frozen.
  27993. * Returns the Mesh.
  27994. */
  27995. Mesh.prototype.unfreezeNormals = function () {
  27996. this._areNormalsFrozen = false;
  27997. return this;
  27998. };
  27999. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28000. /**
  28001. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28002. */
  28003. set: function (count) {
  28004. this._overridenInstanceCount = count;
  28005. },
  28006. enumerable: true,
  28007. configurable: true
  28008. });
  28009. // Methods
  28010. Mesh.prototype._preActivate = function () {
  28011. var sceneRenderId = this.getScene().getRenderId();
  28012. if (this._preActivateId === sceneRenderId) {
  28013. return this;
  28014. }
  28015. this._preActivateId = sceneRenderId;
  28016. this._visibleInstances = null;
  28017. return this;
  28018. };
  28019. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28020. if (this._visibleInstances) {
  28021. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28022. }
  28023. return this;
  28024. };
  28025. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28026. if (!this._visibleInstances) {
  28027. this._visibleInstances = {};
  28028. this._visibleInstances.defaultRenderId = renderId;
  28029. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28030. }
  28031. if (!this._visibleInstances[renderId]) {
  28032. this._visibleInstances[renderId] = new Array();
  28033. }
  28034. this._visibleInstances[renderId].push(instance);
  28035. return this;
  28036. };
  28037. /**
  28038. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28039. * This means the mesh underlying bounding box and sphere are recomputed.
  28040. * Returns the Mesh.
  28041. */
  28042. Mesh.prototype.refreshBoundingInfo = function () {
  28043. return this._refreshBoundingInfo(false);
  28044. };
  28045. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28046. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28047. return this;
  28048. }
  28049. var data = this._getPositionData(applySkeleton);
  28050. if (data) {
  28051. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28052. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28053. }
  28054. if (this.subMeshes) {
  28055. for (var index = 0; index < this.subMeshes.length; index++) {
  28056. this.subMeshes[index].refreshBoundingInfo();
  28057. }
  28058. }
  28059. this._updateBoundingInfo();
  28060. return this;
  28061. };
  28062. Mesh.prototype._getPositionData = function (applySkeleton) {
  28063. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28064. if (data && applySkeleton && this.skeleton) {
  28065. data = BABYLON.Tools.Slice(data);
  28066. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28067. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28068. if (matricesWeightsData && matricesIndicesData) {
  28069. var needExtras = this.numBoneInfluencers > 4;
  28070. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28071. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28072. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28073. var tempVector = BABYLON.Tmp.Vector3[0];
  28074. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28075. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28076. var matWeightIdx = 0;
  28077. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28078. finalMatrix.reset();
  28079. var inf;
  28080. var weight;
  28081. for (inf = 0; inf < 4; inf++) {
  28082. weight = matricesWeightsData[matWeightIdx + inf];
  28083. if (weight <= 0)
  28084. break;
  28085. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28086. finalMatrix.addToSelf(tempMatrix);
  28087. }
  28088. if (needExtras) {
  28089. for (inf = 0; inf < 4; inf++) {
  28090. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28091. if (weight <= 0)
  28092. break;
  28093. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28094. finalMatrix.addToSelf(tempMatrix);
  28095. }
  28096. }
  28097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28098. tempVector.toArray(data, index);
  28099. }
  28100. }
  28101. }
  28102. return data;
  28103. };
  28104. Mesh.prototype._createGlobalSubMesh = function (force) {
  28105. var totalVertices = this.getTotalVertices();
  28106. if (!totalVertices || !this.getIndices()) {
  28107. return null;
  28108. }
  28109. // Check if we need to recreate the submeshes
  28110. if (this.subMeshes && this.subMeshes.length > 0) {
  28111. var ib = this.getIndices();
  28112. if (!ib) {
  28113. return null;
  28114. }
  28115. var totalIndices = ib.length;
  28116. var needToRecreate = false;
  28117. if (force) {
  28118. needToRecreate = true;
  28119. }
  28120. else {
  28121. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28122. var submesh = _a[_i];
  28123. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28124. needToRecreate = true;
  28125. break;
  28126. }
  28127. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28128. needToRecreate = true;
  28129. break;
  28130. }
  28131. }
  28132. }
  28133. if (!needToRecreate) {
  28134. return this.subMeshes[0];
  28135. }
  28136. }
  28137. this.releaseSubMeshes();
  28138. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28139. };
  28140. Mesh.prototype.subdivide = function (count) {
  28141. if (count < 1) {
  28142. return;
  28143. }
  28144. var totalIndices = this.getTotalIndices();
  28145. var subdivisionSize = (totalIndices / count) | 0;
  28146. var offset = 0;
  28147. // Ensure that subdivisionSize is a multiple of 3
  28148. while (subdivisionSize % 3 !== 0) {
  28149. subdivisionSize++;
  28150. }
  28151. this.releaseSubMeshes();
  28152. for (var index = 0; index < count; index++) {
  28153. if (offset >= totalIndices) {
  28154. break;
  28155. }
  28156. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28157. offset += subdivisionSize;
  28158. }
  28159. this.synchronizeInstances();
  28160. };
  28161. /**
  28162. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28163. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28164. * The `data` are either a numeric array either a Float32Array.
  28165. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28166. * 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).
  28167. * Note that a new underlying VertexBuffer object is created each call.
  28168. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28169. *
  28170. * Possible `kind` values :
  28171. * - BABYLON.VertexBuffer.PositionKind
  28172. * - BABYLON.VertexBuffer.UVKind
  28173. * - BABYLON.VertexBuffer.UV2Kind
  28174. * - BABYLON.VertexBuffer.UV3Kind
  28175. * - BABYLON.VertexBuffer.UV4Kind
  28176. * - BABYLON.VertexBuffer.UV5Kind
  28177. * - BABYLON.VertexBuffer.UV6Kind
  28178. * - BABYLON.VertexBuffer.ColorKind
  28179. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28180. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28181. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28182. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28183. *
  28184. * Returns the Mesh.
  28185. */
  28186. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28187. if (updatable === void 0) { updatable = false; }
  28188. if (!this._geometry) {
  28189. var vertexData = new BABYLON.VertexData();
  28190. vertexData.set(data, kind);
  28191. var scene = this.getScene();
  28192. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28193. }
  28194. else {
  28195. this._geometry.setVerticesData(kind, data, updatable, stride);
  28196. }
  28197. return this;
  28198. };
  28199. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28200. if (updatable === void 0) { updatable = true; }
  28201. var vb = this.getVertexBuffer(kind);
  28202. if (!vb || vb.isUpdatable() === updatable) {
  28203. return;
  28204. }
  28205. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28206. };
  28207. /**
  28208. * Sets the mesh VertexBuffer.
  28209. * Returns the Mesh.
  28210. */
  28211. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28212. if (!this._geometry) {
  28213. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28214. }
  28215. this._geometry.setVerticesBuffer(buffer);
  28216. return this;
  28217. };
  28218. /**
  28219. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28220. * If the mesh has no geometry, it is simply returned as it is.
  28221. * The `data` are either a numeric array either a Float32Array.
  28222. * No new underlying VertexBuffer object is created.
  28223. * 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.
  28224. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28225. *
  28226. * Possible `kind` values :
  28227. * - BABYLON.VertexBuffer.PositionKind
  28228. * - BABYLON.VertexBuffer.UVKind
  28229. * - BABYLON.VertexBuffer.UV2Kind
  28230. * - BABYLON.VertexBuffer.UV3Kind
  28231. * - BABYLON.VertexBuffer.UV4Kind
  28232. * - BABYLON.VertexBuffer.UV5Kind
  28233. * - BABYLON.VertexBuffer.UV6Kind
  28234. * - BABYLON.VertexBuffer.ColorKind
  28235. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28236. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28237. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28238. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28239. *
  28240. * Returns the Mesh.
  28241. */
  28242. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28243. if (!this._geometry) {
  28244. return this;
  28245. }
  28246. if (!makeItUnique) {
  28247. this._geometry.updateVerticesData(kind, data, updateExtends);
  28248. }
  28249. else {
  28250. this.makeGeometryUnique();
  28251. this.updateVerticesData(kind, data, updateExtends, false);
  28252. }
  28253. return this;
  28254. };
  28255. /**
  28256. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28257. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28258. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28259. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28260. * Returns the Mesh.
  28261. */
  28262. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28263. if (computeNormals === void 0) { computeNormals = true; }
  28264. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28265. if (!positions) {
  28266. return this;
  28267. }
  28268. positionFunction(positions);
  28269. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28270. if (computeNormals) {
  28271. var indices = this.getIndices();
  28272. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28273. if (!normals) {
  28274. return this;
  28275. }
  28276. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28277. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28278. }
  28279. return this;
  28280. };
  28281. /**
  28282. * Creates a un-shared specific occurence of the geometry for the mesh.
  28283. * Returns the Mesh.
  28284. */
  28285. Mesh.prototype.makeGeometryUnique = function () {
  28286. if (!this._geometry) {
  28287. return this;
  28288. }
  28289. var oldGeometry = this._geometry;
  28290. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28291. oldGeometry.releaseForMesh(this, true);
  28292. geometry.applyToMesh(this);
  28293. return this;
  28294. };
  28295. /**
  28296. * Sets the mesh indices.
  28297. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28298. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28299. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28300. * This method creates a new index buffer each call.
  28301. * Returns the Mesh.
  28302. */
  28303. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28304. if (totalVertices === void 0) { totalVertices = null; }
  28305. if (updatable === void 0) { updatable = false; }
  28306. if (!this._geometry) {
  28307. var vertexData = new BABYLON.VertexData();
  28308. vertexData.indices = indices;
  28309. var scene = this.getScene();
  28310. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28311. }
  28312. else {
  28313. this._geometry.setIndices(indices, totalVertices, updatable);
  28314. }
  28315. return this;
  28316. };
  28317. /**
  28318. * Update the current index buffer
  28319. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28320. * Returns the Mesh.
  28321. */
  28322. Mesh.prototype.updateIndices = function (indices, offset) {
  28323. if (!this._geometry) {
  28324. return this;
  28325. }
  28326. this._geometry.updateIndices(indices, offset);
  28327. return this;
  28328. };
  28329. /**
  28330. * Invert the geometry to move from a right handed system to a left handed one.
  28331. * Returns the Mesh.
  28332. */
  28333. Mesh.prototype.toLeftHanded = function () {
  28334. if (!this._geometry) {
  28335. return this;
  28336. }
  28337. this._geometry.toLeftHanded();
  28338. return this;
  28339. };
  28340. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28341. if (!this._geometry) {
  28342. return this;
  28343. }
  28344. var engine = this.getScene().getEngine();
  28345. // Wireframe
  28346. var indexToBind;
  28347. if (this._unIndexed) {
  28348. indexToBind = null;
  28349. }
  28350. else {
  28351. switch (fillMode) {
  28352. case BABYLON.Material.PointFillMode:
  28353. indexToBind = null;
  28354. break;
  28355. case BABYLON.Material.WireFrameFillMode:
  28356. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28357. break;
  28358. default:
  28359. case BABYLON.Material.TriangleFillMode:
  28360. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28361. break;
  28362. }
  28363. }
  28364. // VBOs
  28365. this._geometry._bind(effect, indexToBind);
  28366. return this;
  28367. };
  28368. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28369. if (alternate === void 0) { alternate = false; }
  28370. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28371. return this;
  28372. }
  28373. this.onBeforeDrawObservable.notifyObservers(this);
  28374. var scene = this.getScene();
  28375. var engine = scene.getEngine();
  28376. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28377. // or triangles as points
  28378. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28379. }
  28380. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28381. // Triangles as wireframe
  28382. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28383. }
  28384. else {
  28385. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28386. }
  28387. if (scene._isAlternateRenderingEnabled && !alternate) {
  28388. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28389. if (!effect || !scene.activeCamera) {
  28390. return this;
  28391. }
  28392. scene._switchToAlternateCameraConfiguration(true);
  28393. this._effectiveMaterial.bindView(effect);
  28394. this._effectiveMaterial.bindViewProjection(effect);
  28395. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28396. this._draw(subMesh, fillMode, instancesCount, true);
  28397. engine.setViewport(scene.activeCamera.viewport);
  28398. scene._switchToAlternateCameraConfiguration(false);
  28399. this._effectiveMaterial.bindView(effect);
  28400. this._effectiveMaterial.bindViewProjection(effect);
  28401. }
  28402. return this;
  28403. };
  28404. /**
  28405. * Registers for this mesh a javascript function called just before the rendering process.
  28406. * This function is passed the current mesh.
  28407. * Return the Mesh.
  28408. */
  28409. Mesh.prototype.registerBeforeRender = function (func) {
  28410. this.onBeforeRenderObservable.add(func);
  28411. return this;
  28412. };
  28413. /**
  28414. * Disposes a previously registered javascript function called before the rendering.
  28415. * This function is passed the current mesh.
  28416. * Returns the Mesh.
  28417. */
  28418. Mesh.prototype.unregisterBeforeRender = function (func) {
  28419. this.onBeforeRenderObservable.removeCallback(func);
  28420. return this;
  28421. };
  28422. /**
  28423. * Registers for this mesh a javascript function called just after the rendering is complete.
  28424. * This function is passed the current mesh.
  28425. * Returns the Mesh.
  28426. */
  28427. Mesh.prototype.registerAfterRender = function (func) {
  28428. this.onAfterRenderObservable.add(func);
  28429. return this;
  28430. };
  28431. /**
  28432. * Disposes a previously registered javascript function called after the rendering.
  28433. * This function is passed the current mesh.
  28434. * Return the Mesh.
  28435. */
  28436. Mesh.prototype.unregisterAfterRender = function (func) {
  28437. this.onAfterRenderObservable.removeCallback(func);
  28438. return this;
  28439. };
  28440. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28441. var scene = this.getScene();
  28442. this._batchCache.mustReturn = false;
  28443. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28444. this._batchCache.visibleInstances[subMeshId] = null;
  28445. if (this._visibleInstances) {
  28446. var currentRenderId = scene.getRenderId();
  28447. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28448. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28449. var selfRenderId = this._renderId;
  28450. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28451. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28452. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28453. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28454. }
  28455. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28456. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28457. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28458. this._batchCache.mustReturn = true;
  28459. return this._batchCache;
  28460. }
  28461. if (currentRenderId !== selfRenderId) {
  28462. this._batchCache.renderSelf[subMeshId] = false;
  28463. }
  28464. }
  28465. this._renderIdForInstances[subMeshId] = currentRenderId;
  28466. }
  28467. return this._batchCache;
  28468. };
  28469. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28470. var visibleInstances = batch.visibleInstances[subMesh._id];
  28471. if (!visibleInstances) {
  28472. return this;
  28473. }
  28474. var matricesCount = visibleInstances.length + 1;
  28475. var bufferSize = matricesCount * 16 * 4;
  28476. var currentInstancesBufferSize = this._instancesBufferSize;
  28477. var instancesBuffer = this._instancesBuffer;
  28478. while (this._instancesBufferSize < bufferSize) {
  28479. this._instancesBufferSize *= 2;
  28480. }
  28481. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28482. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28483. }
  28484. var offset = 0;
  28485. var instancesCount = 0;
  28486. var world = this.getWorldMatrix();
  28487. if (batch.renderSelf[subMesh._id]) {
  28488. world.copyToArray(this._instancesData, offset);
  28489. offset += 16;
  28490. instancesCount++;
  28491. }
  28492. if (visibleInstances) {
  28493. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28494. var instance = visibleInstances[instanceIndex];
  28495. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28496. offset += 16;
  28497. instancesCount++;
  28498. }
  28499. }
  28500. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28501. if (instancesBuffer) {
  28502. instancesBuffer.dispose();
  28503. }
  28504. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28505. this._instancesBuffer = instancesBuffer;
  28506. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28507. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28508. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28509. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28510. }
  28511. else {
  28512. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28513. }
  28514. this._bind(subMesh, effect, fillMode);
  28515. this._draw(subMesh, fillMode, instancesCount);
  28516. engine.unbindInstanceAttributes();
  28517. return this;
  28518. };
  28519. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28520. var scene = this.getScene();
  28521. var engine = scene.getEngine();
  28522. if (hardwareInstancedRendering) {
  28523. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28524. }
  28525. else {
  28526. if (batch.renderSelf[subMesh._id]) {
  28527. // Draw
  28528. if (onBeforeDraw) {
  28529. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28530. }
  28531. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28532. }
  28533. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28534. if (visibleInstancesForSubMesh) {
  28535. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28536. var instance = visibleInstancesForSubMesh[instanceIndex];
  28537. // World
  28538. var world = instance.getWorldMatrix();
  28539. if (onBeforeDraw) {
  28540. onBeforeDraw(true, world, effectiveMaterial);
  28541. }
  28542. // Draw
  28543. this._draw(subMesh, fillMode);
  28544. }
  28545. }
  28546. }
  28547. return this;
  28548. };
  28549. /**
  28550. * Triggers the draw call for the mesh.
  28551. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28552. * Returns the Mesh.
  28553. */
  28554. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28555. this.checkOcclusionQuery();
  28556. if (this._isOccluded) {
  28557. return this;
  28558. }
  28559. var scene = this.getScene();
  28560. // Managing instances
  28561. var batch = this._getInstancesRenderList(subMesh._id);
  28562. if (batch.mustReturn) {
  28563. return this;
  28564. }
  28565. // Checking geometry state
  28566. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28567. return this;
  28568. }
  28569. this.onBeforeRenderObservable.notifyObservers(this);
  28570. var engine = scene.getEngine();
  28571. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28572. // Material
  28573. var material = subMesh.getMaterial();
  28574. if (!material) {
  28575. return this;
  28576. }
  28577. this._effectiveMaterial = material;
  28578. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28579. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28580. return this;
  28581. }
  28582. }
  28583. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28584. return this;
  28585. }
  28586. // Alpha mode
  28587. if (enableAlphaMode) {
  28588. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28589. }
  28590. // Outline - step 1
  28591. var savedDepthWrite = engine.getDepthWrite();
  28592. if (this.renderOutline) {
  28593. engine.setDepthWrite(false);
  28594. scene.getOutlineRenderer().render(subMesh, batch);
  28595. engine.setDepthWrite(savedDepthWrite);
  28596. }
  28597. var effect;
  28598. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28599. effect = subMesh.effect;
  28600. }
  28601. else {
  28602. effect = this._effectiveMaterial.getEffect();
  28603. }
  28604. if (!effect) {
  28605. return this;
  28606. }
  28607. var sideOrientation = this.overrideMaterialSideOrientation;
  28608. if (sideOrientation == null) {
  28609. sideOrientation = this._effectiveMaterial.sideOrientation;
  28610. if (this._getWorldMatrixDeterminant() < 0) {
  28611. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28612. }
  28613. }
  28614. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28615. if (this._effectiveMaterial.forceDepthWrite) {
  28616. engine.setDepthWrite(true);
  28617. }
  28618. // Bind
  28619. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28620. if (!hardwareInstancedRendering) {
  28621. this._bind(subMesh, effect, fillMode);
  28622. }
  28623. var world = this.getWorldMatrix();
  28624. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28625. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28626. }
  28627. else {
  28628. this._effectiveMaterial.bind(world, this);
  28629. }
  28630. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28631. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28632. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28633. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28634. }
  28635. // Draw
  28636. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28637. // Unbind
  28638. this._effectiveMaterial.unbind();
  28639. // Outline - step 2
  28640. if (this.renderOutline && savedDepthWrite) {
  28641. engine.setDepthWrite(true);
  28642. engine.setColorWrite(false);
  28643. scene.getOutlineRenderer().render(subMesh, batch);
  28644. engine.setColorWrite(true);
  28645. }
  28646. // Overlay
  28647. if (this.renderOverlay) {
  28648. var currentMode = engine.getAlphaMode();
  28649. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28650. scene.getOutlineRenderer().render(subMesh, batch, true);
  28651. engine.setAlphaMode(currentMode);
  28652. }
  28653. this.onAfterRenderObservable.notifyObservers(this);
  28654. return this;
  28655. };
  28656. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28657. if (isInstance && effectiveMaterial) {
  28658. effectiveMaterial.bindOnlyWorldMatrix(world);
  28659. }
  28660. };
  28661. /**
  28662. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28663. */
  28664. Mesh.prototype.getEmittedParticleSystems = function () {
  28665. var results = new Array();
  28666. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28667. var particleSystem = this.getScene().particleSystems[index];
  28668. if (particleSystem.emitter === this) {
  28669. results.push(particleSystem);
  28670. }
  28671. }
  28672. return results;
  28673. };
  28674. /**
  28675. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28676. */
  28677. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28678. var results = new Array();
  28679. var descendants = this.getDescendants();
  28680. descendants.push(this);
  28681. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28682. var particleSystem = this.getScene().particleSystems[index];
  28683. var emitter = particleSystem.emitter;
  28684. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28685. results.push(particleSystem);
  28686. }
  28687. }
  28688. return results;
  28689. };
  28690. Mesh.prototype._checkDelayState = function () {
  28691. var scene = this.getScene();
  28692. if (this._geometry) {
  28693. this._geometry.load(scene);
  28694. }
  28695. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28697. this._queueLoad(scene);
  28698. }
  28699. return this;
  28700. };
  28701. Mesh.prototype._queueLoad = function (scene) {
  28702. var _this = this;
  28703. scene._addPendingData(this);
  28704. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28705. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28706. if (data instanceof ArrayBuffer) {
  28707. _this._delayLoadingFunction(data, _this);
  28708. }
  28709. else {
  28710. _this._delayLoadingFunction(JSON.parse(data), _this);
  28711. }
  28712. _this.instances.forEach(function (instance) {
  28713. instance._syncSubMeshes();
  28714. });
  28715. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28716. scene._removePendingData(_this);
  28717. }, function () { }, scene.database, getBinaryData);
  28718. return this;
  28719. };
  28720. /**
  28721. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28722. */
  28723. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28724. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28725. return false;
  28726. }
  28727. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28728. return false;
  28729. }
  28730. this._checkDelayState();
  28731. return true;
  28732. };
  28733. /**
  28734. * Sets the mesh material by the material or multiMaterial `id` property.
  28735. * The material `id` is a string identifying the material or the multiMaterial.
  28736. * This method returns the Mesh.
  28737. */
  28738. Mesh.prototype.setMaterialByID = function (id) {
  28739. var materials = this.getScene().materials;
  28740. var index;
  28741. for (index = materials.length - 1; index > -1; index--) {
  28742. if (materials[index].id === id) {
  28743. this.material = materials[index];
  28744. return this;
  28745. }
  28746. }
  28747. // Multi
  28748. var multiMaterials = this.getScene().multiMaterials;
  28749. for (index = multiMaterials.length - 1; index > -1; index--) {
  28750. if (multiMaterials[index].id === id) {
  28751. this.material = multiMaterials[index];
  28752. return this;
  28753. }
  28754. }
  28755. return this;
  28756. };
  28757. /**
  28758. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28759. */
  28760. Mesh.prototype.getAnimatables = function () {
  28761. var results = new Array();
  28762. if (this.material) {
  28763. results.push(this.material);
  28764. }
  28765. if (this.skeleton) {
  28766. results.push(this.skeleton);
  28767. }
  28768. return results;
  28769. };
  28770. /**
  28771. * Modifies the mesh geometry according to the passed transformation matrix.
  28772. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28773. * The mesh normals are modified accordingly the same transformation.
  28774. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28775. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28776. * Returns the Mesh.
  28777. */
  28778. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28779. // Position
  28780. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28781. return this;
  28782. }
  28783. var submeshes = this.subMeshes.splice(0);
  28784. this._resetPointsArrayCache();
  28785. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28786. var temp = new Array();
  28787. var index;
  28788. for (index = 0; index < data.length; index += 3) {
  28789. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28790. }
  28791. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28792. // Normals
  28793. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28794. return this;
  28795. }
  28796. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28797. temp = [];
  28798. for (index = 0; index < data.length; index += 3) {
  28799. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28800. }
  28801. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28802. // flip faces?
  28803. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28804. this.flipFaces();
  28805. }
  28806. // Restore submeshes
  28807. this.releaseSubMeshes();
  28808. this.subMeshes = submeshes;
  28809. return this;
  28810. };
  28811. /**
  28812. * Modifies the mesh geometry according to its own current World Matrix.
  28813. * The mesh World Matrix is then reset.
  28814. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28815. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28816. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28817. * Returns the Mesh.
  28818. */
  28819. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28820. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28821. this.scaling.copyFromFloats(1, 1, 1);
  28822. this.position.copyFromFloats(0, 0, 0);
  28823. this.rotation.copyFromFloats(0, 0, 0);
  28824. //only if quaternion is already set
  28825. if (this.rotationQuaternion) {
  28826. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28827. }
  28828. this._worldMatrix = BABYLON.Matrix.Identity();
  28829. return this;
  28830. };
  28831. Object.defineProperty(Mesh.prototype, "_positions", {
  28832. // Cache
  28833. get: function () {
  28834. if (this._geometry) {
  28835. return this._geometry._positions;
  28836. }
  28837. return null;
  28838. },
  28839. enumerable: true,
  28840. configurable: true
  28841. });
  28842. Mesh.prototype._resetPointsArrayCache = function () {
  28843. if (this._geometry) {
  28844. this._geometry._resetPointsArrayCache();
  28845. }
  28846. return this;
  28847. };
  28848. Mesh.prototype._generatePointsArray = function () {
  28849. if (this._geometry) {
  28850. return this._geometry._generatePointsArray();
  28851. }
  28852. return false;
  28853. };
  28854. /**
  28855. * Returns a new Mesh object generated from the current mesh properties.
  28856. * This method must not get confused with createInstance().
  28857. * The parameter `name` is a string, the name given to the new mesh.
  28858. * The optional parameter `newParent` can be any Node object (default `null`).
  28859. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28860. * 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.
  28861. */
  28862. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28863. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28864. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28865. };
  28866. /**
  28867. * Releases resources associated with this mesh.
  28868. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28869. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28870. */
  28871. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28872. var _this = this;
  28873. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28874. this.morphTargetManager = null;
  28875. if (this._geometry) {
  28876. this._geometry.releaseForMesh(this, true);
  28877. }
  28878. // Sources
  28879. var meshes = this.getScene().meshes;
  28880. meshes.forEach(function (abstractMesh) {
  28881. var mesh = abstractMesh;
  28882. if (mesh._source && mesh._source === _this) {
  28883. mesh._source = null;
  28884. }
  28885. });
  28886. this._source = null;
  28887. // Instances
  28888. if (this._instancesBuffer) {
  28889. this._instancesBuffer.dispose();
  28890. this._instancesBuffer = null;
  28891. }
  28892. while (this.instances.length) {
  28893. this.instances[0].dispose();
  28894. }
  28895. // Effect layers.
  28896. var effectLayers = this.getScene().effectLayers;
  28897. for (var i = 0; i < effectLayers.length; i++) {
  28898. var effectLayer = effectLayers[i];
  28899. if (effectLayer) {
  28900. effectLayer._disposeMesh(this);
  28901. }
  28902. }
  28903. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28904. };
  28905. /**
  28906. * Modifies the mesh geometry according to a displacement map.
  28907. * 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.
  28908. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28909. * This method returns nothing.
  28910. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28911. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28912. * 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.
  28913. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28914. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28915. *
  28916. * Returns the Mesh.
  28917. */
  28918. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28919. var _this = this;
  28920. var scene = this.getScene();
  28921. var onload = function (img) {
  28922. // Getting height map data
  28923. var canvas = document.createElement("canvas");
  28924. var context = canvas.getContext("2d");
  28925. var heightMapWidth = img.width;
  28926. var heightMapHeight = img.height;
  28927. canvas.width = heightMapWidth;
  28928. canvas.height = heightMapHeight;
  28929. context.drawImage(img, 0, 0);
  28930. // Create VertexData from map data
  28931. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28932. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28933. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28934. //execute success callback, if set
  28935. if (onSuccess) {
  28936. onSuccess(_this);
  28937. }
  28938. };
  28939. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28940. return this;
  28941. };
  28942. /**
  28943. * Modifies the mesh geometry according to a displacementMap buffer.
  28944. * 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.
  28945. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28946. * This method returns nothing.
  28947. * 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.
  28948. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28949. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28950. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28951. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28952. *
  28953. * Returns the Mesh.
  28954. */
  28955. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28956. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28957. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28958. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28959. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28960. return this;
  28961. }
  28962. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28963. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28964. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28965. var position = BABYLON.Vector3.Zero();
  28966. var normal = BABYLON.Vector3.Zero();
  28967. var uv = BABYLON.Vector2.Zero();
  28968. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28969. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28970. for (var index = 0; index < positions.length; index += 3) {
  28971. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28972. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28973. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28974. // Compute height
  28975. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28976. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28977. var pos = (u + v * heightMapWidth) * 4;
  28978. var r = buffer[pos] / 255.0;
  28979. var g = buffer[pos + 1] / 255.0;
  28980. var b = buffer[pos + 2] / 255.0;
  28981. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28982. normal.normalize();
  28983. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28984. position = position.add(normal);
  28985. position.toArray(positions, index);
  28986. }
  28987. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28988. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28989. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28990. return this;
  28991. };
  28992. /**
  28993. * Modify the mesh to get a flat shading rendering.
  28994. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28995. * This method returns the Mesh.
  28996. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28997. */
  28998. Mesh.prototype.convertToFlatShadedMesh = function () {
  28999. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29000. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29001. var kinds = this.getVerticesDataKinds();
  29002. var vbs = {};
  29003. var data = {};
  29004. var newdata = {};
  29005. var updatableNormals = false;
  29006. var kindIndex;
  29007. var kind;
  29008. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29009. kind = kinds[kindIndex];
  29010. var vertexBuffer = this.getVertexBuffer(kind);
  29011. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29012. updatableNormals = vertexBuffer.isUpdatable();
  29013. kinds.splice(kindIndex, 1);
  29014. kindIndex--;
  29015. continue;
  29016. }
  29017. vbs[kind] = vertexBuffer;
  29018. data[kind] = vbs[kind].getData();
  29019. newdata[kind] = [];
  29020. }
  29021. // Save previous submeshes
  29022. var previousSubmeshes = this.subMeshes.slice(0);
  29023. var indices = this.getIndices();
  29024. var totalIndices = this.getTotalIndices();
  29025. // Generating unique vertices per face
  29026. var index;
  29027. for (index = 0; index < totalIndices; index++) {
  29028. var vertexIndex = indices[index];
  29029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29030. kind = kinds[kindIndex];
  29031. var stride = vbs[kind].getStrideSize();
  29032. for (var offset = 0; offset < stride; offset++) {
  29033. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29034. }
  29035. }
  29036. }
  29037. // Updating faces & normal
  29038. var normals = [];
  29039. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29040. for (index = 0; index < totalIndices; index += 3) {
  29041. indices[index] = index;
  29042. indices[index + 1] = index + 1;
  29043. indices[index + 2] = index + 2;
  29044. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29045. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29046. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29047. var p1p2 = p1.subtract(p2);
  29048. var p3p2 = p3.subtract(p2);
  29049. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29050. // Store same normals for every vertex
  29051. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29052. normals.push(normal.x);
  29053. normals.push(normal.y);
  29054. normals.push(normal.z);
  29055. }
  29056. }
  29057. this.setIndices(indices);
  29058. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29059. // Updating vertex buffers
  29060. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29061. kind = kinds[kindIndex];
  29062. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29063. }
  29064. // Updating submeshes
  29065. this.releaseSubMeshes();
  29066. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29067. var previousOne = previousSubmeshes[submeshIndex];
  29068. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29069. }
  29070. this.synchronizeInstances();
  29071. return this;
  29072. };
  29073. /**
  29074. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29075. * In other words, more vertices, no more indices and a single bigger VBO.
  29076. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29077. * Returns the Mesh.
  29078. */
  29079. Mesh.prototype.convertToUnIndexedMesh = function () {
  29080. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29081. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29082. var kinds = this.getVerticesDataKinds();
  29083. var vbs = {};
  29084. var data = {};
  29085. var newdata = {};
  29086. var kindIndex;
  29087. var kind;
  29088. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29089. kind = kinds[kindIndex];
  29090. var vertexBuffer = this.getVertexBuffer(kind);
  29091. vbs[kind] = vertexBuffer;
  29092. data[kind] = vbs[kind].getData();
  29093. newdata[kind] = [];
  29094. }
  29095. // Save previous submeshes
  29096. var previousSubmeshes = this.subMeshes.slice(0);
  29097. var indices = this.getIndices();
  29098. var totalIndices = this.getTotalIndices();
  29099. // Generating unique vertices per face
  29100. var index;
  29101. for (index = 0; index < totalIndices; index++) {
  29102. var vertexIndex = indices[index];
  29103. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29104. kind = kinds[kindIndex];
  29105. var stride = vbs[kind].getStrideSize();
  29106. for (var offset = 0; offset < stride; offset++) {
  29107. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29108. }
  29109. }
  29110. }
  29111. // Updating indices
  29112. for (index = 0; index < totalIndices; index += 3) {
  29113. indices[index] = index;
  29114. indices[index + 1] = index + 1;
  29115. indices[index + 2] = index + 2;
  29116. }
  29117. this.setIndices(indices);
  29118. // Updating vertex buffers
  29119. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29120. kind = kinds[kindIndex];
  29121. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29122. }
  29123. // Updating submeshes
  29124. this.releaseSubMeshes();
  29125. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29126. var previousOne = previousSubmeshes[submeshIndex];
  29127. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29128. }
  29129. this._unIndexed = true;
  29130. this.synchronizeInstances();
  29131. return this;
  29132. };
  29133. /**
  29134. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29135. * This method returns the Mesh.
  29136. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29137. */
  29138. Mesh.prototype.flipFaces = function (flipNormals) {
  29139. if (flipNormals === void 0) { flipNormals = false; }
  29140. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29141. var i;
  29142. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29143. for (i = 0; i < vertex_data.normals.length; i++) {
  29144. vertex_data.normals[i] *= -1;
  29145. }
  29146. }
  29147. if (vertex_data.indices) {
  29148. var temp;
  29149. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29150. // reassign indices
  29151. temp = vertex_data.indices[i + 1];
  29152. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29153. vertex_data.indices[i + 2] = temp;
  29154. }
  29155. }
  29156. vertex_data.applyToMesh(this);
  29157. return this;
  29158. };
  29159. // Instances
  29160. /**
  29161. * Creates a new InstancedMesh object from the mesh model.
  29162. * An instance shares the same properties and the same material than its model.
  29163. * Only these properties of each instance can then be set individually :
  29164. * - position
  29165. * - rotation
  29166. * - rotationQuaternion
  29167. * - setPivotMatrix
  29168. * - scaling
  29169. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29170. * Warning : this method is not supported for Line mesh and LineSystem
  29171. */
  29172. Mesh.prototype.createInstance = function (name) {
  29173. return new BABYLON.InstancedMesh(name, this);
  29174. };
  29175. /**
  29176. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29177. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29178. * This method returns the Mesh.
  29179. */
  29180. Mesh.prototype.synchronizeInstances = function () {
  29181. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29182. var instance = this.instances[instanceIndex];
  29183. instance._syncSubMeshes();
  29184. }
  29185. return this;
  29186. };
  29187. /**
  29188. * Simplify the mesh according to the given array of settings.
  29189. * Function will return immediately and will simplify async. It returns the Mesh.
  29190. * @param settings a collection of simplification settings.
  29191. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29192. * @param type the type of simplification to run.
  29193. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29194. */
  29195. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29196. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29197. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29198. this.getScene().simplificationQueue.addTask({
  29199. settings: settings,
  29200. parallelProcessing: parallelProcessing,
  29201. mesh: this,
  29202. simplificationType: simplificationType,
  29203. successCallback: successCallback
  29204. });
  29205. return this;
  29206. };
  29207. /**
  29208. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29209. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29210. * This should be used together with the simplification to avoid disappearing triangles.
  29211. * Returns the Mesh.
  29212. * @param successCallback an optional success callback to be called after the optimization finished.
  29213. */
  29214. Mesh.prototype.optimizeIndices = function (successCallback) {
  29215. var _this = this;
  29216. var indices = this.getIndices();
  29217. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29218. if (!positions || !indices) {
  29219. return this;
  29220. }
  29221. var vectorPositions = new Array();
  29222. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29223. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29224. }
  29225. var dupes = new Array();
  29226. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29227. var realPos = vectorPositions.length - 1 - iteration;
  29228. var testedPosition = vectorPositions[realPos];
  29229. for (var j = 0; j < realPos; ++j) {
  29230. var againstPosition = vectorPositions[j];
  29231. if (testedPosition.equals(againstPosition)) {
  29232. dupes[realPos] = j;
  29233. break;
  29234. }
  29235. }
  29236. }, function () {
  29237. for (var i = 0; i < indices.length; ++i) {
  29238. indices[i] = dupes[indices[i]] || indices[i];
  29239. }
  29240. //indices are now reordered
  29241. var originalSubMeshes = _this.subMeshes.slice(0);
  29242. _this.setIndices(indices);
  29243. _this.subMeshes = originalSubMeshes;
  29244. if (successCallback) {
  29245. successCallback(_this);
  29246. }
  29247. });
  29248. return this;
  29249. };
  29250. Mesh.prototype.serialize = function (serializationObject) {
  29251. serializationObject.name = this.name;
  29252. serializationObject.id = this.id;
  29253. serializationObject.type = this.getClassName();
  29254. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29255. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29256. }
  29257. serializationObject.position = this.position.asArray();
  29258. if (this.rotationQuaternion) {
  29259. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29260. }
  29261. else if (this.rotation) {
  29262. serializationObject.rotation = this.rotation.asArray();
  29263. }
  29264. serializationObject.scaling = this.scaling.asArray();
  29265. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29266. serializationObject.isEnabled = this.isEnabled(false);
  29267. serializationObject.isVisible = this.isVisible;
  29268. serializationObject.infiniteDistance = this.infiniteDistance;
  29269. serializationObject.pickable = this.isPickable;
  29270. serializationObject.receiveShadows = this.receiveShadows;
  29271. serializationObject.billboardMode = this.billboardMode;
  29272. serializationObject.visibility = this.visibility;
  29273. serializationObject.checkCollisions = this.checkCollisions;
  29274. serializationObject.isBlocker = this.isBlocker;
  29275. // Parent
  29276. if (this.parent) {
  29277. serializationObject.parentId = this.parent.id;
  29278. }
  29279. // Geometry
  29280. serializationObject.isUnIndexed = this.isUnIndexed;
  29281. var geometry = this._geometry;
  29282. if (geometry) {
  29283. var geometryId = geometry.id;
  29284. serializationObject.geometryId = geometryId;
  29285. // SubMeshes
  29286. serializationObject.subMeshes = [];
  29287. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29288. var subMesh = this.subMeshes[subIndex];
  29289. serializationObject.subMeshes.push({
  29290. materialIndex: subMesh.materialIndex,
  29291. verticesStart: subMesh.verticesStart,
  29292. verticesCount: subMesh.verticesCount,
  29293. indexStart: subMesh.indexStart,
  29294. indexCount: subMesh.indexCount
  29295. });
  29296. }
  29297. }
  29298. // Material
  29299. if (this.material) {
  29300. serializationObject.materialId = this.material.id;
  29301. }
  29302. else {
  29303. this.material = null;
  29304. }
  29305. // Morph targets
  29306. if (this.morphTargetManager) {
  29307. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29308. }
  29309. // Skeleton
  29310. if (this.skeleton) {
  29311. serializationObject.skeletonId = this.skeleton.id;
  29312. }
  29313. // Physics
  29314. //TODO implement correct serialization for physics impostors.
  29315. var impostor = this.getPhysicsImpostor();
  29316. if (impostor) {
  29317. serializationObject.physicsMass = impostor.getParam("mass");
  29318. serializationObject.physicsFriction = impostor.getParam("friction");
  29319. serializationObject.physicsRestitution = impostor.getParam("mass");
  29320. serializationObject.physicsImpostor = impostor.type;
  29321. }
  29322. // Metadata
  29323. if (this.metadata) {
  29324. serializationObject.metadata = this.metadata;
  29325. }
  29326. // Instances
  29327. serializationObject.instances = [];
  29328. for (var index = 0; index < this.instances.length; index++) {
  29329. var instance = this.instances[index];
  29330. var serializationInstance = {
  29331. name: instance.name,
  29332. id: instance.id,
  29333. position: instance.position.asArray(),
  29334. scaling: instance.scaling.asArray()
  29335. };
  29336. if (instance.rotationQuaternion) {
  29337. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29338. }
  29339. else if (instance.rotation) {
  29340. serializationInstance.rotation = instance.rotation.asArray();
  29341. }
  29342. serializationObject.instances.push(serializationInstance);
  29343. // Animations
  29344. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29345. serializationInstance.ranges = instance.serializeAnimationRanges();
  29346. }
  29347. //
  29348. // Animations
  29349. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29350. serializationObject.ranges = this.serializeAnimationRanges();
  29351. // Layer mask
  29352. serializationObject.layerMask = this.layerMask;
  29353. // Alpha
  29354. serializationObject.alphaIndex = this.alphaIndex;
  29355. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29356. // Overlay
  29357. serializationObject.overlayAlpha = this.overlayAlpha;
  29358. serializationObject.overlayColor = this.overlayColor.asArray();
  29359. serializationObject.renderOverlay = this.renderOverlay;
  29360. // Fog
  29361. serializationObject.applyFog = this.applyFog;
  29362. // Action Manager
  29363. if (this.actionManager) {
  29364. serializationObject.actions = this.actionManager.serialize(this.name);
  29365. }
  29366. };
  29367. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29368. if (!this.geometry) {
  29369. return;
  29370. }
  29371. this._markSubMeshesAsAttributesDirty();
  29372. var morphTargetManager = this._morphTargetManager;
  29373. if (morphTargetManager && morphTargetManager.vertexCount) {
  29374. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29375. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29376. this.morphTargetManager = null;
  29377. return;
  29378. }
  29379. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29380. var morphTarget = morphTargetManager.getActiveTarget(index);
  29381. var positions = morphTarget.getPositions();
  29382. if (!positions) {
  29383. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29384. return;
  29385. }
  29386. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29387. var normals = morphTarget.getNormals();
  29388. if (normals) {
  29389. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29390. }
  29391. var tangents = morphTarget.getTangents();
  29392. if (tangents) {
  29393. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29394. }
  29395. }
  29396. }
  29397. else {
  29398. var index = 0;
  29399. // Positions
  29400. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29401. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29402. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29403. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29404. }
  29405. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29406. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29407. }
  29408. index++;
  29409. }
  29410. }
  29411. };
  29412. // Statics
  29413. /**
  29414. * Returns a new Mesh object parsed from the source provided.
  29415. * The parameter `parsedMesh` is the source.
  29416. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29417. */
  29418. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29419. var mesh;
  29420. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29421. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29422. }
  29423. else {
  29424. mesh = new Mesh(parsedMesh.name, scene);
  29425. }
  29426. mesh.id = parsedMesh.id;
  29427. if (BABYLON.Tags) {
  29428. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29429. }
  29430. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29431. if (parsedMesh.metadata !== undefined) {
  29432. mesh.metadata = parsedMesh.metadata;
  29433. }
  29434. if (parsedMesh.rotationQuaternion) {
  29435. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29436. }
  29437. else if (parsedMesh.rotation) {
  29438. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29439. }
  29440. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29441. if (parsedMesh.localMatrix) {
  29442. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29443. }
  29444. else if (parsedMesh.pivotMatrix) {
  29445. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29446. }
  29447. mesh.setEnabled(parsedMesh.isEnabled);
  29448. mesh.isVisible = parsedMesh.isVisible;
  29449. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29450. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29451. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29452. if (parsedMesh.applyFog !== undefined) {
  29453. mesh.applyFog = parsedMesh.applyFog;
  29454. }
  29455. if (parsedMesh.pickable !== undefined) {
  29456. mesh.isPickable = parsedMesh.pickable;
  29457. }
  29458. if (parsedMesh.alphaIndex !== undefined) {
  29459. mesh.alphaIndex = parsedMesh.alphaIndex;
  29460. }
  29461. mesh.receiveShadows = parsedMesh.receiveShadows;
  29462. mesh.billboardMode = parsedMesh.billboardMode;
  29463. if (parsedMesh.visibility !== undefined) {
  29464. mesh.visibility = parsedMesh.visibility;
  29465. }
  29466. mesh.checkCollisions = parsedMesh.checkCollisions;
  29467. if (parsedMesh.isBlocker !== undefined) {
  29468. mesh.isBlocker = parsedMesh.isBlocker;
  29469. }
  29470. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29471. // freezeWorldMatrix
  29472. if (parsedMesh.freezeWorldMatrix) {
  29473. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29474. }
  29475. // Parent
  29476. if (parsedMesh.parentId) {
  29477. mesh._waitingParentId = parsedMesh.parentId;
  29478. }
  29479. // Actions
  29480. if (parsedMesh.actions !== undefined) {
  29481. mesh._waitingActions = parsedMesh.actions;
  29482. }
  29483. // Overlay
  29484. if (parsedMesh.overlayAlpha !== undefined) {
  29485. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29486. }
  29487. if (parsedMesh.overlayColor !== undefined) {
  29488. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29489. }
  29490. if (parsedMesh.renderOverlay !== undefined) {
  29491. mesh.renderOverlay = parsedMesh.renderOverlay;
  29492. }
  29493. // Geometry
  29494. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29495. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29496. if (parsedMesh.delayLoadingFile) {
  29497. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29498. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29499. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29500. if (parsedMesh._binaryInfo) {
  29501. mesh._binaryInfo = parsedMesh._binaryInfo;
  29502. }
  29503. mesh._delayInfo = [];
  29504. if (parsedMesh.hasUVs) {
  29505. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29506. }
  29507. if (parsedMesh.hasUVs2) {
  29508. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29509. }
  29510. if (parsedMesh.hasUVs3) {
  29511. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29512. }
  29513. if (parsedMesh.hasUVs4) {
  29514. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29515. }
  29516. if (parsedMesh.hasUVs5) {
  29517. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29518. }
  29519. if (parsedMesh.hasUVs6) {
  29520. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29521. }
  29522. if (parsedMesh.hasColors) {
  29523. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29524. }
  29525. if (parsedMesh.hasMatricesIndices) {
  29526. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29527. }
  29528. if (parsedMesh.hasMatricesWeights) {
  29529. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29530. }
  29531. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29532. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29533. mesh._checkDelayState();
  29534. }
  29535. }
  29536. else {
  29537. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29538. }
  29539. // Material
  29540. if (parsedMesh.materialId) {
  29541. mesh.setMaterialByID(parsedMesh.materialId);
  29542. }
  29543. else {
  29544. mesh.material = null;
  29545. }
  29546. // Morph targets
  29547. if (parsedMesh.morphTargetManagerId > -1) {
  29548. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29549. }
  29550. // Skeleton
  29551. if (parsedMesh.skeletonId > -1) {
  29552. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29553. if (parsedMesh.numBoneInfluencers) {
  29554. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29555. }
  29556. }
  29557. // Animations
  29558. if (parsedMesh.animations) {
  29559. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29560. var parsedAnimation = parsedMesh.animations[animationIndex];
  29561. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29562. }
  29563. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29564. }
  29565. if (parsedMesh.autoAnimate) {
  29566. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29567. }
  29568. // Layer Mask
  29569. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29570. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29571. }
  29572. else {
  29573. mesh.layerMask = 0x0FFFFFFF;
  29574. }
  29575. // Physics
  29576. if (parsedMesh.physicsImpostor) {
  29577. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29578. mass: parsedMesh.physicsMass,
  29579. friction: parsedMesh.physicsFriction,
  29580. restitution: parsedMesh.physicsRestitution
  29581. }, scene);
  29582. }
  29583. // Instances
  29584. if (parsedMesh.instances) {
  29585. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29586. var parsedInstance = parsedMesh.instances[index];
  29587. var instance = mesh.createInstance(parsedInstance.name);
  29588. if (parsedInstance.id) {
  29589. instance.id = parsedInstance.id;
  29590. }
  29591. if (BABYLON.Tags) {
  29592. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29593. }
  29594. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29595. if (parsedInstance.parentId) {
  29596. instance._waitingParentId = parsedInstance.parentId;
  29597. }
  29598. if (parsedInstance.rotationQuaternion) {
  29599. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29600. }
  29601. else if (parsedInstance.rotation) {
  29602. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29603. }
  29604. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29605. instance.checkCollisions = mesh.checkCollisions;
  29606. if (parsedMesh.animations) {
  29607. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29608. parsedAnimation = parsedMesh.animations[animationIndex];
  29609. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29610. }
  29611. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29612. }
  29613. }
  29614. }
  29615. return mesh;
  29616. };
  29617. /**
  29618. * Creates a ribbon mesh.
  29619. * Please consider using the same method from the MeshBuilder class instead.
  29620. * 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.
  29621. *
  29622. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29623. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29624. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29625. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29626. * 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.
  29627. * 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.
  29628. * 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
  29629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29632. */
  29633. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29634. if (closeArray === void 0) { closeArray = false; }
  29635. if (updatable === void 0) { updatable = false; }
  29636. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29637. pathArray: pathArray,
  29638. closeArray: closeArray,
  29639. closePath: closePath,
  29640. offset: offset,
  29641. updatable: updatable,
  29642. sideOrientation: sideOrientation,
  29643. instance: instance
  29644. }, scene);
  29645. };
  29646. /**
  29647. * Creates a plane polygonal mesh. By default, this is a disc.
  29648. * Please consider using the same method from the MeshBuilder class instead.
  29649. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29650. * 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.
  29651. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29654. */
  29655. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29656. if (scene === void 0) { scene = null; }
  29657. var options = {
  29658. radius: radius,
  29659. tessellation: tessellation,
  29660. sideOrientation: sideOrientation,
  29661. updatable: updatable
  29662. };
  29663. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29664. };
  29665. /**
  29666. * Creates a box mesh.
  29667. * Please consider using the same method from the MeshBuilder class instead.
  29668. * The parameter `size` sets the size (float) of each box side (default 1).
  29669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29672. */
  29673. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29674. if (scene === void 0) { scene = null; }
  29675. var options = {
  29676. size: size,
  29677. sideOrientation: sideOrientation,
  29678. updatable: updatable
  29679. };
  29680. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29681. };
  29682. /**
  29683. * Creates a sphere mesh.
  29684. * Please consider using the same method from the MeshBuilder class instead.
  29685. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29686. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29690. */
  29691. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29692. var options = {
  29693. segments: segments,
  29694. diameterX: diameter,
  29695. diameterY: diameter,
  29696. diameterZ: diameter,
  29697. sideOrientation: sideOrientation,
  29698. updatable: updatable
  29699. };
  29700. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29701. };
  29702. /**
  29703. * Creates a cylinder or a cone mesh.
  29704. * Please consider using the same method from the MeshBuilder class instead.
  29705. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29706. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29707. * 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.
  29708. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29709. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29713. */
  29714. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29715. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29716. if (scene !== undefined) {
  29717. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29718. updatable = scene;
  29719. }
  29720. scene = subdivisions;
  29721. subdivisions = 1;
  29722. }
  29723. var options = {
  29724. height: height,
  29725. diameterTop: diameterTop,
  29726. diameterBottom: diameterBottom,
  29727. tessellation: tessellation,
  29728. subdivisions: subdivisions,
  29729. sideOrientation: sideOrientation,
  29730. updatable: updatable
  29731. };
  29732. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29733. };
  29734. // Torus (Code from SharpDX.org)
  29735. /**
  29736. * Creates a torus mesh.
  29737. * Please consider using the same method from the MeshBuilder class instead.
  29738. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29739. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29740. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29744. */
  29745. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29746. var options = {
  29747. diameter: diameter,
  29748. thickness: thickness,
  29749. tessellation: tessellation,
  29750. sideOrientation: sideOrientation,
  29751. updatable: updatable
  29752. };
  29753. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29754. };
  29755. /**
  29756. * Creates a torus knot mesh.
  29757. * Please consider using the same method from the MeshBuilder class instead.
  29758. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29759. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29760. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29761. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29765. */
  29766. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29767. var options = {
  29768. radius: radius,
  29769. tube: tube,
  29770. radialSegments: radialSegments,
  29771. tubularSegments: tubularSegments,
  29772. p: p,
  29773. q: q,
  29774. sideOrientation: sideOrientation,
  29775. updatable: updatable
  29776. };
  29777. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29778. };
  29779. /**
  29780. * Creates a line mesh.
  29781. * Please consider using the same method from the MeshBuilder class instead.
  29782. * 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.
  29783. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29784. * The parameter `points` is an array successive Vector3.
  29785. * 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
  29786. * When updating an instance, remember that only point positions can change, not the number of points.
  29787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29788. */
  29789. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29790. if (scene === void 0) { scene = null; }
  29791. if (updatable === void 0) { updatable = false; }
  29792. if (instance === void 0) { instance = null; }
  29793. var options = {
  29794. points: points,
  29795. updatable: updatable,
  29796. instance: instance
  29797. };
  29798. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29799. };
  29800. /**
  29801. * Creates a dashed line mesh.
  29802. * Please consider using the same method from the MeshBuilder class instead.
  29803. * 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.
  29804. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29805. * The parameter `points` is an array successive Vector3.
  29806. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29807. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29808. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29809. * 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
  29810. * When updating an instance, remember that only point positions can change, not the number of points.
  29811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29812. */
  29813. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29814. if (scene === void 0) { scene = null; }
  29815. var options = {
  29816. points: points,
  29817. dashSize: dashSize,
  29818. gapSize: gapSize,
  29819. dashNb: dashNb,
  29820. updatable: updatable,
  29821. instance: instance
  29822. };
  29823. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29824. };
  29825. /**
  29826. * Creates a polygon mesh.
  29827. * Please consider using the same method from the MeshBuilder class instead.
  29828. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29829. * 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.
  29830. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29832. * Remember you can only change the shape positions, not their number when updating a polygon.
  29833. */
  29834. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29835. var options = {
  29836. shape: shape,
  29837. holes: holes,
  29838. updatable: updatable,
  29839. sideOrientation: sideOrientation
  29840. };
  29841. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29842. };
  29843. /**
  29844. * Creates an extruded polygon mesh, with depth in the Y direction.
  29845. * Please consider using the same method from the MeshBuilder class instead.
  29846. */
  29847. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29848. var options = {
  29849. shape: shape,
  29850. holes: holes,
  29851. depth: depth,
  29852. updatable: updatable,
  29853. sideOrientation: sideOrientation
  29854. };
  29855. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29856. };
  29857. /**
  29858. * Creates an extruded shape mesh.
  29859. * 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.
  29860. * Please consider using the same method from the MeshBuilder class instead.
  29861. *
  29862. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29863. * 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
  29864. * extruded along the Z axis.
  29865. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29866. * 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.
  29867. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29868. * 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
  29869. * 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
  29870. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29874. */
  29875. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29876. if (scene === void 0) { scene = null; }
  29877. var options = {
  29878. shape: shape,
  29879. path: path,
  29880. scale: scale,
  29881. rotation: rotation,
  29882. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29883. sideOrientation: sideOrientation,
  29884. instance: instance,
  29885. updatable: updatable
  29886. };
  29887. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29888. };
  29889. /**
  29890. * Creates an custom extruded shape mesh.
  29891. * 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.
  29892. * Please consider using the same method from the MeshBuilder class instead.
  29893. *
  29894. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29895. * 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
  29896. * extruded along the Z axis.
  29897. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29898. * 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
  29899. * and the distance of this point from the begining of the path :
  29900. * ```javascript
  29901. * var rotationFunction = function(i, distance) {
  29902. * // do things
  29903. * return rotationValue; }
  29904. * ```
  29905. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29906. * 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
  29907. * and the distance of this point from the begining of the path :
  29908. * ```javascript
  29909. * var scaleFunction = function(i, distance) {
  29910. * // do things
  29911. * return scaleValue;}
  29912. * ```
  29913. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29914. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29915. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29916. * 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
  29917. * 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
  29918. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29919. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29920. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29922. */
  29923. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29924. var options = {
  29925. shape: shape,
  29926. path: path,
  29927. scaleFunction: scaleFunction,
  29928. rotationFunction: rotationFunction,
  29929. ribbonCloseArray: ribbonCloseArray,
  29930. ribbonClosePath: ribbonClosePath,
  29931. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29932. sideOrientation: sideOrientation,
  29933. instance: instance,
  29934. updatable: updatable
  29935. };
  29936. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29937. };
  29938. /**
  29939. * Creates lathe mesh.
  29940. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29941. * Please consider using the same method from the MeshBuilder class instead.
  29942. * 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
  29943. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29944. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29945. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29949. */
  29950. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29951. var options = {
  29952. shape: shape,
  29953. radius: radius,
  29954. tessellation: tessellation,
  29955. sideOrientation: sideOrientation,
  29956. updatable: updatable
  29957. };
  29958. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29959. };
  29960. /**
  29961. * Creates a plane mesh.
  29962. * Please consider using the same method from the MeshBuilder class instead.
  29963. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29967. */
  29968. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29969. var options = {
  29970. size: size,
  29971. width: size,
  29972. height: size,
  29973. sideOrientation: sideOrientation,
  29974. updatable: updatable
  29975. };
  29976. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29977. };
  29978. /**
  29979. * Creates a ground mesh.
  29980. * Please consider using the same method from the MeshBuilder class instead.
  29981. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29982. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29984. */
  29985. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29986. var options = {
  29987. width: width,
  29988. height: height,
  29989. subdivisions: subdivisions,
  29990. updatable: updatable
  29991. };
  29992. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29993. };
  29994. /**
  29995. * Creates a tiled ground mesh.
  29996. * Please consider using the same method from the MeshBuilder class instead.
  29997. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29998. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29999. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30000. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30001. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30002. * numbers of subdivisions on the ground width and height of each tile.
  30003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30004. */
  30005. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30006. var options = {
  30007. xmin: xmin,
  30008. zmin: zmin,
  30009. xmax: xmax,
  30010. zmax: zmax,
  30011. subdivisions: subdivisions,
  30012. precision: precision,
  30013. updatable: updatable
  30014. };
  30015. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30016. };
  30017. /**
  30018. * Creates a ground mesh from a height map.
  30019. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30020. * Please consider using the same method from the MeshBuilder class instead.
  30021. * The parameter `url` sets the URL of the height map image resource.
  30022. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30023. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30024. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30025. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30026. * 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).
  30027. * This function is passed the newly built mesh :
  30028. * ```javascript
  30029. * function(mesh) { // do things
  30030. * return; }
  30031. * ```
  30032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30033. */
  30034. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30035. var options = {
  30036. width: width,
  30037. height: height,
  30038. subdivisions: subdivisions,
  30039. minHeight: minHeight,
  30040. maxHeight: maxHeight,
  30041. updatable: updatable,
  30042. onReady: onReady
  30043. };
  30044. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30045. };
  30046. /**
  30047. * Creates a tube mesh.
  30048. * 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.
  30049. * Please consider using the same method from the MeshBuilder class instead.
  30050. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30051. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30052. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30053. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30054. * 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.
  30055. * It must return a radius value (positive float) :
  30056. * ```javascript
  30057. * var radiusFunction = function(i, distance) {
  30058. * // do things
  30059. * return radius; }
  30060. * ```
  30061. * 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
  30062. * 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
  30063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30066. */
  30067. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30068. var options = {
  30069. path: path,
  30070. radius: radius,
  30071. tessellation: tessellation,
  30072. radiusFunction: radiusFunction,
  30073. arc: 1,
  30074. cap: cap,
  30075. updatable: updatable,
  30076. sideOrientation: sideOrientation,
  30077. instance: instance
  30078. };
  30079. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30080. };
  30081. /**
  30082. * Creates a polyhedron mesh.
  30083. * Please consider using the same method from the MeshBuilder class instead.
  30084. * 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
  30085. * to choose the wanted type.
  30086. * The parameter `size` (positive float, default 1) sets the polygon size.
  30087. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30088. * 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`.
  30089. * 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
  30090. * 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)`).
  30091. * 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
  30092. * 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.
  30093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30096. */
  30097. Mesh.CreatePolyhedron = function (name, options, scene) {
  30098. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30099. };
  30100. /**
  30101. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30102. * Please consider using the same method from the MeshBuilder class instead.
  30103. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30104. * 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`).
  30105. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30106. * 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.
  30107. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30110. */
  30111. Mesh.CreateIcoSphere = function (name, options, scene) {
  30112. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30113. };
  30114. /**
  30115. * Creates a decal mesh.
  30116. * Please consider using the same method from the MeshBuilder class instead.
  30117. * 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.
  30118. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30119. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30120. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30121. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30122. */
  30123. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30124. var options = {
  30125. position: position,
  30126. normal: normal,
  30127. size: size,
  30128. angle: angle
  30129. };
  30130. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30131. };
  30132. // Skeletons
  30133. /**
  30134. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30135. */
  30136. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30137. if (!this._sourcePositions) {
  30138. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30139. if (!source) {
  30140. return this._sourcePositions;
  30141. }
  30142. this._sourcePositions = new Float32Array(source);
  30143. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30144. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30145. }
  30146. }
  30147. return this._sourcePositions;
  30148. };
  30149. /**
  30150. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30151. */
  30152. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30153. if (!this._sourceNormals) {
  30154. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30155. if (!source) {
  30156. return this._sourceNormals;
  30157. }
  30158. this._sourceNormals = new Float32Array(source);
  30159. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30160. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30161. }
  30162. }
  30163. return this._sourceNormals;
  30164. };
  30165. /**
  30166. * Updates the vertex buffer by applying transformation from the bones.
  30167. * Returns the Mesh.
  30168. *
  30169. * @param {skeleton} skeleton to apply
  30170. */
  30171. Mesh.prototype.applySkeleton = function (skeleton) {
  30172. if (!this.geometry) {
  30173. return this;
  30174. }
  30175. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30176. return this;
  30177. }
  30178. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30179. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30180. return this;
  30181. }
  30182. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30183. return this;
  30184. }
  30185. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30186. return this;
  30187. }
  30188. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30189. return this;
  30190. }
  30191. if (!this._sourcePositions) {
  30192. var submeshes = this.subMeshes.slice();
  30193. this.setPositionsForCPUSkinning();
  30194. this.subMeshes = submeshes;
  30195. }
  30196. if (!this._sourceNormals) {
  30197. this.setNormalsForCPUSkinning();
  30198. }
  30199. // positionsData checks for not being Float32Array will only pass at most once
  30200. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30201. if (!positionsData) {
  30202. return this;
  30203. }
  30204. if (!(positionsData instanceof Float32Array)) {
  30205. positionsData = new Float32Array(positionsData);
  30206. }
  30207. // normalsData checks for not being Float32Array will only pass at most once
  30208. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30209. if (!normalsData) {
  30210. return this;
  30211. }
  30212. if (!(normalsData instanceof Float32Array)) {
  30213. normalsData = new Float32Array(normalsData);
  30214. }
  30215. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30216. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30217. if (!matricesWeightsData || !matricesIndicesData) {
  30218. return this;
  30219. }
  30220. var needExtras = this.numBoneInfluencers > 4;
  30221. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30222. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30223. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30224. var tempVector3 = BABYLON.Vector3.Zero();
  30225. var finalMatrix = new BABYLON.Matrix();
  30226. var tempMatrix = new BABYLON.Matrix();
  30227. var matWeightIdx = 0;
  30228. var inf;
  30229. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30230. var weight;
  30231. for (inf = 0; inf < 4; inf++) {
  30232. weight = matricesWeightsData[matWeightIdx + inf];
  30233. if (weight > 0) {
  30234. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30235. finalMatrix.addToSelf(tempMatrix);
  30236. }
  30237. else
  30238. break;
  30239. }
  30240. if (needExtras) {
  30241. for (inf = 0; inf < 4; inf++) {
  30242. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30243. if (weight > 0) {
  30244. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30245. finalMatrix.addToSelf(tempMatrix);
  30246. }
  30247. else
  30248. break;
  30249. }
  30250. }
  30251. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30252. tempVector3.toArray(positionsData, index);
  30253. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30254. tempVector3.toArray(normalsData, index);
  30255. finalMatrix.reset();
  30256. }
  30257. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30258. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30259. return this;
  30260. };
  30261. // Tools
  30262. /**
  30263. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30264. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30265. */
  30266. Mesh.MinMax = function (meshes) {
  30267. var minVector = null;
  30268. var maxVector = null;
  30269. meshes.forEach(function (mesh, index, array) {
  30270. var boundingInfo = mesh.getBoundingInfo();
  30271. var boundingBox = boundingInfo.boundingBox;
  30272. if (!minVector || !maxVector) {
  30273. minVector = boundingBox.minimumWorld;
  30274. maxVector = boundingBox.maximumWorld;
  30275. }
  30276. else {
  30277. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30278. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30279. }
  30280. });
  30281. if (!minVector || !maxVector) {
  30282. return {
  30283. min: BABYLON.Vector3.Zero(),
  30284. max: BABYLON.Vector3.Zero()
  30285. };
  30286. }
  30287. return {
  30288. min: minVector,
  30289. max: maxVector
  30290. };
  30291. };
  30292. /**
  30293. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30294. */
  30295. Mesh.Center = function (meshesOrMinMaxVector) {
  30296. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30297. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30298. };
  30299. /**
  30300. * Merge the array of meshes into a single mesh for performance reasons.
  30301. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30302. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30303. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30304. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30305. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30306. */
  30307. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30308. if (disposeSource === void 0) { disposeSource = true; }
  30309. var index;
  30310. if (!allow32BitsIndices) {
  30311. var totalVertices = 0;
  30312. // Counting vertices
  30313. for (index = 0; index < meshes.length; index++) {
  30314. if (meshes[index]) {
  30315. totalVertices += meshes[index].getTotalVertices();
  30316. if (totalVertices > 65536) {
  30317. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30318. return null;
  30319. }
  30320. }
  30321. }
  30322. }
  30323. // Merge
  30324. var vertexData = null;
  30325. var otherVertexData;
  30326. var indiceArray = new Array();
  30327. var source = null;
  30328. for (index = 0; index < meshes.length; index++) {
  30329. if (meshes[index]) {
  30330. meshes[index].computeWorldMatrix(true);
  30331. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30332. otherVertexData.transform(meshes[index].getWorldMatrix());
  30333. if (vertexData) {
  30334. vertexData.merge(otherVertexData);
  30335. }
  30336. else {
  30337. vertexData = otherVertexData;
  30338. source = meshes[index];
  30339. }
  30340. if (subdivideWithSubMeshes) {
  30341. indiceArray.push(meshes[index].getTotalIndices());
  30342. }
  30343. }
  30344. }
  30345. source = source;
  30346. if (!meshSubclass) {
  30347. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30348. }
  30349. vertexData.applyToMesh(meshSubclass);
  30350. // Setting properties
  30351. meshSubclass.material = source.material;
  30352. meshSubclass.checkCollisions = source.checkCollisions;
  30353. // Cleaning
  30354. if (disposeSource) {
  30355. for (index = 0; index < meshes.length; index++) {
  30356. if (meshes[index]) {
  30357. meshes[index].dispose();
  30358. }
  30359. }
  30360. }
  30361. // Subdivide
  30362. if (subdivideWithSubMeshes) {
  30363. //-- Suppresions du submesh global
  30364. meshSubclass.releaseSubMeshes();
  30365. index = 0;
  30366. var offset = 0;
  30367. //-- aplique la subdivision en fonction du tableau d'indices
  30368. while (index < indiceArray.length) {
  30369. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30370. offset += indiceArray[index];
  30371. index++;
  30372. }
  30373. }
  30374. return meshSubclass;
  30375. };
  30376. // Consts
  30377. Mesh._FRONTSIDE = 0;
  30378. Mesh._BACKSIDE = 1;
  30379. Mesh._DOUBLESIDE = 2;
  30380. Mesh._DEFAULTSIDE = 0;
  30381. Mesh._NO_CAP = 0;
  30382. Mesh._CAP_START = 1;
  30383. Mesh._CAP_END = 2;
  30384. Mesh._CAP_ALL = 3;
  30385. return Mesh;
  30386. }(BABYLON.AbstractMesh));
  30387. BABYLON.Mesh = Mesh;
  30388. })(BABYLON || (BABYLON = {}));
  30389. //# sourceMappingURL=babylon.mesh.js.map
  30390. var BABYLON;
  30391. (function (BABYLON) {
  30392. var BaseSubMesh = /** @class */ (function () {
  30393. function BaseSubMesh() {
  30394. }
  30395. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30396. get: function () {
  30397. return this._materialEffect;
  30398. },
  30399. enumerable: true,
  30400. configurable: true
  30401. });
  30402. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30403. if (defines === void 0) { defines = null; }
  30404. if (this._materialEffect === effect) {
  30405. if (!effect) {
  30406. this._materialDefines = null;
  30407. }
  30408. return;
  30409. }
  30410. this._materialDefines = defines;
  30411. this._materialEffect = effect;
  30412. };
  30413. return BaseSubMesh;
  30414. }());
  30415. BABYLON.BaseSubMesh = BaseSubMesh;
  30416. var SubMesh = /** @class */ (function (_super) {
  30417. __extends(SubMesh, _super);
  30418. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30419. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30420. var _this = _super.call(this) || this;
  30421. _this.materialIndex = materialIndex;
  30422. _this.verticesStart = verticesStart;
  30423. _this.verticesCount = verticesCount;
  30424. _this.indexStart = indexStart;
  30425. _this.indexCount = indexCount;
  30426. _this._renderId = 0;
  30427. _this._mesh = mesh;
  30428. _this._renderingMesh = renderingMesh || mesh;
  30429. mesh.subMeshes.push(_this);
  30430. _this._trianglePlanes = [];
  30431. _this._id = mesh.subMeshes.length - 1;
  30432. if (createBoundingBox) {
  30433. _this.refreshBoundingInfo();
  30434. mesh.computeWorldMatrix(true);
  30435. }
  30436. return _this;
  30437. }
  30438. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30439. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30440. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30441. };
  30442. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30443. get: function () {
  30444. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30445. },
  30446. enumerable: true,
  30447. configurable: true
  30448. });
  30449. /**
  30450. * Returns the submesh BoudingInfo object.
  30451. */
  30452. SubMesh.prototype.getBoundingInfo = function () {
  30453. if (this.IsGlobal) {
  30454. return this._mesh.getBoundingInfo();
  30455. }
  30456. return this._boundingInfo;
  30457. };
  30458. /**
  30459. * Sets the submesh BoundingInfo.
  30460. * Return the SubMesh.
  30461. */
  30462. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30463. this._boundingInfo = boundingInfo;
  30464. return this;
  30465. };
  30466. /**
  30467. * Returns the mesh of the current submesh.
  30468. */
  30469. SubMesh.prototype.getMesh = function () {
  30470. return this._mesh;
  30471. };
  30472. /**
  30473. * Returns the rendering mesh of the submesh.
  30474. */
  30475. SubMesh.prototype.getRenderingMesh = function () {
  30476. return this._renderingMesh;
  30477. };
  30478. /**
  30479. * Returns the submesh material.
  30480. */
  30481. SubMesh.prototype.getMaterial = function () {
  30482. var rootMaterial = this._renderingMesh.material;
  30483. if (rootMaterial === null || rootMaterial === undefined) {
  30484. return this._mesh.getScene().defaultMaterial;
  30485. }
  30486. else if (rootMaterial.getSubMaterial) {
  30487. var multiMaterial = rootMaterial;
  30488. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30489. if (this._currentMaterial !== effectiveMaterial) {
  30490. this._currentMaterial = effectiveMaterial;
  30491. this._materialDefines = null;
  30492. }
  30493. return effectiveMaterial;
  30494. }
  30495. return rootMaterial;
  30496. };
  30497. // Methods
  30498. /**
  30499. * Sets a new updated BoundingInfo object to the submesh.
  30500. * Returns the SubMesh.
  30501. */
  30502. SubMesh.prototype.refreshBoundingInfo = function () {
  30503. this._lastColliderWorldVertices = null;
  30504. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30505. return this;
  30506. }
  30507. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30508. if (!data) {
  30509. this._boundingInfo = this._mesh.getBoundingInfo();
  30510. return this;
  30511. }
  30512. var indices = this._renderingMesh.getIndices();
  30513. var extend;
  30514. //is this the only submesh?
  30515. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30516. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30517. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30518. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30519. }
  30520. else {
  30521. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30522. }
  30523. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30524. return this;
  30525. };
  30526. SubMesh.prototype._checkCollision = function (collider) {
  30527. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30528. return boundingInfo._checkCollision(collider);
  30529. };
  30530. /**
  30531. * Updates the submesh BoundingInfo.
  30532. * Returns the Submesh.
  30533. */
  30534. SubMesh.prototype.updateBoundingInfo = function (world) {
  30535. var boundingInfo = this.getBoundingInfo();
  30536. if (!boundingInfo) {
  30537. this.refreshBoundingInfo();
  30538. boundingInfo = this.getBoundingInfo();
  30539. }
  30540. boundingInfo.update(world);
  30541. return this;
  30542. };
  30543. /**
  30544. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30545. * Boolean returned.
  30546. */
  30547. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30548. var boundingInfo = this.getBoundingInfo();
  30549. if (!boundingInfo) {
  30550. return false;
  30551. }
  30552. return boundingInfo.isInFrustum(frustumPlanes);
  30553. };
  30554. /**
  30555. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30556. * Boolean returned.
  30557. */
  30558. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30559. var boundingInfo = this.getBoundingInfo();
  30560. if (!boundingInfo) {
  30561. return false;
  30562. }
  30563. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30564. };
  30565. /**
  30566. * Renders the submesh.
  30567. * Returns it.
  30568. */
  30569. SubMesh.prototype.render = function (enableAlphaMode) {
  30570. this._renderingMesh.render(this, enableAlphaMode);
  30571. return this;
  30572. };
  30573. /**
  30574. * Returns a new Index Buffer.
  30575. * Type returned : WebGLBuffer.
  30576. */
  30577. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30578. if (!this._linesIndexBuffer) {
  30579. var linesIndices = [];
  30580. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30581. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30582. }
  30583. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30584. this.linesIndexCount = linesIndices.length;
  30585. }
  30586. return this._linesIndexBuffer;
  30587. };
  30588. /**
  30589. * True is the passed Ray intersects the submesh bounding box.
  30590. * Boolean returned.
  30591. */
  30592. SubMesh.prototype.canIntersects = function (ray) {
  30593. var boundingInfo = this.getBoundingInfo();
  30594. if (!boundingInfo) {
  30595. return false;
  30596. }
  30597. return ray.intersectsBox(boundingInfo.boundingBox);
  30598. };
  30599. /**
  30600. * Returns an object IntersectionInfo.
  30601. */
  30602. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30603. var intersectInfo = null;
  30604. // LineMesh first as it's also a Mesh...
  30605. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30606. var lineMesh = this._mesh;
  30607. // Line test
  30608. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30609. var p0 = positions[indices[index]];
  30610. var p1 = positions[indices[index + 1]];
  30611. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30612. if (length < 0) {
  30613. continue;
  30614. }
  30615. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30616. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30617. if (fastCheck) {
  30618. break;
  30619. }
  30620. }
  30621. }
  30622. }
  30623. else {
  30624. // Triangles test
  30625. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30626. var p0 = positions[indices[index]];
  30627. var p1 = positions[indices[index + 1]];
  30628. var p2 = positions[indices[index + 2]];
  30629. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30630. if (currentIntersectInfo) {
  30631. if (currentIntersectInfo.distance < 0) {
  30632. continue;
  30633. }
  30634. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30635. intersectInfo = currentIntersectInfo;
  30636. intersectInfo.faceId = index / 3;
  30637. if (fastCheck) {
  30638. break;
  30639. }
  30640. }
  30641. }
  30642. }
  30643. }
  30644. return intersectInfo;
  30645. };
  30646. SubMesh.prototype._rebuild = function () {
  30647. if (this._linesIndexBuffer) {
  30648. this._linesIndexBuffer = null;
  30649. }
  30650. };
  30651. // Clone
  30652. /**
  30653. * Creates a new Submesh from the passed Mesh.
  30654. */
  30655. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30656. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30657. if (!this.IsGlobal) {
  30658. var boundingInfo = this.getBoundingInfo();
  30659. if (!boundingInfo) {
  30660. return result;
  30661. }
  30662. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30663. }
  30664. return result;
  30665. };
  30666. // Dispose
  30667. /**
  30668. * Disposes the Submesh.
  30669. * Returns nothing.
  30670. */
  30671. SubMesh.prototype.dispose = function () {
  30672. if (this._linesIndexBuffer) {
  30673. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30674. this._linesIndexBuffer = null;
  30675. }
  30676. // Remove from mesh
  30677. var index = this._mesh.subMeshes.indexOf(this);
  30678. this._mesh.subMeshes.splice(index, 1);
  30679. };
  30680. // Statics
  30681. /**
  30682. * Creates a new Submesh from the passed parameters :
  30683. * - materialIndex (integer) : the index of the main mesh material.
  30684. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30685. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30686. * - mesh (Mesh) : the main mesh to create the submesh from.
  30687. * - renderingMesh (optional Mesh) : rendering mesh.
  30688. */
  30689. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30690. var minVertexIndex = Number.MAX_VALUE;
  30691. var maxVertexIndex = -Number.MAX_VALUE;
  30692. renderingMesh = (renderingMesh || mesh);
  30693. var indices = renderingMesh.getIndices();
  30694. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30695. var vertexIndex = indices[index];
  30696. if (vertexIndex < minVertexIndex)
  30697. minVertexIndex = vertexIndex;
  30698. if (vertexIndex > maxVertexIndex)
  30699. maxVertexIndex = vertexIndex;
  30700. }
  30701. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30702. };
  30703. return SubMesh;
  30704. }(BaseSubMesh));
  30705. BABYLON.SubMesh = SubMesh;
  30706. })(BABYLON || (BABYLON = {}));
  30707. //# sourceMappingURL=babylon.subMesh.js.map
  30708. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30709. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30710. s = arguments[i];
  30711. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30712. t[p] = s[p];
  30713. }
  30714. return t;
  30715. };
  30716. var BABYLON;
  30717. (function (BABYLON) {
  30718. /**
  30719. * Manages the defines for the Material.
  30720. */
  30721. var MaterialDefines = /** @class */ (function () {
  30722. function MaterialDefines() {
  30723. this._isDirty = true;
  30724. this._areLightsDirty = true;
  30725. this._areAttributesDirty = true;
  30726. this._areTexturesDirty = true;
  30727. this._areFresnelDirty = true;
  30728. this._areMiscDirty = true;
  30729. this._areImageProcessingDirty = true;
  30730. this._normals = false;
  30731. this._uvs = false;
  30732. this._needNormals = false;
  30733. this._needUVs = false;
  30734. }
  30735. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30736. /**
  30737. * Specifies if the material needs to be re-calculated.
  30738. */
  30739. get: function () {
  30740. return this._isDirty;
  30741. },
  30742. enumerable: true,
  30743. configurable: true
  30744. });
  30745. /**
  30746. * Marks the material to indicate that it has been re-calculated.
  30747. */
  30748. MaterialDefines.prototype.markAsProcessed = function () {
  30749. this._isDirty = false;
  30750. this._areAttributesDirty = false;
  30751. this._areTexturesDirty = false;
  30752. this._areFresnelDirty = false;
  30753. this._areLightsDirty = false;
  30754. this._areMiscDirty = false;
  30755. this._areImageProcessingDirty = false;
  30756. };
  30757. /**
  30758. * Marks the material to indicate that it needs to be re-calculated.
  30759. */
  30760. MaterialDefines.prototype.markAsUnprocessed = function () {
  30761. this._isDirty = true;
  30762. };
  30763. /**
  30764. * Marks the material to indicate all of its defines need to be re-calculated.
  30765. */
  30766. MaterialDefines.prototype.markAllAsDirty = function () {
  30767. this._areTexturesDirty = true;
  30768. this._areAttributesDirty = true;
  30769. this._areLightsDirty = true;
  30770. this._areFresnelDirty = true;
  30771. this._areMiscDirty = true;
  30772. this._areImageProcessingDirty = true;
  30773. this._isDirty = true;
  30774. };
  30775. /**
  30776. * Marks the material to indicate that image processing needs to be re-calculated.
  30777. */
  30778. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30779. this._areImageProcessingDirty = true;
  30780. this._isDirty = true;
  30781. };
  30782. /**
  30783. * Marks the material to indicate the lights need to be re-calculated.
  30784. */
  30785. MaterialDefines.prototype.markAsLightDirty = function () {
  30786. this._areLightsDirty = true;
  30787. this._isDirty = true;
  30788. };
  30789. /**
  30790. * Marks the attribute state as changed.
  30791. */
  30792. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30793. this._areAttributesDirty = true;
  30794. this._isDirty = true;
  30795. };
  30796. /**
  30797. * Marks the texture state as changed.
  30798. */
  30799. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30800. this._areTexturesDirty = true;
  30801. this._isDirty = true;
  30802. };
  30803. /**
  30804. * Marks the fresnel state as changed.
  30805. */
  30806. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30807. this._areFresnelDirty = true;
  30808. this._isDirty = true;
  30809. };
  30810. /**
  30811. * Marks the misc state as changed.
  30812. */
  30813. MaterialDefines.prototype.markAsMiscDirty = function () {
  30814. this._areMiscDirty = true;
  30815. this._isDirty = true;
  30816. };
  30817. /**
  30818. * Rebuilds the material defines.
  30819. */
  30820. MaterialDefines.prototype.rebuild = function () {
  30821. if (this._keys) {
  30822. delete this._keys;
  30823. }
  30824. this._keys = [];
  30825. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30826. var key = _a[_i];
  30827. if (key[0] === "_") {
  30828. continue;
  30829. }
  30830. this._keys.push(key);
  30831. }
  30832. };
  30833. /**
  30834. * Specifies if two material defines are equal.
  30835. * @param other - A material define instance to compare to.
  30836. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30837. */
  30838. MaterialDefines.prototype.isEqual = function (other) {
  30839. if (this._keys.length !== other._keys.length) {
  30840. return false;
  30841. }
  30842. for (var index = 0; index < this._keys.length; index++) {
  30843. var prop = this._keys[index];
  30844. if (this[prop] !== other[prop]) {
  30845. return false;
  30846. }
  30847. }
  30848. return true;
  30849. };
  30850. /**
  30851. * Clones this instance's defines to another instance.
  30852. * @param other - material defines to clone values to.
  30853. */
  30854. MaterialDefines.prototype.cloneTo = function (other) {
  30855. if (this._keys.length !== other._keys.length) {
  30856. other._keys = this._keys.slice(0);
  30857. }
  30858. for (var index = 0; index < this._keys.length; index++) {
  30859. var prop = this._keys[index];
  30860. other[prop] = this[prop];
  30861. }
  30862. };
  30863. /**
  30864. * Resets the material define values.
  30865. */
  30866. MaterialDefines.prototype.reset = function () {
  30867. for (var index = 0; index < this._keys.length; index++) {
  30868. var prop = this._keys[index];
  30869. if (typeof (this[prop]) === "number") {
  30870. this[prop] = 0;
  30871. }
  30872. else {
  30873. this[prop] = false;
  30874. }
  30875. }
  30876. };
  30877. /**
  30878. * Converts the material define values to a string.
  30879. * @returns - String of material define information.
  30880. */
  30881. MaterialDefines.prototype.toString = function () {
  30882. var result = "";
  30883. for (var index = 0; index < this._keys.length; index++) {
  30884. var prop = this._keys[index];
  30885. var value = this[prop];
  30886. if (typeof (value) === "number") {
  30887. result += "#define " + prop + " " + this[prop] + "\n";
  30888. }
  30889. else if (value) {
  30890. result += "#define " + prop + "\n";
  30891. }
  30892. }
  30893. return result;
  30894. };
  30895. return MaterialDefines;
  30896. }());
  30897. BABYLON.MaterialDefines = MaterialDefines;
  30898. /**
  30899. * This offers the main features of a material in BJS.
  30900. */
  30901. var Material = /** @class */ (function () {
  30902. /**
  30903. * Creates a material instance.
  30904. * @param name - The name of the material.
  30905. * @param scene - The BJS scene to reference.
  30906. * @param doNotAdd - Specifies if the material should be added to the scene.
  30907. */
  30908. function Material(name, scene, doNotAdd) {
  30909. /**
  30910. * Specifies if the ready state should be checked on each call.
  30911. */
  30912. this.checkReadyOnEveryCall = false;
  30913. /**
  30914. * Specifies if the ready state should be checked once.
  30915. */
  30916. this.checkReadyOnlyOnce = false;
  30917. /**
  30918. * The state of the material.
  30919. */
  30920. this.state = "";
  30921. /**
  30922. * The alpha value of the material.
  30923. */
  30924. this._alpha = 1.0;
  30925. /**
  30926. * Specifies if back face culling is enabled.
  30927. */
  30928. this._backFaceCulling = true;
  30929. /**
  30930. * Specifies if the material should be serialized.
  30931. */
  30932. this.doNotSerialize = false;
  30933. /**
  30934. * Specifies if the effect should be stored on sub meshes.
  30935. */
  30936. this.storeEffectOnSubMeshes = false;
  30937. /**
  30938. * An event triggered when the material is disposed.
  30939. * @type {BABYLON.Observable}
  30940. */
  30941. this.onDisposeObservable = new BABYLON.Observable();
  30942. /**
  30943. * An event triggered when the material is bound.
  30944. * @type {BABYLON.Observable}
  30945. */
  30946. this.onBindObservable = new BABYLON.Observable();
  30947. /**
  30948. * An event triggered when the material is unbound.
  30949. * @type {BABYLON.Observable}
  30950. */
  30951. this.onUnBindObservable = new BABYLON.Observable();
  30952. /**
  30953. * Stores the value of the alpha mode.
  30954. */
  30955. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30956. /**
  30957. * Stores the state of the need depth pre-pass value.
  30958. */
  30959. this._needDepthPrePass = false;
  30960. /**
  30961. * Specifies if depth writing should be disabled.
  30962. */
  30963. this.disableDepthWrite = false;
  30964. /**
  30965. * Specifies if depth writing should be forced.
  30966. */
  30967. this.forceDepthWrite = false;
  30968. /**
  30969. * Specifies if there should be a separate pass for culling.
  30970. */
  30971. this.separateCullingPass = false;
  30972. /**
  30973. * Stores the state specifing if fog should be enabled.
  30974. */
  30975. this._fogEnabled = true;
  30976. /**
  30977. * Stores the size of points.
  30978. */
  30979. this.pointSize = 1.0;
  30980. /**
  30981. * Stores the z offset value.
  30982. */
  30983. this.zOffset = 0;
  30984. /**
  30985. * Specifies if the material was previously ready.
  30986. */
  30987. this._wasPreviouslyReady = false;
  30988. /**
  30989. * Stores the fill mode state.
  30990. */
  30991. this._fillMode = Material.TriangleFillMode;
  30992. this.name = name;
  30993. this.id = name || BABYLON.Tools.RandomId();
  30994. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30995. if (this._scene.useRightHandedSystem) {
  30996. this.sideOrientation = Material.ClockWiseSideOrientation;
  30997. }
  30998. else {
  30999. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31000. }
  31001. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31002. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31003. if (!doNotAdd) {
  31004. this._scene.materials.push(this);
  31005. }
  31006. }
  31007. Object.defineProperty(Material, "TriangleFillMode", {
  31008. /**
  31009. * Returns the triangle fill mode.
  31010. */
  31011. get: function () {
  31012. return Material._TriangleFillMode;
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(Material, "WireFrameFillMode", {
  31018. /**
  31019. * Returns the wireframe mode.
  31020. */
  31021. get: function () {
  31022. return Material._WireFrameFillMode;
  31023. },
  31024. enumerable: true,
  31025. configurable: true
  31026. });
  31027. Object.defineProperty(Material, "PointFillMode", {
  31028. /**
  31029. * Returns the point fill mode.
  31030. */
  31031. get: function () {
  31032. return Material._PointFillMode;
  31033. },
  31034. enumerable: true,
  31035. configurable: true
  31036. });
  31037. Object.defineProperty(Material, "PointListDrawMode", {
  31038. /**
  31039. * Returns the point list draw mode.
  31040. */
  31041. get: function () {
  31042. return Material._PointListDrawMode;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(Material, "LineListDrawMode", {
  31048. /**
  31049. * Returns the line list draw mode.
  31050. */
  31051. get: function () {
  31052. return Material._LineListDrawMode;
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Material, "LineLoopDrawMode", {
  31058. /**
  31059. * Returns the line loop draw mode.
  31060. */
  31061. get: function () {
  31062. return Material._LineLoopDrawMode;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(Material, "LineStripDrawMode", {
  31068. /**
  31069. * Returns the line strip draw mode.
  31070. */
  31071. get: function () {
  31072. return Material._LineStripDrawMode;
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31078. /**
  31079. * Returns the triangle strip draw mode.
  31080. */
  31081. get: function () {
  31082. return Material._TriangleStripDrawMode;
  31083. },
  31084. enumerable: true,
  31085. configurable: true
  31086. });
  31087. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31088. /**
  31089. * Returns the triangle fan draw mode.
  31090. */
  31091. get: function () {
  31092. return Material._TriangleFanDrawMode;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31098. /**
  31099. * Returns the clock-wise side orientation.
  31100. */
  31101. get: function () {
  31102. return Material._ClockWiseSideOrientation;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31108. /**
  31109. * Returns the counter clock-wise side orientation.
  31110. */
  31111. get: function () {
  31112. return Material._CounterClockWiseSideOrientation;
  31113. },
  31114. enumerable: true,
  31115. configurable: true
  31116. });
  31117. Object.defineProperty(Material, "TextureDirtyFlag", {
  31118. /**
  31119. * Returns the dirty texture flag value.
  31120. */
  31121. get: function () {
  31122. return Material._TextureDirtyFlag;
  31123. },
  31124. enumerable: true,
  31125. configurable: true
  31126. });
  31127. Object.defineProperty(Material, "LightDirtyFlag", {
  31128. /**
  31129. * Returns the dirty light flag value.
  31130. */
  31131. get: function () {
  31132. return Material._LightDirtyFlag;
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31138. /**
  31139. * Returns the dirty fresnel flag value.
  31140. */
  31141. get: function () {
  31142. return Material._FresnelDirtyFlag;
  31143. },
  31144. enumerable: true,
  31145. configurable: true
  31146. });
  31147. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31148. /**
  31149. * Returns the dirty attributes flag value.
  31150. */
  31151. get: function () {
  31152. return Material._AttributesDirtyFlag;
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. Object.defineProperty(Material, "MiscDirtyFlag", {
  31158. /**
  31159. * Returns the dirty misc flag value.
  31160. */
  31161. get: function () {
  31162. return Material._MiscDirtyFlag;
  31163. },
  31164. enumerable: true,
  31165. configurable: true
  31166. });
  31167. Object.defineProperty(Material.prototype, "alpha", {
  31168. /**
  31169. * Gets the alpha value of the material.
  31170. */
  31171. get: function () {
  31172. return this._alpha;
  31173. },
  31174. /**
  31175. * Sets the alpha value of the material.
  31176. */
  31177. set: function (value) {
  31178. if (this._alpha === value) {
  31179. return;
  31180. }
  31181. this._alpha = value;
  31182. this.markAsDirty(Material.MiscDirtyFlag);
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31188. /**
  31189. * Gets the back-face culling state.
  31190. */
  31191. get: function () {
  31192. return this._backFaceCulling;
  31193. },
  31194. /**
  31195. * Sets the back-face culling state.
  31196. */
  31197. set: function (value) {
  31198. if (this._backFaceCulling === value) {
  31199. return;
  31200. }
  31201. this._backFaceCulling = value;
  31202. this.markAsDirty(Material.TextureDirtyFlag);
  31203. },
  31204. enumerable: true,
  31205. configurable: true
  31206. });
  31207. Object.defineProperty(Material.prototype, "onDispose", {
  31208. /**
  31209. * Called during a dispose event.
  31210. */
  31211. set: function (callback) {
  31212. if (this._onDisposeObserver) {
  31213. this.onDisposeObservable.remove(this._onDisposeObserver);
  31214. }
  31215. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. Object.defineProperty(Material.prototype, "onBind", {
  31221. /**
  31222. * Called during a bind event.
  31223. */
  31224. set: function (callback) {
  31225. if (this._onBindObserver) {
  31226. this.onBindObservable.remove(this._onBindObserver);
  31227. }
  31228. this._onBindObserver = this.onBindObservable.add(callback);
  31229. },
  31230. enumerable: true,
  31231. configurable: true
  31232. });
  31233. Object.defineProperty(Material.prototype, "alphaMode", {
  31234. /**
  31235. * Gets the value of the alpha mode.
  31236. */
  31237. get: function () {
  31238. return this._alphaMode;
  31239. },
  31240. /**
  31241. * Sets the value of the alpha mode.
  31242. */
  31243. set: function (value) {
  31244. if (this._alphaMode === value) {
  31245. return;
  31246. }
  31247. this._alphaMode = value;
  31248. this.markAsDirty(Material.TextureDirtyFlag);
  31249. },
  31250. enumerable: true,
  31251. configurable: true
  31252. });
  31253. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31254. /**
  31255. * Gets the depth pre-pass value.
  31256. */
  31257. get: function () {
  31258. return this._needDepthPrePass;
  31259. },
  31260. /**
  31261. * Sets the need depth pre-pass value.
  31262. */
  31263. set: function (value) {
  31264. if (this._needDepthPrePass === value) {
  31265. return;
  31266. }
  31267. this._needDepthPrePass = value;
  31268. if (this._needDepthPrePass) {
  31269. this.checkReadyOnEveryCall = true;
  31270. }
  31271. },
  31272. enumerable: true,
  31273. configurable: true
  31274. });
  31275. Object.defineProperty(Material.prototype, "fogEnabled", {
  31276. /**
  31277. * Gets the value of the fog enabled state.
  31278. */
  31279. get: function () {
  31280. return this._fogEnabled;
  31281. },
  31282. /**
  31283. * Sets the state for enabling fog.
  31284. */
  31285. set: function (value) {
  31286. if (this._fogEnabled === value) {
  31287. return;
  31288. }
  31289. this._fogEnabled = value;
  31290. this.markAsDirty(Material.MiscDirtyFlag);
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(Material.prototype, "wireframe", {
  31296. /**
  31297. * Gets a value specifying if wireframe mode is enabled.
  31298. */
  31299. get: function () {
  31300. return this._fillMode === Material.WireFrameFillMode;
  31301. },
  31302. /**
  31303. * Sets the state of wireframe mode.
  31304. */
  31305. set: function (value) {
  31306. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31307. },
  31308. enumerable: true,
  31309. configurable: true
  31310. });
  31311. Object.defineProperty(Material.prototype, "pointsCloud", {
  31312. /**
  31313. * Gets the value specifying if point clouds are enabled.
  31314. */
  31315. get: function () {
  31316. return this._fillMode === Material.PointFillMode;
  31317. },
  31318. /**
  31319. * Sets the state of point cloud mode.
  31320. */
  31321. set: function (value) {
  31322. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31323. },
  31324. enumerable: true,
  31325. configurable: true
  31326. });
  31327. Object.defineProperty(Material.prototype, "fillMode", {
  31328. /**
  31329. * Gets the material fill mode.
  31330. */
  31331. get: function () {
  31332. return this._fillMode;
  31333. },
  31334. /**
  31335. * Sets the material fill mode.
  31336. */
  31337. set: function (value) {
  31338. if (this._fillMode === value) {
  31339. return;
  31340. }
  31341. this._fillMode = value;
  31342. this.markAsDirty(Material.MiscDirtyFlag);
  31343. },
  31344. enumerable: true,
  31345. configurable: true
  31346. });
  31347. /**
  31348. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31349. * subclasses should override adding information pertainent to themselves.
  31350. * @returns - String with material information.
  31351. */
  31352. Material.prototype.toString = function (fullDetails) {
  31353. var ret = "Name: " + this.name;
  31354. if (fullDetails) {
  31355. }
  31356. return ret;
  31357. };
  31358. /**
  31359. * Gets the class name of the material.
  31360. * @returns - String with the class name of the material.
  31361. */
  31362. Material.prototype.getClassName = function () {
  31363. return "Material";
  31364. };
  31365. Object.defineProperty(Material.prototype, "isFrozen", {
  31366. /**
  31367. * Specifies if updates for the material been locked.
  31368. */
  31369. get: function () {
  31370. return this.checkReadyOnlyOnce;
  31371. },
  31372. enumerable: true,
  31373. configurable: true
  31374. });
  31375. /**
  31376. * Locks updates for the material.
  31377. */
  31378. Material.prototype.freeze = function () {
  31379. this.checkReadyOnlyOnce = true;
  31380. };
  31381. /**
  31382. * Unlocks updates for the material.
  31383. */
  31384. Material.prototype.unfreeze = function () {
  31385. this.checkReadyOnlyOnce = false;
  31386. };
  31387. /**
  31388. * Specifies if the material is ready to be used.
  31389. * @param mesh - BJS mesh.
  31390. * @param useInstances - Specifies if instances should be used.
  31391. * @returns - Boolean indicating if the material is ready to be used.
  31392. */
  31393. Material.prototype.isReady = function (mesh, useInstances) {
  31394. return true;
  31395. };
  31396. /**
  31397. * Specifies that the submesh is ready to be used.
  31398. * @param mesh - BJS mesh.
  31399. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31400. * @param useInstances - Specifies that instances should be used.
  31401. * @returns - boolean indicating that the submesh is ready or not.
  31402. */
  31403. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31404. return false;
  31405. };
  31406. /**
  31407. * Returns the material effect.
  31408. * @returns - Nullable material effect.
  31409. */
  31410. Material.prototype.getEffect = function () {
  31411. return this._effect;
  31412. };
  31413. /**
  31414. * Returns the BJS scene.
  31415. * @returns - BJS Scene.
  31416. */
  31417. Material.prototype.getScene = function () {
  31418. return this._scene;
  31419. };
  31420. /**
  31421. * Specifies if the material will require alpha blending
  31422. * @returns - Boolean specifying if alpha blending is needed.
  31423. */
  31424. Material.prototype.needAlphaBlending = function () {
  31425. return (this.alpha < 1.0);
  31426. };
  31427. /**
  31428. * Specifies if the mesh will require alpha blending.
  31429. * @param mesh - BJS mesh.
  31430. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31431. */
  31432. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31433. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31434. };
  31435. /**
  31436. * Specifies if this material should be rendered in alpha test mode.
  31437. * @returns - Boolean specifying if an alpha test is needed.
  31438. */
  31439. Material.prototype.needAlphaTesting = function () {
  31440. return false;
  31441. };
  31442. /**
  31443. * Gets the texture used for the alpha test.
  31444. * @returns - Nullable alpha test texture.
  31445. */
  31446. Material.prototype.getAlphaTestTexture = function () {
  31447. return null;
  31448. };
  31449. /**
  31450. * Marks the material to indicate that it needs to be re-calculated.
  31451. */
  31452. Material.prototype.markDirty = function () {
  31453. this._wasPreviouslyReady = false;
  31454. };
  31455. Material.prototype._preBind = function (effect, overrideOrientation) {
  31456. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31457. var engine = this._scene.getEngine();
  31458. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31459. var reverse = orientation === Material.ClockWiseSideOrientation;
  31460. engine.enableEffect(effect ? effect : this._effect);
  31461. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31462. return reverse;
  31463. };
  31464. /**
  31465. * Binds the material to the mesh.
  31466. * @param world - World transformation matrix.
  31467. * @param mesh - Mesh to bind the material to.
  31468. */
  31469. Material.prototype.bind = function (world, mesh) {
  31470. };
  31471. /**
  31472. * Binds the submesh to the material.
  31473. * @param world - World transformation matrix.
  31474. * @param mesh - Mesh containing the submesh.
  31475. * @param subMesh - Submesh to bind the material to.
  31476. */
  31477. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31478. };
  31479. /**
  31480. * Binds the world matrix to the material.
  31481. * @param world - World transformation matrix.
  31482. */
  31483. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31484. };
  31485. /**
  31486. * Binds the scene's uniform buffer to the effect.
  31487. * @param effect - Effect to bind to the scene uniform buffer.
  31488. * @param sceneUbo - Scene uniform buffer.
  31489. */
  31490. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31491. sceneUbo.bindToEffect(effect, "Scene");
  31492. };
  31493. /**
  31494. * Binds the view matrix to the effect.
  31495. * @param effect - Effect to bind the view matrix to.
  31496. */
  31497. Material.prototype.bindView = function (effect) {
  31498. if (!this._useUBO) {
  31499. effect.setMatrix("view", this.getScene().getViewMatrix());
  31500. }
  31501. else {
  31502. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31503. }
  31504. };
  31505. /**
  31506. * Binds the view projection matrix to the effect.
  31507. * @param effect - Effect to bind the view projection matrix to.
  31508. */
  31509. Material.prototype.bindViewProjection = function (effect) {
  31510. if (!this._useUBO) {
  31511. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31512. }
  31513. else {
  31514. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31515. }
  31516. };
  31517. /**
  31518. * Specifies if material alpha testing should be turned on for the mesh.
  31519. * @param mesh - BJS mesh.
  31520. */
  31521. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31522. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31523. };
  31524. /**
  31525. * Processes to execute after binding the material to a mesh.
  31526. * @param mesh - BJS mesh.
  31527. */
  31528. Material.prototype._afterBind = function (mesh) {
  31529. this._scene._cachedMaterial = this;
  31530. if (mesh) {
  31531. this._scene._cachedVisibility = mesh.visibility;
  31532. }
  31533. else {
  31534. this._scene._cachedVisibility = 1;
  31535. }
  31536. if (mesh) {
  31537. this.onBindObservable.notifyObservers(mesh);
  31538. }
  31539. if (this.disableDepthWrite) {
  31540. var engine = this._scene.getEngine();
  31541. this._cachedDepthWriteState = engine.getDepthWrite();
  31542. engine.setDepthWrite(false);
  31543. }
  31544. };
  31545. /**
  31546. * Unbinds the material from the mesh.
  31547. */
  31548. Material.prototype.unbind = function () {
  31549. this.onUnBindObservable.notifyObservers(this);
  31550. if (this.disableDepthWrite) {
  31551. var engine = this._scene.getEngine();
  31552. engine.setDepthWrite(this._cachedDepthWriteState);
  31553. }
  31554. };
  31555. /**
  31556. * Gets the active textures from the material.
  31557. * @returns - Array of textures.
  31558. */
  31559. Material.prototype.getActiveTextures = function () {
  31560. return [];
  31561. };
  31562. /**
  31563. * Specifies if the material uses a texture.
  31564. * @param texture - Texture to check against the material.
  31565. * @returns - Boolean specifying if the material uses the texture.
  31566. */
  31567. Material.prototype.hasTexture = function (texture) {
  31568. return false;
  31569. };
  31570. /**
  31571. * Makes a duplicate of the material, and gives it a new name.
  31572. * @param name - Name to call the duplicated material.
  31573. * @returns - Nullable cloned material
  31574. */
  31575. Material.prototype.clone = function (name) {
  31576. return null;
  31577. };
  31578. /**
  31579. * Gets the meshes bound to the material.
  31580. * @returns - Array of meshes bound to the material.
  31581. */
  31582. Material.prototype.getBindedMeshes = function () {
  31583. var result = new Array();
  31584. for (var index = 0; index < this._scene.meshes.length; index++) {
  31585. var mesh = this._scene.meshes[index];
  31586. if (mesh.material === this) {
  31587. result.push(mesh);
  31588. }
  31589. }
  31590. return result;
  31591. };
  31592. /**
  31593. * Force shader compilation
  31594. * @param mesh - BJS mesh.
  31595. * @param onCompiled - function to execute once the material is compiled.
  31596. * @param options - options to pass to this function.
  31597. */
  31598. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31599. var _this = this;
  31600. var localOptions = __assign({ clipPlane: false }, options);
  31601. var subMesh = new BABYLON.BaseSubMesh();
  31602. var scene = this.getScene();
  31603. var checkReady = function () {
  31604. if (!_this._scene || !_this._scene.getEngine()) {
  31605. return;
  31606. }
  31607. if (subMesh._materialDefines) {
  31608. subMesh._materialDefines._renderId = -1;
  31609. }
  31610. var clipPlaneState = scene.clipPlane;
  31611. if (localOptions.clipPlane) {
  31612. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31613. }
  31614. if (_this.storeEffectOnSubMeshes) {
  31615. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31616. if (onCompiled) {
  31617. onCompiled(_this);
  31618. }
  31619. }
  31620. else {
  31621. setTimeout(checkReady, 16);
  31622. }
  31623. }
  31624. else {
  31625. if (_this.isReady(mesh)) {
  31626. if (onCompiled) {
  31627. onCompiled(_this);
  31628. }
  31629. }
  31630. else {
  31631. setTimeout(checkReady, 16);
  31632. }
  31633. }
  31634. if (localOptions.clipPlane) {
  31635. scene.clipPlane = clipPlaneState;
  31636. }
  31637. };
  31638. checkReady();
  31639. };
  31640. /**
  31641. * Force shader compilation.
  31642. * @param mesh The mesh that will use this material
  31643. * @param options Additional options for compiling the shaders
  31644. * @returns A promise that resolves when the compilation completes
  31645. */
  31646. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31647. var _this = this;
  31648. return new Promise(function (resolve) {
  31649. _this.forceCompilation(mesh, function () {
  31650. resolve();
  31651. }, options);
  31652. });
  31653. };
  31654. /**
  31655. * Marks a define in the material to indicate that it needs to be re-computed.
  31656. * @param flag - Material define flag.
  31657. */
  31658. Material.prototype.markAsDirty = function (flag) {
  31659. if (flag & Material.TextureDirtyFlag) {
  31660. this._markAllSubMeshesAsTexturesDirty();
  31661. }
  31662. if (flag & Material.LightDirtyFlag) {
  31663. this._markAllSubMeshesAsLightsDirty();
  31664. }
  31665. if (flag & Material.FresnelDirtyFlag) {
  31666. this._markAllSubMeshesAsFresnelDirty();
  31667. }
  31668. if (flag & Material.AttributesDirtyFlag) {
  31669. this._markAllSubMeshesAsAttributesDirty();
  31670. }
  31671. if (flag & Material.MiscDirtyFlag) {
  31672. this._markAllSubMeshesAsMiscDirty();
  31673. }
  31674. this.getScene().resetCachedMaterial();
  31675. };
  31676. /**
  31677. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31678. * @param func - function which checks material defines against the submeshes.
  31679. */
  31680. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31681. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31682. var mesh = _a[_i];
  31683. if (!mesh.subMeshes) {
  31684. continue;
  31685. }
  31686. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31687. var subMesh = _c[_b];
  31688. if (subMesh.getMaterial() !== this) {
  31689. continue;
  31690. }
  31691. if (!subMesh._materialDefines) {
  31692. continue;
  31693. }
  31694. func(subMesh._materialDefines);
  31695. }
  31696. }
  31697. };
  31698. /**
  31699. * Indicates that image processing needs to be re-calculated for all submeshes.
  31700. */
  31701. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31702. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31703. };
  31704. /**
  31705. * Indicates that textures need to be re-calculated for all submeshes.
  31706. */
  31707. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31708. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31709. };
  31710. /**
  31711. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31712. */
  31713. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31714. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31715. };
  31716. /**
  31717. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31718. */
  31719. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31720. this._markAllSubMeshesAsDirty(function (defines) {
  31721. defines.markAsFresnelDirty();
  31722. defines.markAsMiscDirty();
  31723. });
  31724. };
  31725. /**
  31726. * Indicates that lights need to be re-calculated for all submeshes.
  31727. */
  31728. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31729. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31730. };
  31731. /**
  31732. * Indicates that attributes need to be re-calculated for all submeshes.
  31733. */
  31734. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31735. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31736. };
  31737. /**
  31738. * Indicates that misc needs to be re-calculated for all submeshes.
  31739. */
  31740. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31741. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31742. };
  31743. /**
  31744. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31745. */
  31746. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31747. this._markAllSubMeshesAsDirty(function (defines) {
  31748. defines.markAsTexturesDirty();
  31749. defines.markAsMiscDirty();
  31750. });
  31751. };
  31752. /**
  31753. * Disposes the material.
  31754. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31755. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31756. */
  31757. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31758. // Animations
  31759. this.getScene().stopAnimation(this);
  31760. this.getScene().freeProcessedMaterials();
  31761. // Remove from scene
  31762. var index = this._scene.materials.indexOf(this);
  31763. if (index >= 0) {
  31764. this._scene.materials.splice(index, 1);
  31765. }
  31766. // Remove from meshes
  31767. for (index = 0; index < this._scene.meshes.length; index++) {
  31768. var mesh = this._scene.meshes[index];
  31769. if (mesh.material === this) {
  31770. mesh.material = null;
  31771. if (mesh.geometry) {
  31772. var geometry = (mesh.geometry);
  31773. if (this.storeEffectOnSubMeshes) {
  31774. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31775. var subMesh = _a[_i];
  31776. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31777. if (forceDisposeEffect && subMesh._materialEffect) {
  31778. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31779. }
  31780. }
  31781. }
  31782. else {
  31783. geometry._releaseVertexArrayObject(this._effect);
  31784. }
  31785. }
  31786. }
  31787. }
  31788. this._uniformBuffer.dispose();
  31789. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31790. if (forceDisposeEffect && this._effect) {
  31791. if (!this.storeEffectOnSubMeshes) {
  31792. this._scene.getEngine()._releaseEffect(this._effect);
  31793. }
  31794. this._effect = null;
  31795. }
  31796. // Callback
  31797. this.onDisposeObservable.notifyObservers(this);
  31798. this.onDisposeObservable.clear();
  31799. this.onBindObservable.clear();
  31800. this.onUnBindObservable.clear();
  31801. };
  31802. /**
  31803. * Serializes this material.
  31804. * @returns - serialized material object.
  31805. */
  31806. Material.prototype.serialize = function () {
  31807. return BABYLON.SerializationHelper.Serialize(this);
  31808. };
  31809. /**
  31810. * Creates a MultiMaterial from parse MultiMaterial data.
  31811. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31812. * @param scene - BJS scene.
  31813. * @returns - MultiMaterial.
  31814. */
  31815. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31816. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31817. multiMaterial.id = parsedMultiMaterial.id;
  31818. if (BABYLON.Tags) {
  31819. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31820. }
  31821. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31822. var subMatId = parsedMultiMaterial.materials[matIndex];
  31823. if (subMatId) {
  31824. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31825. }
  31826. else {
  31827. multiMaterial.subMaterials.push(null);
  31828. }
  31829. }
  31830. return multiMaterial;
  31831. };
  31832. /**
  31833. * Creates a material from parsed material data.
  31834. * @param parsedMaterial - Parsed material data.
  31835. * @param scene - BJS scene.
  31836. * @param rootUrl - Root URL containing the material information.
  31837. * @returns - Parsed material.
  31838. */
  31839. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31840. if (!parsedMaterial.customType) {
  31841. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31842. }
  31843. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31844. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31845. if (!BABYLON.LegacyPBRMaterial) {
  31846. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31847. return;
  31848. }
  31849. }
  31850. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31851. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31852. ;
  31853. };
  31854. // Triangle views
  31855. Material._TriangleFillMode = 0;
  31856. Material._WireFrameFillMode = 1;
  31857. Material._PointFillMode = 2;
  31858. // Draw modes
  31859. Material._PointListDrawMode = 3;
  31860. Material._LineListDrawMode = 4;
  31861. Material._LineLoopDrawMode = 5;
  31862. Material._LineStripDrawMode = 6;
  31863. Material._TriangleStripDrawMode = 7;
  31864. Material._TriangleFanDrawMode = 8;
  31865. /**
  31866. * Stores the clock-wise side orientation.
  31867. */
  31868. Material._ClockWiseSideOrientation = 0;
  31869. /**
  31870. * Stores the counter clock-wise side orientation.
  31871. */
  31872. Material._CounterClockWiseSideOrientation = 1;
  31873. /**
  31874. * The dirty texture flag value.
  31875. */
  31876. Material._TextureDirtyFlag = 1;
  31877. /**
  31878. * The dirty light flag value.
  31879. */
  31880. Material._LightDirtyFlag = 2;
  31881. /**
  31882. * The dirty fresnel flag value.
  31883. */
  31884. Material._FresnelDirtyFlag = 4;
  31885. /**
  31886. * The dirty attribute flag value.
  31887. */
  31888. Material._AttributesDirtyFlag = 8;
  31889. /**
  31890. * The dirty misc flag value.
  31891. */
  31892. Material._MiscDirtyFlag = 16;
  31893. __decorate([
  31894. BABYLON.serialize()
  31895. ], Material.prototype, "id", void 0);
  31896. __decorate([
  31897. BABYLON.serialize()
  31898. ], Material.prototype, "name", void 0);
  31899. __decorate([
  31900. BABYLON.serialize()
  31901. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31902. __decorate([
  31903. BABYLON.serialize()
  31904. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31905. __decorate([
  31906. BABYLON.serialize()
  31907. ], Material.prototype, "state", void 0);
  31908. __decorate([
  31909. BABYLON.serialize("alpha")
  31910. ], Material.prototype, "_alpha", void 0);
  31911. __decorate([
  31912. BABYLON.serialize("backFaceCulling")
  31913. ], Material.prototype, "_backFaceCulling", void 0);
  31914. __decorate([
  31915. BABYLON.serialize()
  31916. ], Material.prototype, "sideOrientation", void 0);
  31917. __decorate([
  31918. BABYLON.serialize("alphaMode")
  31919. ], Material.prototype, "_alphaMode", void 0);
  31920. __decorate([
  31921. BABYLON.serialize()
  31922. ], Material.prototype, "_needDepthPrePass", void 0);
  31923. __decorate([
  31924. BABYLON.serialize()
  31925. ], Material.prototype, "disableDepthWrite", void 0);
  31926. __decorate([
  31927. BABYLON.serialize()
  31928. ], Material.prototype, "forceDepthWrite", void 0);
  31929. __decorate([
  31930. BABYLON.serialize()
  31931. ], Material.prototype, "separateCullingPass", void 0);
  31932. __decorate([
  31933. BABYLON.serialize("fogEnabled")
  31934. ], Material.prototype, "_fogEnabled", void 0);
  31935. __decorate([
  31936. BABYLON.serialize()
  31937. ], Material.prototype, "pointSize", void 0);
  31938. __decorate([
  31939. BABYLON.serialize()
  31940. ], Material.prototype, "zOffset", void 0);
  31941. __decorate([
  31942. BABYLON.serialize()
  31943. ], Material.prototype, "wireframe", null);
  31944. __decorate([
  31945. BABYLON.serialize()
  31946. ], Material.prototype, "pointsCloud", null);
  31947. __decorate([
  31948. BABYLON.serialize()
  31949. ], Material.prototype, "fillMode", null);
  31950. return Material;
  31951. }());
  31952. BABYLON.Material = Material;
  31953. })(BABYLON || (BABYLON = {}));
  31954. //# sourceMappingURL=babylon.material.js.map
  31955. var BABYLON;
  31956. (function (BABYLON) {
  31957. var UniformBuffer = /** @class */ (function () {
  31958. /**
  31959. * Uniform buffer objects.
  31960. *
  31961. * Handles blocks of uniform on the GPU.
  31962. *
  31963. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31964. *
  31965. * For more information, please refer to :
  31966. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31967. */
  31968. function UniformBuffer(engine, data, dynamic) {
  31969. this._engine = engine;
  31970. this._noUBO = !engine.supportsUniformBuffers;
  31971. this._dynamic = dynamic;
  31972. this._data = data || [];
  31973. this._uniformLocations = {};
  31974. this._uniformSizes = {};
  31975. this._uniformLocationPointer = 0;
  31976. this._needSync = false;
  31977. if (this._noUBO) {
  31978. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31979. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31980. this.updateFloat = this._updateFloatForEffect;
  31981. this.updateFloat2 = this._updateFloat2ForEffect;
  31982. this.updateFloat3 = this._updateFloat3ForEffect;
  31983. this.updateFloat4 = this._updateFloat4ForEffect;
  31984. this.updateMatrix = this._updateMatrixForEffect;
  31985. this.updateVector3 = this._updateVector3ForEffect;
  31986. this.updateVector4 = this._updateVector4ForEffect;
  31987. this.updateColor3 = this._updateColor3ForEffect;
  31988. this.updateColor4 = this._updateColor4ForEffect;
  31989. }
  31990. else {
  31991. this._engine._uniformBuffers.push(this);
  31992. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31993. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31994. this.updateFloat = this._updateFloatForUniform;
  31995. this.updateFloat2 = this._updateFloat2ForUniform;
  31996. this.updateFloat3 = this._updateFloat3ForUniform;
  31997. this.updateFloat4 = this._updateFloat4ForUniform;
  31998. this.updateMatrix = this._updateMatrixForUniform;
  31999. this.updateVector3 = this._updateVector3ForUniform;
  32000. this.updateVector4 = this._updateVector4ForUniform;
  32001. this.updateColor3 = this._updateColor3ForUniform;
  32002. this.updateColor4 = this._updateColor4ForUniform;
  32003. }
  32004. }
  32005. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32006. // Properties
  32007. /**
  32008. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32009. * or just falling back on setUniformXXX calls.
  32010. */
  32011. get: function () {
  32012. return !this._noUBO;
  32013. },
  32014. enumerable: true,
  32015. configurable: true
  32016. });
  32017. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32018. /**
  32019. * Indicates if the WebGL underlying uniform buffer is in sync
  32020. * with the javascript cache data.
  32021. */
  32022. get: function () {
  32023. return !this._needSync;
  32024. },
  32025. enumerable: true,
  32026. configurable: true
  32027. });
  32028. /**
  32029. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32030. * Also, a dynamic UniformBuffer will disable cache verification and always
  32031. * update the underlying WebGL uniform buffer to the GPU.
  32032. */
  32033. UniformBuffer.prototype.isDynamic = function () {
  32034. return this._dynamic !== undefined;
  32035. };
  32036. /**
  32037. * The data cache on JS side.
  32038. */
  32039. UniformBuffer.prototype.getData = function () {
  32040. return this._bufferData;
  32041. };
  32042. /**
  32043. * The underlying WebGL Uniform buffer.
  32044. */
  32045. UniformBuffer.prototype.getBuffer = function () {
  32046. return this._buffer;
  32047. };
  32048. /**
  32049. * std140 layout specifies how to align data within an UBO structure.
  32050. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32051. * for specs.
  32052. */
  32053. UniformBuffer.prototype._fillAlignment = function (size) {
  32054. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32055. // and 4x4 matrices
  32056. // TODO : change if other types are used
  32057. var alignment;
  32058. if (size <= 2) {
  32059. alignment = size;
  32060. }
  32061. else {
  32062. alignment = 4;
  32063. }
  32064. if ((this._uniformLocationPointer % alignment) !== 0) {
  32065. var oldPointer = this._uniformLocationPointer;
  32066. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32067. var diff = this._uniformLocationPointer - oldPointer;
  32068. for (var i = 0; i < diff; i++) {
  32069. this._data.push(0);
  32070. }
  32071. }
  32072. };
  32073. /**
  32074. * Adds an uniform in the buffer.
  32075. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32076. * for the layout to be correct !
  32077. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32078. * @param {number|number[]} size Data size, or data directly.
  32079. */
  32080. UniformBuffer.prototype.addUniform = function (name, size) {
  32081. if (this._noUBO) {
  32082. return;
  32083. }
  32084. if (this._uniformLocations[name] !== undefined) {
  32085. // Already existing uniform
  32086. return;
  32087. }
  32088. // This function must be called in the order of the shader layout !
  32089. // size can be the size of the uniform, or data directly
  32090. var data;
  32091. if (size instanceof Array) {
  32092. data = size;
  32093. size = data.length;
  32094. }
  32095. else {
  32096. size = size;
  32097. data = [];
  32098. // Fill with zeros
  32099. for (var i = 0; i < size; i++) {
  32100. data.push(0);
  32101. }
  32102. }
  32103. this._fillAlignment(size);
  32104. this._uniformSizes[name] = size;
  32105. this._uniformLocations[name] = this._uniformLocationPointer;
  32106. this._uniformLocationPointer += size;
  32107. for (var i = 0; i < size; i++) {
  32108. this._data.push(data[i]);
  32109. }
  32110. this._needSync = true;
  32111. };
  32112. /**
  32113. * Wrapper for addUniform.
  32114. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32115. * @param {Matrix} mat A 4x4 matrix.
  32116. */
  32117. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32118. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32119. };
  32120. /**
  32121. * Wrapper for addUniform.
  32122. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32123. * @param {number} x
  32124. * @param {number} y
  32125. */
  32126. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32127. var temp = [x, y];
  32128. this.addUniform(name, temp);
  32129. };
  32130. /**
  32131. * Wrapper for addUniform.
  32132. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32133. * @param {number} x
  32134. * @param {number} y
  32135. * @param {number} z
  32136. */
  32137. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32138. var temp = [x, y, z];
  32139. this.addUniform(name, temp);
  32140. };
  32141. /**
  32142. * Wrapper for addUniform.
  32143. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32144. * @param {Color3} color
  32145. */
  32146. UniformBuffer.prototype.addColor3 = function (name, color) {
  32147. var temp = new Array();
  32148. color.toArray(temp);
  32149. this.addUniform(name, temp);
  32150. };
  32151. /**
  32152. * Wrapper for addUniform.
  32153. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32154. * @param {Color3} color
  32155. * @param {number} alpha
  32156. */
  32157. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32158. var temp = new Array();
  32159. color.toArray(temp);
  32160. temp.push(alpha);
  32161. this.addUniform(name, temp);
  32162. };
  32163. /**
  32164. * Wrapper for addUniform.
  32165. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32166. * @param {Vector3} vector
  32167. */
  32168. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32169. var temp = new Array();
  32170. vector.toArray(temp);
  32171. this.addUniform(name, temp);
  32172. };
  32173. /**
  32174. * Wrapper for addUniform.
  32175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32176. */
  32177. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32178. this.addUniform(name, 12);
  32179. };
  32180. /**
  32181. * Wrapper for addUniform.
  32182. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32183. */
  32184. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32185. this.addUniform(name, 8);
  32186. };
  32187. /**
  32188. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32189. */
  32190. UniformBuffer.prototype.create = function () {
  32191. if (this._noUBO) {
  32192. return;
  32193. }
  32194. if (this._buffer) {
  32195. return; // nothing to do
  32196. }
  32197. // See spec, alignment must be filled as a vec4
  32198. this._fillAlignment(4);
  32199. this._bufferData = new Float32Array(this._data);
  32200. this._rebuild();
  32201. this._needSync = true;
  32202. };
  32203. UniformBuffer.prototype._rebuild = function () {
  32204. if (this._noUBO) {
  32205. return;
  32206. }
  32207. if (this._dynamic) {
  32208. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32209. }
  32210. else {
  32211. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32212. }
  32213. };
  32214. /**
  32215. * Updates the WebGL Uniform Buffer on the GPU.
  32216. * If the `dynamic` flag is set to true, no cache comparison is done.
  32217. * Otherwise, the buffer will be updated only if the cache differs.
  32218. */
  32219. UniformBuffer.prototype.update = function () {
  32220. if (!this._buffer) {
  32221. this.create();
  32222. return;
  32223. }
  32224. if (!this._dynamic && !this._needSync) {
  32225. return;
  32226. }
  32227. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32228. this._needSync = false;
  32229. };
  32230. /**
  32231. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32232. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32233. * @param {number[]|Float32Array} data Flattened data
  32234. * @param {number} size Size of the data.
  32235. */
  32236. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32237. var location = this._uniformLocations[uniformName];
  32238. if (location === undefined) {
  32239. if (this._buffer) {
  32240. // Cannot add an uniform if the buffer is already created
  32241. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32242. return;
  32243. }
  32244. this.addUniform(uniformName, size);
  32245. location = this._uniformLocations[uniformName];
  32246. }
  32247. if (!this._buffer) {
  32248. this.create();
  32249. }
  32250. if (!this._dynamic) {
  32251. // Cache for static uniform buffers
  32252. var changed = false;
  32253. for (var i = 0; i < size; i++) {
  32254. if (this._bufferData[location + i] !== data[i]) {
  32255. changed = true;
  32256. this._bufferData[location + i] = data[i];
  32257. }
  32258. }
  32259. this._needSync = this._needSync || changed;
  32260. }
  32261. else {
  32262. // No cache for dynamic
  32263. for (var i = 0; i < size; i++) {
  32264. this._bufferData[location + i] = data[i];
  32265. }
  32266. }
  32267. };
  32268. // Update methods
  32269. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32270. // To match std140, matrix must be realigned
  32271. for (var i = 0; i < 3; i++) {
  32272. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32273. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32274. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32275. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32276. }
  32277. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32278. };
  32279. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32280. this._currentEffect.setMatrix3x3(name, matrix);
  32281. };
  32282. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32283. this._currentEffect.setMatrix2x2(name, matrix);
  32284. };
  32285. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32286. // To match std140, matrix must be realigned
  32287. for (var i = 0; i < 2; i++) {
  32288. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32289. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32290. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32291. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32292. }
  32293. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32294. };
  32295. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32296. this._currentEffect.setFloat(name, x);
  32297. };
  32298. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32299. UniformBuffer._tempBuffer[0] = x;
  32300. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32301. };
  32302. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32303. if (suffix === void 0) { suffix = ""; }
  32304. this._currentEffect.setFloat2(name + suffix, x, y);
  32305. };
  32306. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32307. if (suffix === void 0) { suffix = ""; }
  32308. UniformBuffer._tempBuffer[0] = x;
  32309. UniformBuffer._tempBuffer[1] = y;
  32310. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32311. };
  32312. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32313. if (suffix === void 0) { suffix = ""; }
  32314. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32315. };
  32316. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32317. if (suffix === void 0) { suffix = ""; }
  32318. UniformBuffer._tempBuffer[0] = x;
  32319. UniformBuffer._tempBuffer[1] = y;
  32320. UniformBuffer._tempBuffer[2] = z;
  32321. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32322. };
  32323. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32324. if (suffix === void 0) { suffix = ""; }
  32325. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32326. };
  32327. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32328. if (suffix === void 0) { suffix = ""; }
  32329. UniformBuffer._tempBuffer[0] = x;
  32330. UniformBuffer._tempBuffer[1] = y;
  32331. UniformBuffer._tempBuffer[2] = z;
  32332. UniformBuffer._tempBuffer[3] = w;
  32333. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32334. };
  32335. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32336. this._currentEffect.setMatrix(name, mat);
  32337. };
  32338. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32339. this.updateUniform(name, mat.toArray(), 16);
  32340. };
  32341. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32342. this._currentEffect.setVector3(name, vector);
  32343. };
  32344. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32345. vector.toArray(UniformBuffer._tempBuffer);
  32346. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32347. };
  32348. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32349. this._currentEffect.setVector4(name, vector);
  32350. };
  32351. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32352. vector.toArray(UniformBuffer._tempBuffer);
  32353. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32354. };
  32355. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32356. if (suffix === void 0) { suffix = ""; }
  32357. this._currentEffect.setColor3(name + suffix, color);
  32358. };
  32359. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32360. if (suffix === void 0) { suffix = ""; }
  32361. color.toArray(UniformBuffer._tempBuffer);
  32362. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32363. };
  32364. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32365. if (suffix === void 0) { suffix = ""; }
  32366. this._currentEffect.setColor4(name + suffix, color, alpha);
  32367. };
  32368. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32369. if (suffix === void 0) { suffix = ""; }
  32370. color.toArray(UniformBuffer._tempBuffer);
  32371. UniformBuffer._tempBuffer[3] = alpha;
  32372. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32373. };
  32374. /**
  32375. * Sets a sampler uniform on the effect.
  32376. * @param {string} name Name of the sampler.
  32377. * @param {Texture} texture
  32378. */
  32379. UniformBuffer.prototype.setTexture = function (name, texture) {
  32380. this._currentEffect.setTexture(name, texture);
  32381. };
  32382. /**
  32383. * Directly updates the value of the uniform in the cache AND on the GPU.
  32384. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32385. * @param {number[]|Float32Array} data Flattened data
  32386. */
  32387. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32388. this.updateUniform(uniformName, data, data.length);
  32389. this.update();
  32390. };
  32391. /**
  32392. * Binds this uniform buffer to an effect.
  32393. * @param {Effect} effect
  32394. * @param {string} name Name of the uniform block in the shader.
  32395. */
  32396. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32397. this._currentEffect = effect;
  32398. if (this._noUBO || !this._buffer) {
  32399. return;
  32400. }
  32401. effect.bindUniformBuffer(this._buffer, name);
  32402. };
  32403. /**
  32404. * Disposes the uniform buffer.
  32405. */
  32406. UniformBuffer.prototype.dispose = function () {
  32407. if (this._noUBO) {
  32408. return;
  32409. }
  32410. var index = this._engine._uniformBuffers.indexOf(this);
  32411. if (index !== -1) {
  32412. this._engine._uniformBuffers.splice(index, 1);
  32413. }
  32414. if (!this._buffer) {
  32415. return;
  32416. }
  32417. if (this._engine._releaseBuffer(this._buffer)) {
  32418. this._buffer = null;
  32419. }
  32420. };
  32421. // Pool for avoiding memory leaks
  32422. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32423. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32424. return UniformBuffer;
  32425. }());
  32426. BABYLON.UniformBuffer = UniformBuffer;
  32427. })(BABYLON || (BABYLON = {}));
  32428. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32429. var BABYLON;
  32430. (function (BABYLON) {
  32431. var VertexData = /** @class */ (function () {
  32432. function VertexData() {
  32433. }
  32434. VertexData.prototype.set = function (data, kind) {
  32435. switch (kind) {
  32436. case BABYLON.VertexBuffer.PositionKind:
  32437. this.positions = data;
  32438. break;
  32439. case BABYLON.VertexBuffer.NormalKind:
  32440. this.normals = data;
  32441. break;
  32442. case BABYLON.VertexBuffer.TangentKind:
  32443. this.tangents = data;
  32444. break;
  32445. case BABYLON.VertexBuffer.UVKind:
  32446. this.uvs = data;
  32447. break;
  32448. case BABYLON.VertexBuffer.UV2Kind:
  32449. this.uvs2 = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.UV3Kind:
  32452. this.uvs3 = data;
  32453. break;
  32454. case BABYLON.VertexBuffer.UV4Kind:
  32455. this.uvs4 = data;
  32456. break;
  32457. case BABYLON.VertexBuffer.UV5Kind:
  32458. this.uvs5 = data;
  32459. break;
  32460. case BABYLON.VertexBuffer.UV6Kind:
  32461. this.uvs6 = data;
  32462. break;
  32463. case BABYLON.VertexBuffer.ColorKind:
  32464. this.colors = data;
  32465. break;
  32466. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32467. this.matricesIndices = data;
  32468. break;
  32469. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32470. this.matricesWeights = data;
  32471. break;
  32472. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32473. this.matricesIndicesExtra = data;
  32474. break;
  32475. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32476. this.matricesWeightsExtra = data;
  32477. break;
  32478. }
  32479. };
  32480. /**
  32481. * Associates the vertexData to the passed Mesh.
  32482. * Sets it as updatable or not (default `false`).
  32483. * Returns the VertexData.
  32484. */
  32485. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32486. this._applyTo(mesh, updatable);
  32487. return this;
  32488. };
  32489. /**
  32490. * Associates the vertexData to the passed Geometry.
  32491. * Sets it as updatable or not (default `false`).
  32492. * Returns the VertexData.
  32493. */
  32494. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32495. this._applyTo(geometry, updatable);
  32496. return this;
  32497. };
  32498. /**
  32499. * Updates the associated mesh.
  32500. * Returns the VertexData.
  32501. */
  32502. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32503. this._update(mesh);
  32504. return this;
  32505. };
  32506. /**
  32507. * Updates the associated geometry.
  32508. * Returns the VertexData.
  32509. */
  32510. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32511. this._update(geometry);
  32512. return this;
  32513. };
  32514. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32515. if (updatable === void 0) { updatable = false; }
  32516. if (this.positions) {
  32517. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32518. }
  32519. if (this.normals) {
  32520. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32521. }
  32522. if (this.tangents) {
  32523. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32524. }
  32525. if (this.uvs) {
  32526. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32527. }
  32528. if (this.uvs2) {
  32529. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32530. }
  32531. if (this.uvs3) {
  32532. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32533. }
  32534. if (this.uvs4) {
  32535. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32536. }
  32537. if (this.uvs5) {
  32538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32539. }
  32540. if (this.uvs6) {
  32541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32542. }
  32543. if (this.colors) {
  32544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32545. }
  32546. if (this.matricesIndices) {
  32547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32548. }
  32549. if (this.matricesWeights) {
  32550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32551. }
  32552. if (this.matricesIndicesExtra) {
  32553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32554. }
  32555. if (this.matricesWeightsExtra) {
  32556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32557. }
  32558. if (this.indices) {
  32559. meshOrGeometry.setIndices(this.indices, null, updatable);
  32560. }
  32561. return this;
  32562. };
  32563. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32564. if (this.positions) {
  32565. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32566. }
  32567. if (this.normals) {
  32568. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32569. }
  32570. if (this.tangents) {
  32571. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32572. }
  32573. if (this.uvs) {
  32574. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32575. }
  32576. if (this.uvs2) {
  32577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32578. }
  32579. if (this.uvs3) {
  32580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32581. }
  32582. if (this.uvs4) {
  32583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32584. }
  32585. if (this.uvs5) {
  32586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32587. }
  32588. if (this.uvs6) {
  32589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32590. }
  32591. if (this.colors) {
  32592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32593. }
  32594. if (this.matricesIndices) {
  32595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32596. }
  32597. if (this.matricesWeights) {
  32598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32599. }
  32600. if (this.matricesIndicesExtra) {
  32601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32602. }
  32603. if (this.matricesWeightsExtra) {
  32604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32605. }
  32606. if (this.indices) {
  32607. meshOrGeometry.setIndices(this.indices, null);
  32608. }
  32609. return this;
  32610. };
  32611. /**
  32612. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32613. * Returns the VertexData.
  32614. */
  32615. VertexData.prototype.transform = function (matrix) {
  32616. var transformed = BABYLON.Vector3.Zero();
  32617. var index;
  32618. if (this.positions) {
  32619. var position = BABYLON.Vector3.Zero();
  32620. for (index = 0; index < this.positions.length; index += 3) {
  32621. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32622. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32623. this.positions[index] = transformed.x;
  32624. this.positions[index + 1] = transformed.y;
  32625. this.positions[index + 2] = transformed.z;
  32626. }
  32627. }
  32628. if (this.normals) {
  32629. var normal = BABYLON.Vector3.Zero();
  32630. for (index = 0; index < this.normals.length; index += 3) {
  32631. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32632. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32633. this.normals[index] = transformed.x;
  32634. this.normals[index + 1] = transformed.y;
  32635. this.normals[index + 2] = transformed.z;
  32636. }
  32637. }
  32638. if (this.tangents) {
  32639. var tangent = BABYLON.Vector4.Zero();
  32640. var tangentTransformed = BABYLON.Vector4.Zero();
  32641. for (index = 0; index < this.tangents.length; index += 4) {
  32642. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32643. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32644. this.tangents[index] = tangentTransformed.x;
  32645. this.tangents[index + 1] = tangentTransformed.y;
  32646. this.tangents[index + 2] = tangentTransformed.z;
  32647. this.tangents[index + 3] = tangentTransformed.w;
  32648. }
  32649. }
  32650. return this;
  32651. };
  32652. /**
  32653. * Merges the passed VertexData into the current one.
  32654. * Returns the modified VertexData.
  32655. */
  32656. VertexData.prototype.merge = function (other) {
  32657. this._validate();
  32658. other._validate();
  32659. if (!this.normals !== !other.normals ||
  32660. !this.tangents !== !other.tangents ||
  32661. !this.uvs !== !other.uvs ||
  32662. !this.uvs2 !== !other.uvs2 ||
  32663. !this.uvs3 !== !other.uvs3 ||
  32664. !this.uvs4 !== !other.uvs4 ||
  32665. !this.uvs5 !== !other.uvs5 ||
  32666. !this.uvs6 !== !other.uvs6 ||
  32667. !this.colors !== !other.colors ||
  32668. !this.matricesIndices !== !other.matricesIndices ||
  32669. !this.matricesWeights !== !other.matricesWeights ||
  32670. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32671. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32672. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32673. }
  32674. if (other.indices) {
  32675. if (!this.indices) {
  32676. this.indices = [];
  32677. }
  32678. var offset = this.positions ? this.positions.length / 3 : 0;
  32679. for (var index = 0; index < other.indices.length; index++) {
  32680. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32681. this.indices.push(other.indices[index] + offset);
  32682. }
  32683. }
  32684. this.positions = this._mergeElement(this.positions, other.positions);
  32685. this.normals = this._mergeElement(this.normals, other.normals);
  32686. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32687. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32688. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32689. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32690. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32691. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32692. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32693. this.colors = this._mergeElement(this.colors, other.colors);
  32694. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32695. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32696. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32697. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32698. return this;
  32699. };
  32700. VertexData.prototype._mergeElement = function (source, other) {
  32701. if (!source) {
  32702. return other;
  32703. }
  32704. if (!other) {
  32705. return source;
  32706. }
  32707. var len = other.length + source.length;
  32708. var isSrcTypedArray = source instanceof Float32Array;
  32709. var isOthTypedArray = other instanceof Float32Array;
  32710. // use non-loop method when the source is Float32Array
  32711. if (isSrcTypedArray) {
  32712. var ret32 = new Float32Array(len);
  32713. ret32.set(source);
  32714. ret32.set(other, source.length);
  32715. return ret32;
  32716. // source is number[], when other is also use concat
  32717. }
  32718. else if (!isOthTypedArray) {
  32719. return source.concat(other);
  32720. // source is a number[], but other is a Float32Array, loop required
  32721. }
  32722. else {
  32723. var ret = source.slice(0); // copy source to a separate array
  32724. for (var i = 0, len = other.length; i < len; i++) {
  32725. ret.push(other[i]);
  32726. }
  32727. return ret;
  32728. }
  32729. };
  32730. VertexData.prototype._validate = function () {
  32731. if (!this.positions) {
  32732. throw new Error("Positions are required");
  32733. }
  32734. var getElementCount = function (kind, values) {
  32735. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32736. if ((values.length % stride) !== 0) {
  32737. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32738. }
  32739. return values.length / stride;
  32740. };
  32741. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32742. var validateElementCount = function (kind, values) {
  32743. var elementCount = getElementCount(kind, values);
  32744. if (elementCount !== positionsElementCount) {
  32745. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32746. }
  32747. };
  32748. if (this.normals)
  32749. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32750. if (this.tangents)
  32751. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32752. if (this.uvs)
  32753. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32754. if (this.uvs2)
  32755. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32756. if (this.uvs3)
  32757. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32758. if (this.uvs4)
  32759. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32760. if (this.uvs5)
  32761. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32762. if (this.uvs6)
  32763. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32764. if (this.colors)
  32765. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32766. if (this.matricesIndices)
  32767. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32768. if (this.matricesWeights)
  32769. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32770. if (this.matricesIndicesExtra)
  32771. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32772. if (this.matricesWeightsExtra)
  32773. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32774. };
  32775. /**
  32776. * Serializes the VertexData.
  32777. * Returns a serialized object.
  32778. */
  32779. VertexData.prototype.serialize = function () {
  32780. var serializationObject = this.serialize();
  32781. if (this.positions) {
  32782. serializationObject.positions = this.positions;
  32783. }
  32784. if (this.normals) {
  32785. serializationObject.normals = this.normals;
  32786. }
  32787. if (this.tangents) {
  32788. serializationObject.tangents = this.tangents;
  32789. }
  32790. if (this.uvs) {
  32791. serializationObject.uvs = this.uvs;
  32792. }
  32793. if (this.uvs2) {
  32794. serializationObject.uvs2 = this.uvs2;
  32795. }
  32796. if (this.uvs3) {
  32797. serializationObject.uvs3 = this.uvs3;
  32798. }
  32799. if (this.uvs4) {
  32800. serializationObject.uvs4 = this.uvs4;
  32801. }
  32802. if (this.uvs5) {
  32803. serializationObject.uvs5 = this.uvs5;
  32804. }
  32805. if (this.uvs6) {
  32806. serializationObject.uvs6 = this.uvs6;
  32807. }
  32808. if (this.colors) {
  32809. serializationObject.colors = this.colors;
  32810. }
  32811. if (this.matricesIndices) {
  32812. serializationObject.matricesIndices = this.matricesIndices;
  32813. serializationObject.matricesIndices._isExpanded = true;
  32814. }
  32815. if (this.matricesWeights) {
  32816. serializationObject.matricesWeights = this.matricesWeights;
  32817. }
  32818. if (this.matricesIndicesExtra) {
  32819. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32820. serializationObject.matricesIndicesExtra._isExpanded = true;
  32821. }
  32822. if (this.matricesWeightsExtra) {
  32823. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32824. }
  32825. serializationObject.indices = this.indices;
  32826. return serializationObject;
  32827. };
  32828. // Statics
  32829. /**
  32830. * Returns the object VertexData associated to the passed mesh.
  32831. */
  32832. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32833. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32834. };
  32835. /**
  32836. * Returns the object VertexData associated to the passed geometry.
  32837. */
  32838. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32839. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32840. };
  32841. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32842. var result = new VertexData();
  32843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32844. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32845. }
  32846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32847. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32848. }
  32849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32850. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32851. }
  32852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32853. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32854. }
  32855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32856. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32857. }
  32858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32859. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32860. }
  32861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32862. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32863. }
  32864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32865. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32866. }
  32867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32868. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32869. }
  32870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32871. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32872. }
  32873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32874. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32875. }
  32876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32877. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32878. }
  32879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32880. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32881. }
  32882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32883. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32884. }
  32885. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32886. return result;
  32887. };
  32888. /**
  32889. * Creates the vertexData of the Ribbon.
  32890. */
  32891. VertexData.CreateRibbon = function (options) {
  32892. var pathArray = options.pathArray;
  32893. var closeArray = options.closeArray || false;
  32894. var closePath = options.closePath || false;
  32895. var invertUV = options.invertUV || false;
  32896. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32897. var offset = options.offset || defaultOffset;
  32898. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32899. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32900. var customUV = options.uvs;
  32901. var customColors = options.colors;
  32902. var positions = [];
  32903. var indices = [];
  32904. var normals = [];
  32905. var uvs = [];
  32906. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32907. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32908. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32909. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32910. var minlg; // minimal length among all paths from pathArray
  32911. var lg = []; // array of path lengths : nb of vertex per path
  32912. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32913. var p; // path iterator
  32914. var i; // point iterator
  32915. var j; // point iterator
  32916. // if single path in pathArray
  32917. if (pathArray.length < 2) {
  32918. var ar1 = [];
  32919. var ar2 = [];
  32920. for (i = 0; i < pathArray[0].length - offset; i++) {
  32921. ar1.push(pathArray[0][i]);
  32922. ar2.push(pathArray[0][i + offset]);
  32923. }
  32924. pathArray = [ar1, ar2];
  32925. }
  32926. // positions and horizontal distances (u)
  32927. var idc = 0;
  32928. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32929. var path;
  32930. var l;
  32931. minlg = pathArray[0].length;
  32932. var vectlg;
  32933. var dist;
  32934. for (p = 0; p < pathArray.length; p++) {
  32935. uTotalDistance[p] = 0;
  32936. us[p] = [0];
  32937. path = pathArray[p];
  32938. l = path.length;
  32939. minlg = (minlg < l) ? minlg : l;
  32940. j = 0;
  32941. while (j < l) {
  32942. positions.push(path[j].x, path[j].y, path[j].z);
  32943. if (j > 0) {
  32944. vectlg = path[j].subtract(path[j - 1]).length();
  32945. dist = vectlg + uTotalDistance[p];
  32946. us[p].push(dist);
  32947. uTotalDistance[p] = dist;
  32948. }
  32949. j++;
  32950. }
  32951. if (closePath) {
  32952. j--;
  32953. positions.push(path[0].x, path[0].y, path[0].z);
  32954. vectlg = path[j].subtract(path[0]).length();
  32955. dist = vectlg + uTotalDistance[p];
  32956. us[p].push(dist);
  32957. uTotalDistance[p] = dist;
  32958. }
  32959. lg[p] = l + closePathCorr;
  32960. idx[p] = idc;
  32961. idc += (l + closePathCorr);
  32962. }
  32963. // vertical distances (v)
  32964. var path1;
  32965. var path2;
  32966. var vertex1 = null;
  32967. var vertex2 = null;
  32968. for (i = 0; i < minlg + closePathCorr; i++) {
  32969. vTotalDistance[i] = 0;
  32970. vs[i] = [0];
  32971. for (p = 0; p < pathArray.length - 1; p++) {
  32972. path1 = pathArray[p];
  32973. path2 = pathArray[p + 1];
  32974. if (i === minlg) {
  32975. vertex1 = path1[0];
  32976. vertex2 = path2[0];
  32977. }
  32978. else {
  32979. vertex1 = path1[i];
  32980. vertex2 = path2[i];
  32981. }
  32982. vectlg = vertex2.subtract(vertex1).length();
  32983. dist = vectlg + vTotalDistance[i];
  32984. vs[i].push(dist);
  32985. vTotalDistance[i] = dist;
  32986. }
  32987. if (closeArray && vertex2 && vertex1) {
  32988. path1 = pathArray[p];
  32989. path2 = pathArray[0];
  32990. if (i === minlg) {
  32991. vertex2 = path2[0];
  32992. }
  32993. vectlg = vertex2.subtract(vertex1).length();
  32994. dist = vectlg + vTotalDistance[i];
  32995. vTotalDistance[i] = dist;
  32996. }
  32997. }
  32998. // uvs
  32999. var u;
  33000. var v;
  33001. if (customUV) {
  33002. for (p = 0; p < customUV.length; p++) {
  33003. uvs.push(customUV[p].x, customUV[p].y);
  33004. }
  33005. }
  33006. else {
  33007. for (p = 0; p < pathArray.length; p++) {
  33008. for (i = 0; i < minlg + closePathCorr; i++) {
  33009. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33010. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33011. if (invertUV) {
  33012. uvs.push(v, u);
  33013. }
  33014. else {
  33015. uvs.push(u, v);
  33016. }
  33017. }
  33018. }
  33019. }
  33020. // indices
  33021. p = 0; // path index
  33022. var pi = 0; // positions array index
  33023. var l1 = lg[p] - 1; // path1 length
  33024. var l2 = lg[p + 1] - 1; // path2 length
  33025. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33026. var shft = idx[1] - idx[0]; // shift
  33027. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33028. while (pi <= min && p < path1nb) {
  33029. // 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
  33030. indices.push(pi, pi + shft, pi + 1);
  33031. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33032. pi += 1;
  33033. if (pi === min) {
  33034. p++;
  33035. if (p === lg.length - 1) {
  33036. shft = idx[0] - idx[p];
  33037. l1 = lg[p] - 1;
  33038. l2 = lg[0] - 1;
  33039. }
  33040. else {
  33041. shft = idx[p + 1] - idx[p];
  33042. l1 = lg[p] - 1;
  33043. l2 = lg[p + 1] - 1;
  33044. }
  33045. pi = idx[p];
  33046. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33047. }
  33048. }
  33049. // normals
  33050. VertexData.ComputeNormals(positions, indices, normals);
  33051. if (closePath) {
  33052. var indexFirst = 0;
  33053. var indexLast = 0;
  33054. for (p = 0; p < pathArray.length; p++) {
  33055. indexFirst = idx[p] * 3;
  33056. if (p + 1 < pathArray.length) {
  33057. indexLast = (idx[p + 1] - 1) * 3;
  33058. }
  33059. else {
  33060. indexLast = normals.length - 3;
  33061. }
  33062. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33063. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33064. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33065. normals[indexLast] = normals[indexFirst];
  33066. normals[indexLast + 1] = normals[indexFirst + 1];
  33067. normals[indexLast + 2] = normals[indexFirst + 2];
  33068. }
  33069. }
  33070. // sides
  33071. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33072. // Colors
  33073. var colors = null;
  33074. if (customColors) {
  33075. colors = new Float32Array(customColors.length * 4);
  33076. for (var c = 0; c < customColors.length; c++) {
  33077. colors[c * 4] = customColors[c].r;
  33078. colors[c * 4 + 1] = customColors[c].g;
  33079. colors[c * 4 + 2] = customColors[c].b;
  33080. colors[c * 4 + 3] = customColors[c].a;
  33081. }
  33082. }
  33083. // Result
  33084. var vertexData = new VertexData();
  33085. var positions32 = new Float32Array(positions);
  33086. var normals32 = new Float32Array(normals);
  33087. var uvs32 = new Float32Array(uvs);
  33088. vertexData.indices = indices;
  33089. vertexData.positions = positions32;
  33090. vertexData.normals = normals32;
  33091. vertexData.uvs = uvs32;
  33092. if (colors) {
  33093. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33094. }
  33095. if (closePath) {
  33096. vertexData._idx = idx;
  33097. }
  33098. return vertexData;
  33099. };
  33100. /**
  33101. * Creates the VertexData of the Box.
  33102. */
  33103. VertexData.CreateBox = function (options) {
  33104. var normalsSource = [
  33105. new BABYLON.Vector3(0, 0, 1),
  33106. new BABYLON.Vector3(0, 0, -1),
  33107. new BABYLON.Vector3(1, 0, 0),
  33108. new BABYLON.Vector3(-1, 0, 0),
  33109. new BABYLON.Vector3(0, 1, 0),
  33110. new BABYLON.Vector3(0, -1, 0)
  33111. ];
  33112. var indices = [];
  33113. var positions = [];
  33114. var normals = [];
  33115. var uvs = [];
  33116. var width = options.width || options.size || 1;
  33117. var height = options.height || options.size || 1;
  33118. var depth = options.depth || options.size || 1;
  33119. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33120. var faceUV = options.faceUV || new Array(6);
  33121. var faceColors = options.faceColors;
  33122. var colors = [];
  33123. // default face colors and UV if undefined
  33124. for (var f = 0; f < 6; f++) {
  33125. if (faceUV[f] === undefined) {
  33126. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33127. }
  33128. if (faceColors && faceColors[f] === undefined) {
  33129. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33130. }
  33131. }
  33132. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33133. // Create each face in turn.
  33134. for (var index = 0; index < normalsSource.length; index++) {
  33135. var normal = normalsSource[index];
  33136. // Get two vectors perpendicular to the face normal and to each other.
  33137. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33138. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33139. // Six indices (two triangles) per face.
  33140. var verticesLength = positions.length / 3;
  33141. indices.push(verticesLength);
  33142. indices.push(verticesLength + 1);
  33143. indices.push(verticesLength + 2);
  33144. indices.push(verticesLength);
  33145. indices.push(verticesLength + 2);
  33146. indices.push(verticesLength + 3);
  33147. // Four vertices per face.
  33148. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33149. positions.push(vertex.x, vertex.y, vertex.z);
  33150. normals.push(normal.x, normal.y, normal.z);
  33151. uvs.push(faceUV[index].z, faceUV[index].w);
  33152. if (faceColors) {
  33153. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33154. }
  33155. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33156. positions.push(vertex.x, vertex.y, vertex.z);
  33157. normals.push(normal.x, normal.y, normal.z);
  33158. uvs.push(faceUV[index].x, faceUV[index].w);
  33159. if (faceColors) {
  33160. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33161. }
  33162. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33163. positions.push(vertex.x, vertex.y, vertex.z);
  33164. normals.push(normal.x, normal.y, normal.z);
  33165. uvs.push(faceUV[index].x, faceUV[index].y);
  33166. if (faceColors) {
  33167. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33168. }
  33169. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33170. positions.push(vertex.x, vertex.y, vertex.z);
  33171. normals.push(normal.x, normal.y, normal.z);
  33172. uvs.push(faceUV[index].z, faceUV[index].y);
  33173. if (faceColors) {
  33174. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33175. }
  33176. }
  33177. // sides
  33178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33179. // Result
  33180. var vertexData = new VertexData();
  33181. vertexData.indices = indices;
  33182. vertexData.positions = positions;
  33183. vertexData.normals = normals;
  33184. vertexData.uvs = uvs;
  33185. if (faceColors) {
  33186. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33187. vertexData.colors = totalColors;
  33188. }
  33189. return vertexData;
  33190. };
  33191. /**
  33192. * Creates the VertexData of the Sphere.
  33193. */
  33194. VertexData.CreateSphere = function (options) {
  33195. var segments = options.segments || 32;
  33196. var diameterX = options.diameterX || options.diameter || 1;
  33197. var diameterY = options.diameterY || options.diameter || 1;
  33198. var diameterZ = options.diameterZ || options.diameter || 1;
  33199. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33200. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33201. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33202. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33203. var totalZRotationSteps = 2 + segments;
  33204. var totalYRotationSteps = 2 * totalZRotationSteps;
  33205. var indices = [];
  33206. var positions = [];
  33207. var normals = [];
  33208. var uvs = [];
  33209. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33210. var normalizedZ = zRotationStep / totalZRotationSteps;
  33211. var angleZ = normalizedZ * Math.PI * slice;
  33212. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33213. var normalizedY = yRotationStep / totalYRotationSteps;
  33214. var angleY = normalizedY * Math.PI * 2 * arc;
  33215. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33216. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33217. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33218. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33219. var vertex = complete.multiply(radius);
  33220. var normal = complete.divide(radius).normalize();
  33221. positions.push(vertex.x, vertex.y, vertex.z);
  33222. normals.push(normal.x, normal.y, normal.z);
  33223. uvs.push(normalizedY, normalizedZ);
  33224. }
  33225. if (zRotationStep > 0) {
  33226. var verticesCount = positions.length / 3;
  33227. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33228. indices.push((firstIndex));
  33229. indices.push((firstIndex + 1));
  33230. indices.push(firstIndex + totalYRotationSteps + 1);
  33231. indices.push((firstIndex + totalYRotationSteps + 1));
  33232. indices.push((firstIndex + 1));
  33233. indices.push((firstIndex + totalYRotationSteps + 2));
  33234. }
  33235. }
  33236. }
  33237. // Sides
  33238. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33239. // Result
  33240. var vertexData = new VertexData();
  33241. vertexData.indices = indices;
  33242. vertexData.positions = positions;
  33243. vertexData.normals = normals;
  33244. vertexData.uvs = uvs;
  33245. return vertexData;
  33246. };
  33247. /**
  33248. * Creates the VertexData of the Cylinder or Cone.
  33249. */
  33250. VertexData.CreateCylinder = function (options) {
  33251. var height = options.height || 2;
  33252. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33253. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33254. var tessellation = options.tessellation || 24;
  33255. var subdivisions = options.subdivisions || 1;
  33256. var hasRings = options.hasRings ? true : false;
  33257. var enclose = options.enclose ? true : false;
  33258. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33259. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33260. var faceUV = options.faceUV || new Array(3);
  33261. var faceColors = options.faceColors;
  33262. // default face colors and UV if undefined
  33263. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33264. var ringNb = (hasRings) ? subdivisions : 1;
  33265. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33266. var f;
  33267. for (f = 0; f < surfaceNb; f++) {
  33268. if (faceColors && faceColors[f] === undefined) {
  33269. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33270. }
  33271. }
  33272. for (f = 0; f < surfaceNb; f++) {
  33273. if (faceUV && faceUV[f] === undefined) {
  33274. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33275. }
  33276. }
  33277. var indices = new Array();
  33278. var positions = new Array();
  33279. var normals = new Array();
  33280. var uvs = new Array();
  33281. var colors = new Array();
  33282. var angle_step = Math.PI * 2 * arc / tessellation;
  33283. var angle;
  33284. var h;
  33285. var radius;
  33286. var tan = (diameterBottom - diameterTop) / 2 / height;
  33287. var ringVertex = BABYLON.Vector3.Zero();
  33288. var ringNormal = BABYLON.Vector3.Zero();
  33289. var ringFirstVertex = BABYLON.Vector3.Zero();
  33290. var ringFirstNormal = BABYLON.Vector3.Zero();
  33291. var quadNormal = BABYLON.Vector3.Zero();
  33292. var Y = BABYLON.Axis.Y;
  33293. // positions, normals, uvs
  33294. var i;
  33295. var j;
  33296. var r;
  33297. var ringIdx = 1;
  33298. var s = 1; // surface index
  33299. var cs = 0;
  33300. var v = 0;
  33301. for (i = 0; i <= subdivisions; i++) {
  33302. h = i / subdivisions;
  33303. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33304. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33305. for (r = 0; r < ringIdx; r++) {
  33306. if (hasRings) {
  33307. s += r;
  33308. }
  33309. if (enclose) {
  33310. s += 2 * r;
  33311. }
  33312. for (j = 0; j <= tessellation; j++) {
  33313. angle = j * angle_step;
  33314. // position
  33315. ringVertex.x = Math.cos(-angle) * radius;
  33316. ringVertex.y = -height / 2 + h * height;
  33317. ringVertex.z = Math.sin(-angle) * radius;
  33318. // normal
  33319. if (diameterTop === 0 && i === subdivisions) {
  33320. // if no top cap, reuse former normals
  33321. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33322. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33323. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33324. }
  33325. else {
  33326. ringNormal.x = ringVertex.x;
  33327. ringNormal.z = ringVertex.z;
  33328. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33329. ringNormal.normalize();
  33330. }
  33331. // keep first ring vertex values for enclose
  33332. if (j === 0) {
  33333. ringFirstVertex.copyFrom(ringVertex);
  33334. ringFirstNormal.copyFrom(ringNormal);
  33335. }
  33336. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33337. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33338. if (hasRings) {
  33339. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33340. }
  33341. else {
  33342. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33343. }
  33344. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33345. if (faceColors) {
  33346. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33347. }
  33348. }
  33349. // if enclose, add four vertices and their dedicated normals
  33350. if (arc !== 1 && enclose) {
  33351. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33352. positions.push(0, ringVertex.y, 0);
  33353. positions.push(0, ringVertex.y, 0);
  33354. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33355. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33356. quadNormal.normalize();
  33357. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33358. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33359. quadNormal.normalize();
  33360. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33361. if (hasRings) {
  33362. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33363. }
  33364. else {
  33365. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33366. }
  33367. uvs.push(faceUV[s + 1].x, v);
  33368. uvs.push(faceUV[s + 1].z, v);
  33369. if (hasRings) {
  33370. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33371. }
  33372. else {
  33373. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33374. }
  33375. uvs.push(faceUV[s + 2].x, v);
  33376. uvs.push(faceUV[s + 2].z, v);
  33377. if (faceColors) {
  33378. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33379. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33380. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33381. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33382. }
  33383. }
  33384. if (cs !== s) {
  33385. cs = s;
  33386. }
  33387. }
  33388. }
  33389. // indices
  33390. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33391. var s;
  33392. i = 0;
  33393. for (s = 0; s < subdivisions; s++) {
  33394. var i0 = 0;
  33395. var i1 = 0;
  33396. var i2 = 0;
  33397. var i3 = 0;
  33398. for (j = 0; j < tessellation; j++) {
  33399. i0 = i * (e + 1) + j;
  33400. i1 = (i + 1) * (e + 1) + j;
  33401. i2 = i * (e + 1) + (j + 1);
  33402. i3 = (i + 1) * (e + 1) + (j + 1);
  33403. indices.push(i0, i1, i2);
  33404. indices.push(i3, i2, i1);
  33405. }
  33406. if (arc !== 1 && enclose) {
  33407. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33408. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33409. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33410. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33411. }
  33412. i = (hasRings) ? (i + 2) : (i + 1);
  33413. }
  33414. // Caps
  33415. var createCylinderCap = function (isTop) {
  33416. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33417. if (radius === 0) {
  33418. return;
  33419. }
  33420. // Cap positions, normals & uvs
  33421. var angle;
  33422. var circleVector;
  33423. var i;
  33424. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33425. var c = null;
  33426. if (faceColors) {
  33427. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33428. }
  33429. // cap center
  33430. var vbase = positions.length / 3;
  33431. var offset = isTop ? height / 2 : -height / 2;
  33432. var center = new BABYLON.Vector3(0, offset, 0);
  33433. positions.push(center.x, center.y, center.z);
  33434. normals.push(0, isTop ? 1 : -1, 0);
  33435. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33436. if (c) {
  33437. colors.push(c.r, c.g, c.b, c.a);
  33438. }
  33439. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33440. for (i = 0; i <= tessellation; i++) {
  33441. angle = Math.PI * 2 * i * arc / tessellation;
  33442. var cos = Math.cos(-angle);
  33443. var sin = Math.sin(-angle);
  33444. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33445. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33446. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33447. normals.push(0, isTop ? 1 : -1, 0);
  33448. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33449. if (c) {
  33450. colors.push(c.r, c.g, c.b, c.a);
  33451. }
  33452. }
  33453. // Cap indices
  33454. for (i = 0; i < tessellation; i++) {
  33455. if (!isTop) {
  33456. indices.push(vbase);
  33457. indices.push(vbase + (i + 1));
  33458. indices.push(vbase + (i + 2));
  33459. }
  33460. else {
  33461. indices.push(vbase);
  33462. indices.push(vbase + (i + 2));
  33463. indices.push(vbase + (i + 1));
  33464. }
  33465. }
  33466. };
  33467. // add caps to geometry
  33468. createCylinderCap(false);
  33469. createCylinderCap(true);
  33470. // Sides
  33471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33472. var vertexData = new VertexData();
  33473. vertexData.indices = indices;
  33474. vertexData.positions = positions;
  33475. vertexData.normals = normals;
  33476. vertexData.uvs = uvs;
  33477. if (faceColors) {
  33478. vertexData.colors = colors;
  33479. }
  33480. return vertexData;
  33481. };
  33482. /**
  33483. * Creates the VertexData of the Torus.
  33484. */
  33485. VertexData.CreateTorus = function (options) {
  33486. var indices = [];
  33487. var positions = [];
  33488. var normals = [];
  33489. var uvs = [];
  33490. var diameter = options.diameter || 1;
  33491. var thickness = options.thickness || 0.5;
  33492. var tessellation = options.tessellation || 16;
  33493. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33494. var stride = tessellation + 1;
  33495. for (var i = 0; i <= tessellation; i++) {
  33496. var u = i / tessellation;
  33497. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33498. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33499. for (var j = 0; j <= tessellation; j++) {
  33500. var v = 1 - j / tessellation;
  33501. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33502. var dx = Math.cos(innerAngle);
  33503. var dy = Math.sin(innerAngle);
  33504. // Create a vertex.
  33505. var normal = new BABYLON.Vector3(dx, dy, 0);
  33506. var position = normal.scale(thickness / 2);
  33507. var textureCoordinate = new BABYLON.Vector2(u, v);
  33508. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33509. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33510. positions.push(position.x, position.y, position.z);
  33511. normals.push(normal.x, normal.y, normal.z);
  33512. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33513. // And create indices for two triangles.
  33514. var nextI = (i + 1) % stride;
  33515. var nextJ = (j + 1) % stride;
  33516. indices.push(i * stride + j);
  33517. indices.push(i * stride + nextJ);
  33518. indices.push(nextI * stride + j);
  33519. indices.push(i * stride + nextJ);
  33520. indices.push(nextI * stride + nextJ);
  33521. indices.push(nextI * stride + j);
  33522. }
  33523. }
  33524. // Sides
  33525. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33526. // Result
  33527. var vertexData = new VertexData();
  33528. vertexData.indices = indices;
  33529. vertexData.positions = positions;
  33530. vertexData.normals = normals;
  33531. vertexData.uvs = uvs;
  33532. return vertexData;
  33533. };
  33534. /**
  33535. * Creates the VertexData of the LineSystem.
  33536. */
  33537. VertexData.CreateLineSystem = function (options) {
  33538. var indices = [];
  33539. var positions = [];
  33540. var lines = options.lines;
  33541. var colors = options.colors;
  33542. var vertexColors = [];
  33543. var idx = 0;
  33544. for (var l = 0; l < lines.length; l++) {
  33545. var points = lines[l];
  33546. for (var index = 0; index < points.length; index++) {
  33547. positions.push(points[index].x, points[index].y, points[index].z);
  33548. if (colors) {
  33549. var color = colors[l];
  33550. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33551. }
  33552. if (index > 0) {
  33553. indices.push(idx - 1);
  33554. indices.push(idx);
  33555. }
  33556. idx++;
  33557. }
  33558. }
  33559. var vertexData = new VertexData();
  33560. vertexData.indices = indices;
  33561. vertexData.positions = positions;
  33562. if (colors) {
  33563. vertexData.colors = vertexColors;
  33564. }
  33565. return vertexData;
  33566. };
  33567. /**
  33568. * Create the VertexData of the DashedLines.
  33569. */
  33570. VertexData.CreateDashedLines = function (options) {
  33571. var dashSize = options.dashSize || 3;
  33572. var gapSize = options.gapSize || 1;
  33573. var dashNb = options.dashNb || 200;
  33574. var points = options.points;
  33575. var positions = new Array();
  33576. var indices = new Array();
  33577. var curvect = BABYLON.Vector3.Zero();
  33578. var lg = 0;
  33579. var nb = 0;
  33580. var shft = 0;
  33581. var dashshft = 0;
  33582. var curshft = 0;
  33583. var idx = 0;
  33584. var i = 0;
  33585. for (i = 0; i < points.length - 1; i++) {
  33586. points[i + 1].subtractToRef(points[i], curvect);
  33587. lg += curvect.length();
  33588. }
  33589. shft = lg / dashNb;
  33590. dashshft = dashSize * shft / (dashSize + gapSize);
  33591. for (i = 0; i < points.length - 1; i++) {
  33592. points[i + 1].subtractToRef(points[i], curvect);
  33593. nb = Math.floor(curvect.length() / shft);
  33594. curvect.normalize();
  33595. for (var j = 0; j < nb; j++) {
  33596. curshft = shft * j;
  33597. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33598. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33599. indices.push(idx, idx + 1);
  33600. idx += 2;
  33601. }
  33602. }
  33603. // Result
  33604. var vertexData = new VertexData();
  33605. vertexData.positions = positions;
  33606. vertexData.indices = indices;
  33607. return vertexData;
  33608. };
  33609. /**
  33610. * Creates the VertexData of the Ground.
  33611. */
  33612. VertexData.CreateGround = function (options) {
  33613. var indices = [];
  33614. var positions = [];
  33615. var normals = [];
  33616. var uvs = [];
  33617. var row, col;
  33618. var width = options.width || 1;
  33619. var height = options.height || 1;
  33620. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33621. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33622. for (row = 0; row <= subdivisionsY; row++) {
  33623. for (col = 0; col <= subdivisionsX; col++) {
  33624. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33625. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33626. positions.push(position.x, position.y, position.z);
  33627. normals.push(normal.x, normal.y, normal.z);
  33628. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33629. }
  33630. }
  33631. for (row = 0; row < subdivisionsY; row++) {
  33632. for (col = 0; col < subdivisionsX; col++) {
  33633. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33634. indices.push(col + 1 + row * (subdivisionsX + 1));
  33635. indices.push(col + row * (subdivisionsX + 1));
  33636. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33637. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33638. indices.push(col + row * (subdivisionsX + 1));
  33639. }
  33640. }
  33641. // Result
  33642. var vertexData = new VertexData();
  33643. vertexData.indices = indices;
  33644. vertexData.positions = positions;
  33645. vertexData.normals = normals;
  33646. vertexData.uvs = uvs;
  33647. return vertexData;
  33648. };
  33649. /**
  33650. * Creates the VertexData of the TiledGround.
  33651. */
  33652. VertexData.CreateTiledGround = function (options) {
  33653. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33654. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33655. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33656. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33657. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33658. var precision = options.precision || { w: 1, h: 1 };
  33659. var indices = new Array();
  33660. var positions = new Array();
  33661. var normals = new Array();
  33662. var uvs = new Array();
  33663. var row, col, tileRow, tileCol;
  33664. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33665. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33666. precision.w = (precision.w < 1) ? 1 : precision.w;
  33667. precision.h = (precision.h < 1) ? 1 : precision.h;
  33668. var tileSize = {
  33669. 'w': (xmax - xmin) / subdivisions.w,
  33670. 'h': (zmax - zmin) / subdivisions.h
  33671. };
  33672. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33673. // Indices
  33674. var base = positions.length / 3;
  33675. var rowLength = precision.w + 1;
  33676. for (row = 0; row < precision.h; row++) {
  33677. for (col = 0; col < precision.w; col++) {
  33678. var square = [
  33679. base + col + row * rowLength,
  33680. base + (col + 1) + row * rowLength,
  33681. base + (col + 1) + (row + 1) * rowLength,
  33682. base + col + (row + 1) * rowLength
  33683. ];
  33684. indices.push(square[1]);
  33685. indices.push(square[2]);
  33686. indices.push(square[3]);
  33687. indices.push(square[0]);
  33688. indices.push(square[1]);
  33689. indices.push(square[3]);
  33690. }
  33691. }
  33692. // Position, normals and uvs
  33693. var position = BABYLON.Vector3.Zero();
  33694. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33695. for (row = 0; row <= precision.h; row++) {
  33696. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33697. for (col = 0; col <= precision.w; col++) {
  33698. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33699. position.y = 0;
  33700. positions.push(position.x, position.y, position.z);
  33701. normals.push(normal.x, normal.y, normal.z);
  33702. uvs.push(col / precision.w, row / precision.h);
  33703. }
  33704. }
  33705. }
  33706. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33707. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33708. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33709. }
  33710. }
  33711. // Result
  33712. var vertexData = new VertexData();
  33713. vertexData.indices = indices;
  33714. vertexData.positions = positions;
  33715. vertexData.normals = normals;
  33716. vertexData.uvs = uvs;
  33717. return vertexData;
  33718. };
  33719. /**
  33720. * Creates the VertexData of the Ground designed from a heightmap.
  33721. */
  33722. VertexData.CreateGroundFromHeightMap = function (options) {
  33723. var indices = [];
  33724. var positions = [];
  33725. var normals = [];
  33726. var uvs = [];
  33727. var row, col;
  33728. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33729. // Vertices
  33730. for (row = 0; row <= options.subdivisions; row++) {
  33731. for (col = 0; col <= options.subdivisions; col++) {
  33732. 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));
  33733. // Compute height
  33734. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33735. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33736. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33737. var r = options.buffer[pos] / 255.0;
  33738. var g = options.buffer[pos + 1] / 255.0;
  33739. var b = options.buffer[pos + 2] / 255.0;
  33740. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33741. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33742. // Add vertex
  33743. positions.push(position.x, position.y, position.z);
  33744. normals.push(0, 0, 0);
  33745. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33746. }
  33747. }
  33748. // Indices
  33749. for (row = 0; row < options.subdivisions; row++) {
  33750. for (col = 0; col < options.subdivisions; col++) {
  33751. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33752. indices.push(col + 1 + row * (options.subdivisions + 1));
  33753. indices.push(col + row * (options.subdivisions + 1));
  33754. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33755. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33756. indices.push(col + row * (options.subdivisions + 1));
  33757. }
  33758. }
  33759. // Normals
  33760. VertexData.ComputeNormals(positions, indices, normals);
  33761. // Result
  33762. var vertexData = new VertexData();
  33763. vertexData.indices = indices;
  33764. vertexData.positions = positions;
  33765. vertexData.normals = normals;
  33766. vertexData.uvs = uvs;
  33767. return vertexData;
  33768. };
  33769. /**
  33770. * Creates the VertexData of the Plane.
  33771. */
  33772. VertexData.CreatePlane = function (options) {
  33773. var indices = [];
  33774. var positions = [];
  33775. var normals = [];
  33776. var uvs = [];
  33777. var width = options.width || options.size || 1;
  33778. var height = options.height || options.size || 1;
  33779. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33780. // Vertices
  33781. var halfWidth = width / 2.0;
  33782. var halfHeight = height / 2.0;
  33783. positions.push(-halfWidth, -halfHeight, 0);
  33784. normals.push(0, 0, -1.0);
  33785. uvs.push(0.0, 0.0);
  33786. positions.push(halfWidth, -halfHeight, 0);
  33787. normals.push(0, 0, -1.0);
  33788. uvs.push(1.0, 0.0);
  33789. positions.push(halfWidth, halfHeight, 0);
  33790. normals.push(0, 0, -1.0);
  33791. uvs.push(1.0, 1.0);
  33792. positions.push(-halfWidth, halfHeight, 0);
  33793. normals.push(0, 0, -1.0);
  33794. uvs.push(0.0, 1.0);
  33795. // Indices
  33796. indices.push(0);
  33797. indices.push(1);
  33798. indices.push(2);
  33799. indices.push(0);
  33800. indices.push(2);
  33801. indices.push(3);
  33802. // Sides
  33803. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33804. // Result
  33805. var vertexData = new VertexData();
  33806. vertexData.indices = indices;
  33807. vertexData.positions = positions;
  33808. vertexData.normals = normals;
  33809. vertexData.uvs = uvs;
  33810. return vertexData;
  33811. };
  33812. /**
  33813. * Creates the VertexData of the Disc or regular Polygon.
  33814. */
  33815. VertexData.CreateDisc = function (options) {
  33816. var positions = new Array();
  33817. var indices = new Array();
  33818. var normals = new Array();
  33819. var uvs = new Array();
  33820. var radius = options.radius || 0.5;
  33821. var tessellation = options.tessellation || 64;
  33822. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33823. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33824. // positions and uvs
  33825. positions.push(0, 0, 0); // disc center first
  33826. uvs.push(0.5, 0.5);
  33827. var theta = Math.PI * 2 * arc;
  33828. var step = theta / tessellation;
  33829. for (var a = 0; a < theta; a += step) {
  33830. var x = Math.cos(a);
  33831. var y = Math.sin(a);
  33832. var u = (x + 1) / 2;
  33833. var v = (1 - y) / 2;
  33834. positions.push(radius * x, radius * y, 0);
  33835. uvs.push(u, v);
  33836. }
  33837. if (arc === 1) {
  33838. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33839. uvs.push(uvs[2], uvs[3]);
  33840. }
  33841. //indices
  33842. var vertexNb = positions.length / 3;
  33843. for (var i = 1; i < vertexNb - 1; i++) {
  33844. indices.push(i + 1, 0, i);
  33845. }
  33846. // result
  33847. VertexData.ComputeNormals(positions, indices, normals);
  33848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33849. var vertexData = new VertexData();
  33850. vertexData.indices = indices;
  33851. vertexData.positions = positions;
  33852. vertexData.normals = normals;
  33853. vertexData.uvs = uvs;
  33854. return vertexData;
  33855. };
  33856. /**
  33857. * Re-creates the VertexData of the Polygon for sideOrientation.
  33858. */
  33859. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33860. var faceUV = fUV || new Array(3);
  33861. var faceColors = fColors;
  33862. var colors = [];
  33863. // default face colors and UV if undefined
  33864. for (var f = 0; f < 3; f++) {
  33865. if (faceUV[f] === undefined) {
  33866. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33867. }
  33868. if (faceColors && faceColors[f] === undefined) {
  33869. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33870. }
  33871. }
  33872. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33873. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33874. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33875. var indices = polygon.getIndices();
  33876. // set face colours and textures
  33877. var idx = 0;
  33878. var face = 0;
  33879. for (var index = 0; index < normals.length; index += 3) {
  33880. //Edge Face no. 1
  33881. if (Math.abs(normals[index + 1]) < 0.001) {
  33882. face = 1;
  33883. }
  33884. //Top Face no. 0
  33885. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33886. face = 0;
  33887. }
  33888. //Bottom Face no. 2
  33889. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33890. face = 2;
  33891. }
  33892. idx = index / 3;
  33893. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33894. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33895. if (faceColors) {
  33896. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33897. }
  33898. }
  33899. // sides
  33900. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33901. // Result
  33902. var vertexData = new VertexData();
  33903. vertexData.indices = indices;
  33904. vertexData.positions = positions;
  33905. vertexData.normals = normals;
  33906. vertexData.uvs = uvs;
  33907. if (faceColors) {
  33908. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33909. vertexData.colors = totalColors;
  33910. }
  33911. return vertexData;
  33912. };
  33913. /**
  33914. * Creates the VertexData of the IcoSphere.
  33915. */
  33916. VertexData.CreateIcoSphere = function (options) {
  33917. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33918. var radius = options.radius || 1;
  33919. var flat = (options.flat === undefined) ? true : options.flat;
  33920. var subdivisions = options.subdivisions || 4;
  33921. var radiusX = options.radiusX || radius;
  33922. var radiusY = options.radiusY || radius;
  33923. var radiusZ = options.radiusZ || radius;
  33924. var t = (1 + Math.sqrt(5)) / 2;
  33925. // 12 vertex x,y,z
  33926. var ico_vertices = [
  33927. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33928. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33929. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33930. ];
  33931. // index of 3 vertex makes a face of icopshere
  33932. var ico_indices = [
  33933. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33934. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33935. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33936. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33937. ];
  33938. // vertex for uv have aliased position, not for UV
  33939. var vertices_unalias_id = [
  33940. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33941. // vertex alias
  33942. 0,
  33943. 2,
  33944. 3,
  33945. 3,
  33946. 3,
  33947. 4,
  33948. 7,
  33949. 8,
  33950. 9,
  33951. 9,
  33952. 10,
  33953. 11 // 23: B + 12
  33954. ];
  33955. // uv as integer step (not pixels !)
  33956. var ico_vertexuv = [
  33957. 5, 1, 3, 1, 6, 4, 0, 0,
  33958. 5, 3, 4, 2, 2, 2, 4, 0,
  33959. 2, 0, 1, 1, 6, 0, 6, 2,
  33960. // vertex alias (for same vertex on different faces)
  33961. 0, 4,
  33962. 3, 3,
  33963. 4, 4,
  33964. 3, 1,
  33965. 4, 2,
  33966. 4, 4,
  33967. 0, 2,
  33968. 1, 1,
  33969. 2, 2,
  33970. 3, 3,
  33971. 1, 3,
  33972. 2, 4 // 23: B + 12
  33973. ];
  33974. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33975. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33976. // First island of uv mapping
  33977. // v = 4h 3+ 2
  33978. // v = 3h 9+ 4
  33979. // v = 2h 9+ 5 B
  33980. // v = 1h 9 1 0
  33981. // v = 0h 3 8 7 A
  33982. // u = 0 1 2 3 4 5 6 *a
  33983. // Second island of uv mapping
  33984. // v = 4h 0+ B+ 4+
  33985. // v = 3h A+ 2+
  33986. // v = 2h 7+ 6 3+
  33987. // v = 1h 8+ 3+
  33988. // v = 0h
  33989. // u = 0 1 2 3 4 5 6 *a
  33990. // Face layout on texture UV mapping
  33991. // ============
  33992. // \ 4 /\ 16 / ======
  33993. // \ / \ / /\ 11 /
  33994. // \/ 7 \/ / \ /
  33995. // ======= / 10 \/
  33996. // /\ 17 /\ =======
  33997. // / \ / \ \ 15 /\
  33998. // / 8 \/ 12 \ \ / \
  33999. // ============ \/ 6 \
  34000. // \ 18 /\ ============
  34001. // \ / \ \ 5 /\ 0 /
  34002. // \/ 13 \ \ / \ /
  34003. // ======= \/ 1 \/
  34004. // =============
  34005. // /\ 19 /\ 2 /\
  34006. // / \ / \ / \
  34007. // / 14 \/ 9 \/ 3 \
  34008. // ===================
  34009. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34010. var ustep = 138 / 1024;
  34011. var vstep = 239 / 1024;
  34012. var uoffset = 60 / 1024;
  34013. var voffset = 26 / 1024;
  34014. // Second island should have margin, not to touch the first island
  34015. // avoid any borderline artefact in pixel rounding
  34016. var island_u_offset = -40 / 1024;
  34017. var island_v_offset = +20 / 1024;
  34018. // face is either island 0 or 1 :
  34019. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34020. var island = [
  34021. 0, 0, 0, 0, 1,
  34022. 0, 0, 1, 1, 0,
  34023. 0, 0, 1, 1, 0,
  34024. 0, 1, 1, 1, 0 // 15 - 19
  34025. ];
  34026. var indices = new Array();
  34027. var positions = new Array();
  34028. var normals = new Array();
  34029. var uvs = new Array();
  34030. var current_indice = 0;
  34031. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34032. var face_vertex_pos = new Array(3);
  34033. var face_vertex_uv = new Array(3);
  34034. var v012;
  34035. for (v012 = 0; v012 < 3; v012++) {
  34036. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34037. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34038. }
  34039. // create all with normals
  34040. for (var face = 0; face < 20; face++) {
  34041. // 3 vertex per face
  34042. for (v012 = 0; v012 < 3; v012++) {
  34043. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34044. var v_id = ico_indices[3 * face + v012];
  34045. // vertex have 3D position (x,y,z)
  34046. 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]);
  34047. // Normalize to get normal, then scale to radius
  34048. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34049. // uv Coordinates from vertex ID
  34050. 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);
  34051. }
  34052. // Subdivide the face (interpolate pos, norm, uv)
  34053. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34054. // - norm is linear interpolation of vertex corner normal
  34055. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34056. // - uv is linear interpolation
  34057. //
  34058. // Topology is as below for sub-divide by 2
  34059. // vertex shown as v0,v1,v2
  34060. // interp index is i1 to progress in range [v0,v1[
  34061. // interp index is i2 to progress in range [v0,v2[
  34062. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34063. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34064. //
  34065. //
  34066. // i2 v2
  34067. // ^ ^
  34068. // / / \
  34069. // / / \
  34070. // / / \
  34071. // / / (0,1) \
  34072. // / #---------\
  34073. // / / \ (0,0)'/ \
  34074. // / / \ / \
  34075. // / / \ / \
  34076. // / / (0,0) \ / (1,0) \
  34077. // / #---------#---------\
  34078. // v0 v1
  34079. //
  34080. // --------------------> i1
  34081. //
  34082. // interp of (i1,i2):
  34083. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34084. // along i1 : lerp(x0,x1, i1/(S-i2))
  34085. //
  34086. // centroid of triangle is needed to get help normal computation
  34087. // (c1,c2) are used for centroid location
  34088. var interp_vertex = function (i1, i2, c1, c2) {
  34089. // vertex is interpolated from
  34090. // - face_vertex_pos[0..2]
  34091. // - face_vertex_uv[0..2]
  34092. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34093. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34094. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34095. pos_interp.normalize();
  34096. var vertex_normal;
  34097. if (flat) {
  34098. // in flat mode, recalculate normal as face centroid normal
  34099. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34100. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34101. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34102. }
  34103. else {
  34104. // in smooth mode, recalculate normal from each single vertex position
  34105. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34106. }
  34107. // Vertex normal need correction due to X,Y,Z radius scaling
  34108. vertex_normal.x /= radiusX;
  34109. vertex_normal.y /= radiusY;
  34110. vertex_normal.z /= radiusZ;
  34111. vertex_normal.normalize();
  34112. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34113. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34114. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34115. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34116. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34117. uvs.push(uv_interp.x, uv_interp.y);
  34118. // push each vertex has member of a face
  34119. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34120. indices.push(current_indice);
  34121. current_indice++;
  34122. };
  34123. for (var i2 = 0; i2 < subdivisions; i2++) {
  34124. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34125. // face : (i1,i2) for /\ :
  34126. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34127. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34128. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34129. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34130. if (i1 + i2 + 1 < subdivisions) {
  34131. // face : (i1,i2)' for \/ :
  34132. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34133. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34134. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34135. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34136. }
  34137. }
  34138. }
  34139. }
  34140. // Sides
  34141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34142. // Result
  34143. var vertexData = new VertexData();
  34144. vertexData.indices = indices;
  34145. vertexData.positions = positions;
  34146. vertexData.normals = normals;
  34147. vertexData.uvs = uvs;
  34148. return vertexData;
  34149. };
  34150. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34151. /**
  34152. * Creates the VertexData of the Polyhedron.
  34153. */
  34154. VertexData.CreatePolyhedron = function (options) {
  34155. // provided polyhedron types :
  34156. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34157. // 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)
  34158. var polyhedra = [];
  34159. 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]] };
  34160. 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]] };
  34161. polyhedra[2] = {
  34162. 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]],
  34163. 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]]
  34164. };
  34165. polyhedra[3] = {
  34166. 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]],
  34167. 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]]
  34168. };
  34169. polyhedra[4] = {
  34170. 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]],
  34171. 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]]
  34172. };
  34173. 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]] };
  34174. 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]] };
  34175. 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]] };
  34176. 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]] };
  34177. 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]] };
  34178. 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]] };
  34179. 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]] };
  34180. 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]] };
  34181. 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]] };
  34182. polyhedra[14] = {
  34183. 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]],
  34184. 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]]
  34185. };
  34186. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34187. var size = options.size;
  34188. var sizeX = options.sizeX || size || 1;
  34189. var sizeY = options.sizeY || size || 1;
  34190. var sizeZ = options.sizeZ || size || 1;
  34191. var data = options.custom || polyhedra[type];
  34192. var nbfaces = data.face.length;
  34193. var faceUV = options.faceUV || new Array(nbfaces);
  34194. var faceColors = options.faceColors;
  34195. var flat = (options.flat === undefined) ? true : options.flat;
  34196. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34197. var positions = new Array();
  34198. var indices = new Array();
  34199. var normals = new Array();
  34200. var uvs = new Array();
  34201. var colors = new Array();
  34202. var index = 0;
  34203. var faceIdx = 0; // face cursor in the array "indexes"
  34204. var indexes = new Array();
  34205. var i = 0;
  34206. var f = 0;
  34207. var u, v, ang, x, y, tmp;
  34208. // default face colors and UV if undefined
  34209. if (flat) {
  34210. for (f = 0; f < nbfaces; f++) {
  34211. if (faceColors && faceColors[f] === undefined) {
  34212. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34213. }
  34214. if (faceUV && faceUV[f] === undefined) {
  34215. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34216. }
  34217. }
  34218. }
  34219. if (!flat) {
  34220. for (i = 0; i < data.vertex.length; i++) {
  34221. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34222. uvs.push(0, 0);
  34223. }
  34224. for (f = 0; f < nbfaces; f++) {
  34225. for (i = 0; i < data.face[f].length - 2; i++) {
  34226. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34227. }
  34228. }
  34229. }
  34230. else {
  34231. for (f = 0; f < nbfaces; f++) {
  34232. var fl = data.face[f].length; // number of vertices of the current face
  34233. ang = 2 * Math.PI / fl;
  34234. x = 0.5 * Math.tan(ang / 2);
  34235. y = 0.5;
  34236. // positions, uvs, colors
  34237. for (i = 0; i < fl; i++) {
  34238. // positions
  34239. 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);
  34240. indexes.push(index);
  34241. index++;
  34242. // uvs
  34243. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34244. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34245. uvs.push(u, v);
  34246. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34247. y = x * Math.sin(ang) + y * Math.cos(ang);
  34248. x = tmp;
  34249. // colors
  34250. if (faceColors) {
  34251. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34252. }
  34253. }
  34254. // indices from indexes
  34255. for (i = 0; i < fl - 2; i++) {
  34256. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34257. }
  34258. faceIdx += fl;
  34259. }
  34260. }
  34261. VertexData.ComputeNormals(positions, indices, normals);
  34262. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34263. var vertexData = new VertexData();
  34264. vertexData.positions = positions;
  34265. vertexData.indices = indices;
  34266. vertexData.normals = normals;
  34267. vertexData.uvs = uvs;
  34268. if (faceColors && flat) {
  34269. vertexData.colors = colors;
  34270. }
  34271. return vertexData;
  34272. };
  34273. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34274. /**
  34275. * Creates the VertexData of the Torus Knot.
  34276. */
  34277. VertexData.CreateTorusKnot = function (options) {
  34278. var indices = new Array();
  34279. var positions = new Array();
  34280. var normals = new Array();
  34281. var uvs = new Array();
  34282. var radius = options.radius || 2;
  34283. var tube = options.tube || 0.5;
  34284. var radialSegments = options.radialSegments || 32;
  34285. var tubularSegments = options.tubularSegments || 32;
  34286. var p = options.p || 2;
  34287. var q = options.q || 3;
  34288. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34289. // Helper
  34290. var getPos = function (angle) {
  34291. var cu = Math.cos(angle);
  34292. var su = Math.sin(angle);
  34293. var quOverP = q / p * angle;
  34294. var cs = Math.cos(quOverP);
  34295. var tx = radius * (2 + cs) * 0.5 * cu;
  34296. var ty = radius * (2 + cs) * su * 0.5;
  34297. var tz = radius * Math.sin(quOverP) * 0.5;
  34298. return new BABYLON.Vector3(tx, ty, tz);
  34299. };
  34300. // Vertices
  34301. var i;
  34302. var j;
  34303. for (i = 0; i <= radialSegments; i++) {
  34304. var modI = i % radialSegments;
  34305. var u = modI / radialSegments * 2 * p * Math.PI;
  34306. var p1 = getPos(u);
  34307. var p2 = getPos(u + 0.01);
  34308. var tang = p2.subtract(p1);
  34309. var n = p2.add(p1);
  34310. var bitan = BABYLON.Vector3.Cross(tang, n);
  34311. n = BABYLON.Vector3.Cross(bitan, tang);
  34312. bitan.normalize();
  34313. n.normalize();
  34314. for (j = 0; j < tubularSegments; j++) {
  34315. var modJ = j % tubularSegments;
  34316. var v = modJ / tubularSegments * 2 * Math.PI;
  34317. var cx = -tube * Math.cos(v);
  34318. var cy = tube * Math.sin(v);
  34319. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34320. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34321. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34322. uvs.push(i / radialSegments);
  34323. uvs.push(j / tubularSegments);
  34324. }
  34325. }
  34326. for (i = 0; i < radialSegments; i++) {
  34327. for (j = 0; j < tubularSegments; j++) {
  34328. var jNext = (j + 1) % tubularSegments;
  34329. var a = i * tubularSegments + j;
  34330. var b = (i + 1) * tubularSegments + j;
  34331. var c = (i + 1) * tubularSegments + jNext;
  34332. var d = i * tubularSegments + jNext;
  34333. indices.push(d);
  34334. indices.push(b);
  34335. indices.push(a);
  34336. indices.push(d);
  34337. indices.push(c);
  34338. indices.push(b);
  34339. }
  34340. }
  34341. // Normals
  34342. VertexData.ComputeNormals(positions, indices, normals);
  34343. // Sides
  34344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34345. // Result
  34346. var vertexData = new VertexData();
  34347. vertexData.indices = indices;
  34348. vertexData.positions = positions;
  34349. vertexData.normals = normals;
  34350. vertexData.uvs = uvs;
  34351. return vertexData;
  34352. };
  34353. // Tools
  34354. /**
  34355. * @param {any} - positions (number[] or Float32Array)
  34356. * @param {any} - indices (number[] or Uint16Array)
  34357. * @param {any} - normals (number[] or Float32Array)
  34358. * options (optional) :
  34359. * facetPositions : optional array of facet positions (vector3)
  34360. * facetNormals : optional array of facet normals (vector3)
  34361. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34362. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34363. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34364. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34365. * bInfo : optional bounding info, required for facetPartitioning computation
  34366. * useRightHandedSystem: optional boolean to for right handed system computation
  34367. * depthSort : optional boolean to enable the facet depth sort computation
  34368. * distanceTo : optional Vector3 to compute the facet depth from this location
  34369. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34370. */
  34371. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34372. // temporary scalar variables
  34373. var index = 0; // facet index
  34374. var p1p2x = 0.0; // p1p2 vector x coordinate
  34375. var p1p2y = 0.0; // p1p2 vector y coordinate
  34376. var p1p2z = 0.0; // p1p2 vector z coordinate
  34377. var p3p2x = 0.0; // p3p2 vector x coordinate
  34378. var p3p2y = 0.0; // p3p2 vector y coordinate
  34379. var p3p2z = 0.0; // p3p2 vector z coordinate
  34380. var faceNormalx = 0.0; // facet normal x coordinate
  34381. var faceNormaly = 0.0; // facet normal y coordinate
  34382. var faceNormalz = 0.0; // facet normal z coordinate
  34383. var length = 0.0; // facet normal length before normalization
  34384. var v1x = 0; // vector1 x index in the positions array
  34385. var v1y = 0; // vector1 y index in the positions array
  34386. var v1z = 0; // vector1 z index in the positions array
  34387. var v2x = 0; // vector2 x index in the positions array
  34388. var v2y = 0; // vector2 y index in the positions array
  34389. var v2z = 0; // vector2 z index in the positions array
  34390. var v3x = 0; // vector3 x index in the positions array
  34391. var v3y = 0; // vector3 y index in the positions array
  34392. var v3z = 0; // vector3 z index in the positions array
  34393. var computeFacetNormals = false;
  34394. var computeFacetPositions = false;
  34395. var computeFacetPartitioning = false;
  34396. var computeDepthSort = false;
  34397. var faceNormalSign = 1;
  34398. var ratio = 0;
  34399. var distanceTo = null;
  34400. if (options) {
  34401. computeFacetNormals = (options.facetNormals) ? true : false;
  34402. computeFacetPositions = (options.facetPositions) ? true : false;
  34403. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34404. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34405. ratio = options.ratio || 0;
  34406. computeDepthSort = (options.depthSort) ? true : false;
  34407. distanceTo = (options.distanceTo);
  34408. if (computeDepthSort) {
  34409. if (distanceTo === undefined) {
  34410. distanceTo = BABYLON.Vector3.Zero();
  34411. }
  34412. var depthSortedFacets = options.depthSortedFacets;
  34413. }
  34414. }
  34415. // facetPartitioning reinit if needed
  34416. var xSubRatio = 0;
  34417. var ySubRatio = 0;
  34418. var zSubRatio = 0;
  34419. var subSq = 0;
  34420. if (computeFacetPartitioning && options && options.bbSize) {
  34421. var ox = 0; // X partitioning index for facet position
  34422. var oy = 0; // Y partinioning index for facet position
  34423. var oz = 0; // Z partinioning index for facet position
  34424. var b1x = 0; // X partitioning index for facet v1 vertex
  34425. var b1y = 0; // Y partitioning index for facet v1 vertex
  34426. var b1z = 0; // z partitioning index for facet v1 vertex
  34427. var b2x = 0; // X partitioning index for facet v2 vertex
  34428. var b2y = 0; // Y partitioning index for facet v2 vertex
  34429. var b2z = 0; // Z partitioning index for facet v2 vertex
  34430. var b3x = 0; // X partitioning index for facet v3 vertex
  34431. var b3y = 0; // Y partitioning index for facet v3 vertex
  34432. var b3z = 0; // Z partitioning index for facet v3 vertex
  34433. var block_idx_o = 0; // facet barycenter block index
  34434. var block_idx_v1 = 0; // v1 vertex block index
  34435. var block_idx_v2 = 0; // v2 vertex block index
  34436. var block_idx_v3 = 0; // v3 vertex block index
  34437. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34438. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34439. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34440. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34441. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34442. subSq = options.subDiv.max * options.subDiv.max;
  34443. options.facetPartitioning.length = 0;
  34444. }
  34445. // reset the normals
  34446. for (index = 0; index < positions.length; index++) {
  34447. normals[index] = 0.0;
  34448. }
  34449. // Loop : 1 indice triplet = 1 facet
  34450. var nbFaces = (indices.length / 3) | 0;
  34451. for (index = 0; index < nbFaces; index++) {
  34452. // get the indexes of the coordinates of each vertex of the facet
  34453. v1x = indices[index * 3] * 3;
  34454. v1y = v1x + 1;
  34455. v1z = v1x + 2;
  34456. v2x = indices[index * 3 + 1] * 3;
  34457. v2y = v2x + 1;
  34458. v2z = v2x + 2;
  34459. v3x = indices[index * 3 + 2] * 3;
  34460. v3y = v3x + 1;
  34461. v3z = v3x + 2;
  34462. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34463. p1p2y = positions[v1y] - positions[v2y];
  34464. p1p2z = positions[v1z] - positions[v2z];
  34465. p3p2x = positions[v3x] - positions[v2x];
  34466. p3p2y = positions[v3y] - positions[v2y];
  34467. p3p2z = positions[v3z] - positions[v2z];
  34468. // compute the face normal with the cross product
  34469. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34470. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34471. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34472. // normalize this normal and store it in the array facetData
  34473. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34474. length = (length === 0) ? 1.0 : length;
  34475. faceNormalx /= length;
  34476. faceNormaly /= length;
  34477. faceNormalz /= length;
  34478. if (computeFacetNormals && options) {
  34479. options.facetNormals[index].x = faceNormalx;
  34480. options.facetNormals[index].y = faceNormaly;
  34481. options.facetNormals[index].z = faceNormalz;
  34482. }
  34483. if (computeFacetPositions && options) {
  34484. // compute and the facet barycenter coordinates in the array facetPositions
  34485. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34486. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34487. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34488. }
  34489. if (computeFacetPartitioning && options) {
  34490. // store the facet indexes in arrays in the main facetPartitioning array :
  34491. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34492. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34493. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34494. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34495. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34496. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34497. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34498. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34499. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34500. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34501. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34502. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34503. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34504. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34505. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34506. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34507. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34508. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34509. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34510. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34511. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34512. // push each facet index in each block containing the vertex
  34513. options.facetPartitioning[block_idx_v1].push(index);
  34514. if (block_idx_v2 != block_idx_v1) {
  34515. options.facetPartitioning[block_idx_v2].push(index);
  34516. }
  34517. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34518. options.facetPartitioning[block_idx_v3].push(index);
  34519. }
  34520. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34521. options.facetPartitioning[block_idx_o].push(index);
  34522. }
  34523. }
  34524. if (computeDepthSort && options && options.facetPositions) {
  34525. var dsf = depthSortedFacets[index];
  34526. dsf.ind = index * 3;
  34527. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34528. }
  34529. // compute the normals anyway
  34530. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34531. normals[v1y] += faceNormaly;
  34532. normals[v1z] += faceNormalz;
  34533. normals[v2x] += faceNormalx;
  34534. normals[v2y] += faceNormaly;
  34535. normals[v2z] += faceNormalz;
  34536. normals[v3x] += faceNormalx;
  34537. normals[v3y] += faceNormaly;
  34538. normals[v3z] += faceNormalz;
  34539. }
  34540. // last normalization of each normal
  34541. for (index = 0; index < normals.length / 3; index++) {
  34542. faceNormalx = normals[index * 3];
  34543. faceNormaly = normals[index * 3 + 1];
  34544. faceNormalz = normals[index * 3 + 2];
  34545. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34546. length = (length === 0) ? 1.0 : length;
  34547. faceNormalx /= length;
  34548. faceNormaly /= length;
  34549. faceNormalz /= length;
  34550. normals[index * 3] = faceNormalx;
  34551. normals[index * 3 + 1] = faceNormaly;
  34552. normals[index * 3 + 2] = faceNormalz;
  34553. }
  34554. };
  34555. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34556. var li = indices.length;
  34557. var ln = normals.length;
  34558. var i;
  34559. var n;
  34560. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34561. switch (sideOrientation) {
  34562. case BABYLON.Mesh.FRONTSIDE:
  34563. // nothing changed
  34564. break;
  34565. case BABYLON.Mesh.BACKSIDE:
  34566. var tmp;
  34567. // indices
  34568. for (i = 0; i < li; i += 3) {
  34569. tmp = indices[i];
  34570. indices[i] = indices[i + 2];
  34571. indices[i + 2] = tmp;
  34572. }
  34573. // normals
  34574. for (n = 0; n < ln; n++) {
  34575. normals[n] = -normals[n];
  34576. }
  34577. break;
  34578. case BABYLON.Mesh.DOUBLESIDE:
  34579. // positions
  34580. var lp = positions.length;
  34581. var l = lp / 3;
  34582. for (var p = 0; p < lp; p++) {
  34583. positions[lp + p] = positions[p];
  34584. }
  34585. // indices
  34586. for (i = 0; i < li; i += 3) {
  34587. indices[i + li] = indices[i + 2] + l;
  34588. indices[i + 1 + li] = indices[i + 1] + l;
  34589. indices[i + 2 + li] = indices[i] + l;
  34590. }
  34591. // normals
  34592. for (n = 0; n < ln; n++) {
  34593. normals[ln + n] = -normals[n];
  34594. }
  34595. // uvs
  34596. var lu = uvs.length;
  34597. var u = 0;
  34598. for (u = 0; u < lu; u++) {
  34599. uvs[u + lu] = uvs[u];
  34600. }
  34601. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34602. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34603. u = 0;
  34604. for (i = 0; i < lu / 2; i++) {
  34605. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34606. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34607. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34608. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34609. u += 2;
  34610. }
  34611. break;
  34612. }
  34613. };
  34614. /**
  34615. * Creates a new VertexData from the imported parameters.
  34616. */
  34617. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34618. var vertexData = new VertexData();
  34619. // positions
  34620. var positions = parsedVertexData.positions;
  34621. if (positions) {
  34622. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34623. }
  34624. // normals
  34625. var normals = parsedVertexData.normals;
  34626. if (normals) {
  34627. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34628. }
  34629. // tangents
  34630. var tangents = parsedVertexData.tangents;
  34631. if (tangents) {
  34632. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34633. }
  34634. // uvs
  34635. var uvs = parsedVertexData.uvs;
  34636. if (uvs) {
  34637. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34638. }
  34639. // uv2s
  34640. var uv2s = parsedVertexData.uv2s;
  34641. if (uv2s) {
  34642. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34643. }
  34644. // uv3s
  34645. var uv3s = parsedVertexData.uv3s;
  34646. if (uv3s) {
  34647. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34648. }
  34649. // uv4s
  34650. var uv4s = parsedVertexData.uv4s;
  34651. if (uv4s) {
  34652. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34653. }
  34654. // uv5s
  34655. var uv5s = parsedVertexData.uv5s;
  34656. if (uv5s) {
  34657. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34658. }
  34659. // uv6s
  34660. var uv6s = parsedVertexData.uv6s;
  34661. if (uv6s) {
  34662. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34663. }
  34664. // colors
  34665. var colors = parsedVertexData.colors;
  34666. if (colors) {
  34667. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34668. }
  34669. // matricesIndices
  34670. var matricesIndices = parsedVertexData.matricesIndices;
  34671. if (matricesIndices) {
  34672. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34673. }
  34674. // matricesWeights
  34675. var matricesWeights = parsedVertexData.matricesWeights;
  34676. if (matricesWeights) {
  34677. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34678. }
  34679. // indices
  34680. var indices = parsedVertexData.indices;
  34681. if (indices) {
  34682. vertexData.indices = indices;
  34683. }
  34684. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34685. };
  34686. return VertexData;
  34687. }());
  34688. BABYLON.VertexData = VertexData;
  34689. })(BABYLON || (BABYLON = {}));
  34690. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34691. var BABYLON;
  34692. (function (BABYLON) {
  34693. /**
  34694. * Class used to store geometry data (vertex buffers + index buffer)
  34695. */
  34696. var Geometry = /** @class */ (function () {
  34697. /**
  34698. * Creates a new geometry
  34699. * @param id defines the unique ID
  34700. * @param scene defines the hosting scene
  34701. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34702. * @param updatable defines if geometry must be updatable (false by default)
  34703. * @param mesh defines the mesh that will be associated with the geometry
  34704. */
  34705. function Geometry(id, scene, vertexData, updatable, mesh) {
  34706. if (updatable === void 0) { updatable = false; }
  34707. if (mesh === void 0) { mesh = null; }
  34708. /**
  34709. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34710. */
  34711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34712. this._totalVertices = 0;
  34713. this._isDisposed = false;
  34714. this._indexBufferIsUpdatable = false;
  34715. this.id = id;
  34716. this._engine = scene.getEngine();
  34717. this._meshes = [];
  34718. this._scene = scene;
  34719. //Init vertex buffer cache
  34720. this._vertexBuffers = {};
  34721. this._indices = [];
  34722. this._updatable = updatable;
  34723. // vertexData
  34724. if (vertexData) {
  34725. this.setAllVerticesData(vertexData, updatable);
  34726. }
  34727. else {
  34728. this._totalVertices = 0;
  34729. this._indices = [];
  34730. }
  34731. if (this._engine.getCaps().vertexArrayObject) {
  34732. this._vertexArrayObjects = {};
  34733. }
  34734. // applyToMesh
  34735. if (mesh) {
  34736. if (mesh.getClassName() === "LinesMesh") {
  34737. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34738. this.updateExtend();
  34739. }
  34740. this.applyToMesh(mesh);
  34741. mesh.computeWorldMatrix(true);
  34742. }
  34743. }
  34744. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34745. /**
  34746. * 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
  34747. */
  34748. get: function () {
  34749. return this._boundingBias;
  34750. },
  34751. /**
  34752. * 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
  34753. */
  34754. set: function (value) {
  34755. if (this._boundingBias && this._boundingBias.equals(value)) {
  34756. return;
  34757. }
  34758. this._boundingBias = value.clone();
  34759. this.updateBoundingInfo(true, null);
  34760. },
  34761. enumerable: true,
  34762. configurable: true
  34763. });
  34764. /**
  34765. * Static function used to attach a new empty geometry to a mesh
  34766. * @param mesh defines the mesh to attach the geometry to
  34767. * @returns the new {BABYLON.Geometry}
  34768. */
  34769. Geometry.CreateGeometryForMesh = function (mesh) {
  34770. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34771. geometry.applyToMesh(mesh);
  34772. return geometry;
  34773. };
  34774. Object.defineProperty(Geometry.prototype, "extend", {
  34775. /**
  34776. * Gets the current extend of the geometry
  34777. */
  34778. get: function () {
  34779. return this._extend;
  34780. },
  34781. enumerable: true,
  34782. configurable: true
  34783. });
  34784. /**
  34785. * Gets the hosting scene
  34786. * @returns the hosting {BABYLON.Scene}
  34787. */
  34788. Geometry.prototype.getScene = function () {
  34789. return this._scene;
  34790. };
  34791. /**
  34792. * Gets the hosting engine
  34793. * @returns the hosting {BABYLON.Engine}
  34794. */
  34795. Geometry.prototype.getEngine = function () {
  34796. return this._engine;
  34797. };
  34798. /**
  34799. * Defines if the geometry is ready to use
  34800. * @returns true if the geometry is ready to be used
  34801. */
  34802. Geometry.prototype.isReady = function () {
  34803. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34804. };
  34805. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34806. /**
  34807. * Gets a value indicating that the geometry should not be serialized
  34808. */
  34809. get: function () {
  34810. for (var index = 0; index < this._meshes.length; index++) {
  34811. if (!this._meshes[index].doNotSerialize) {
  34812. return false;
  34813. }
  34814. }
  34815. return true;
  34816. },
  34817. enumerable: true,
  34818. configurable: true
  34819. });
  34820. /** @ignore */
  34821. Geometry.prototype._rebuild = function () {
  34822. if (this._vertexArrayObjects) {
  34823. this._vertexArrayObjects = {};
  34824. }
  34825. // Index buffer
  34826. if (this._meshes.length !== 0 && this._indices) {
  34827. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34828. }
  34829. // Vertex buffers
  34830. for (var key in this._vertexBuffers) {
  34831. var vertexBuffer = this._vertexBuffers[key];
  34832. vertexBuffer._rebuild();
  34833. }
  34834. };
  34835. /**
  34836. * Affects all gemetry data in one call
  34837. * @param vertexData defines the geometry data
  34838. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34839. */
  34840. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34841. vertexData.applyToGeometry(this, updatable);
  34842. this.notifyUpdate();
  34843. };
  34844. /**
  34845. * Set specific vertex data
  34846. * @param kind defines the data kind (Position, normal, etc...)
  34847. * @param data defines the vertex data to use
  34848. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34849. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34850. */
  34851. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34852. if (updatable === void 0) { updatable = false; }
  34853. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34854. this.setVerticesBuffer(buffer);
  34855. };
  34856. /**
  34857. * Removes a specific vertex data
  34858. * @param kind defines the data kind (Position, normal, etc...)
  34859. */
  34860. Geometry.prototype.removeVerticesData = function (kind) {
  34861. if (this._vertexBuffers[kind]) {
  34862. this._vertexBuffers[kind].dispose();
  34863. delete this._vertexBuffers[kind];
  34864. }
  34865. };
  34866. /**
  34867. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34868. * @param buffer defines the vertex buffer to use
  34869. */
  34870. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34871. var kind = buffer.getKind();
  34872. if (this._vertexBuffers[kind]) {
  34873. this._vertexBuffers[kind].dispose();
  34874. }
  34875. this._vertexBuffers[kind] = buffer;
  34876. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34877. var data = buffer.getData();
  34878. var stride = buffer.getStrideSize();
  34879. this._totalVertices = data.length / stride;
  34880. this.updateExtend(data, stride);
  34881. this._resetPointsArrayCache();
  34882. var meshes = this._meshes;
  34883. var numOfMeshes = meshes.length;
  34884. for (var index = 0; index < numOfMeshes; index++) {
  34885. var mesh = meshes[index];
  34886. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34887. mesh._createGlobalSubMesh(false);
  34888. mesh.computeWorldMatrix(true);
  34889. }
  34890. }
  34891. this.notifyUpdate(kind);
  34892. if (this._vertexArrayObjects) {
  34893. this._disposeVertexArrayObjects();
  34894. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34895. }
  34896. };
  34897. /**
  34898. * Update a specific vertex buffer
  34899. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34900. * It will do nothing if the buffer is not updatable
  34901. * @param kind defines the data kind (Position, normal, etc...)
  34902. * @param data defines the data to use
  34903. * @param offset defines the offset in the target buffer where to store the data
  34904. */
  34905. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34906. var vertexBuffer = this.getVertexBuffer(kind);
  34907. if (!vertexBuffer) {
  34908. return;
  34909. }
  34910. vertexBuffer.updateDirectly(data, offset);
  34911. this.notifyUpdate(kind);
  34912. };
  34913. /**
  34914. * Update a specific vertex buffer
  34915. * This function will create a new buffer if the current one is not updatable
  34916. * @param kind defines the data kind (Position, normal, etc...)
  34917. * @param data defines the data to use
  34918. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34919. */
  34920. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34921. if (updateExtends === void 0) { updateExtends = false; }
  34922. var vertexBuffer = this.getVertexBuffer(kind);
  34923. if (!vertexBuffer) {
  34924. return;
  34925. }
  34926. vertexBuffer.update(data);
  34927. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34928. var stride = vertexBuffer.getStrideSize();
  34929. this._totalVertices = data.length / stride;
  34930. this.updateBoundingInfo(updateExtends, data);
  34931. }
  34932. this.notifyUpdate(kind);
  34933. };
  34934. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34935. if (updateExtends) {
  34936. this.updateExtend(data);
  34937. }
  34938. var meshes = this._meshes;
  34939. var numOfMeshes = meshes.length;
  34940. this._resetPointsArrayCache();
  34941. for (var index = 0; index < numOfMeshes; index++) {
  34942. var mesh = meshes[index];
  34943. if (updateExtends) {
  34944. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34945. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34946. var subMesh = mesh.subMeshes[subIndex];
  34947. subMesh.refreshBoundingInfo();
  34948. }
  34949. }
  34950. }
  34951. };
  34952. /** @ignore */
  34953. Geometry.prototype._bind = function (effect, indexToBind) {
  34954. if (!effect) {
  34955. return;
  34956. }
  34957. if (indexToBind === undefined) {
  34958. indexToBind = this._indexBuffer;
  34959. }
  34960. var vbs = this.getVertexBuffers();
  34961. if (!vbs) {
  34962. return;
  34963. }
  34964. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34965. this._engine.bindBuffers(vbs, indexToBind, effect);
  34966. return;
  34967. }
  34968. // Using VAO
  34969. if (!this._vertexArrayObjects[effect.key]) {
  34970. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34971. }
  34972. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34973. };
  34974. /**
  34975. * Gets total number of vertices
  34976. * @returns the total number of vertices
  34977. */
  34978. Geometry.prototype.getTotalVertices = function () {
  34979. if (!this.isReady()) {
  34980. return 0;
  34981. }
  34982. return this._totalVertices;
  34983. };
  34984. /**
  34985. * Gets a specific vertex data attached to this geometry
  34986. * @param kind defines the data kind (Position, normal, etc...)
  34987. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34988. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34989. * @returns a float array containing vertex data
  34990. */
  34991. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34992. var vertexBuffer = this.getVertexBuffer(kind);
  34993. if (!vertexBuffer) {
  34994. return null;
  34995. }
  34996. var orig = vertexBuffer.getData();
  34997. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34998. return orig;
  34999. }
  35000. else {
  35001. var len = orig.length;
  35002. var copy = [];
  35003. for (var i = 0; i < len; i++) {
  35004. copy.push(orig[i]);
  35005. }
  35006. return copy;
  35007. }
  35008. };
  35009. /**
  35010. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35011. * @param kind defines the data kind (Position, normal, etc...)
  35012. * @returns true if the vertex buffer with the specified kind is updatable
  35013. */
  35014. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35015. var vb = this._vertexBuffers[kind];
  35016. if (!vb) {
  35017. return false;
  35018. }
  35019. return vb.isUpdatable();
  35020. };
  35021. /**
  35022. * Gets a specific vertex buffer
  35023. * @param kind defines the data kind (Position, normal, etc...)
  35024. * @returns a {BABYLON.VertexBuffer}
  35025. */
  35026. Geometry.prototype.getVertexBuffer = function (kind) {
  35027. if (!this.isReady()) {
  35028. return null;
  35029. }
  35030. return this._vertexBuffers[kind];
  35031. };
  35032. /**
  35033. * Returns all vertex buffers
  35034. * @return an object holding all vertex buffers indexed by kind
  35035. */
  35036. Geometry.prototype.getVertexBuffers = function () {
  35037. if (!this.isReady()) {
  35038. return null;
  35039. }
  35040. return this._vertexBuffers;
  35041. };
  35042. /**
  35043. * Gets a boolean indicating if specific vertex buffer is present
  35044. * @param kind defines the data kind (Position, normal, etc...)
  35045. * @returns true if data is present
  35046. */
  35047. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35048. if (!this._vertexBuffers) {
  35049. if (this._delayInfo) {
  35050. return this._delayInfo.indexOf(kind) !== -1;
  35051. }
  35052. return false;
  35053. }
  35054. return this._vertexBuffers[kind] !== undefined;
  35055. };
  35056. /**
  35057. * Gets a list of all attached data kinds (Position, normal, etc...)
  35058. * @returns a list of string containing all kinds
  35059. */
  35060. Geometry.prototype.getVerticesDataKinds = function () {
  35061. var result = [];
  35062. var kind;
  35063. if (!this._vertexBuffers && this._delayInfo) {
  35064. for (kind in this._delayInfo) {
  35065. result.push(kind);
  35066. }
  35067. }
  35068. else {
  35069. for (kind in this._vertexBuffers) {
  35070. result.push(kind);
  35071. }
  35072. }
  35073. return result;
  35074. };
  35075. /**
  35076. * Update index buffer
  35077. * @param indices defines the indices to store in the index buffer
  35078. * @param offset defines the offset in the target buffer where to store the data
  35079. */
  35080. Geometry.prototype.updateIndices = function (indices, offset) {
  35081. if (!this._indexBuffer) {
  35082. return;
  35083. }
  35084. if (!this._indexBufferIsUpdatable) {
  35085. this.setIndices(indices, null, true);
  35086. }
  35087. else {
  35088. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35089. }
  35090. };
  35091. /**
  35092. * Creates a new index buffer
  35093. * @param indices defines the indices to store in the index buffer
  35094. * @param totalVertices defines the total number of vertices (could be null)
  35095. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35096. */
  35097. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35098. if (totalVertices === void 0) { totalVertices = null; }
  35099. if (updatable === void 0) { updatable = false; }
  35100. if (this._indexBuffer) {
  35101. this._engine._releaseBuffer(this._indexBuffer);
  35102. }
  35103. this._disposeVertexArrayObjects();
  35104. this._indices = indices;
  35105. this._indexBufferIsUpdatable = updatable;
  35106. if (this._meshes.length !== 0 && this._indices) {
  35107. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35108. }
  35109. if (totalVertices != undefined) {
  35110. this._totalVertices = totalVertices;
  35111. }
  35112. var meshes = this._meshes;
  35113. var numOfMeshes = meshes.length;
  35114. for (var index = 0; index < numOfMeshes; index++) {
  35115. meshes[index]._createGlobalSubMesh(true);
  35116. }
  35117. this.notifyUpdate();
  35118. };
  35119. /**
  35120. * Return the total number of indices
  35121. * @returns the total number of indices
  35122. */
  35123. Geometry.prototype.getTotalIndices = function () {
  35124. if (!this.isReady()) {
  35125. return 0;
  35126. }
  35127. return this._indices.length;
  35128. };
  35129. /**
  35130. * Gets the index buffer array
  35131. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35132. * @returns the index buffer array
  35133. */
  35134. Geometry.prototype.getIndices = function (copyWhenShared) {
  35135. if (!this.isReady()) {
  35136. return null;
  35137. }
  35138. var orig = this._indices;
  35139. if (!copyWhenShared || this._meshes.length === 1) {
  35140. return orig;
  35141. }
  35142. else {
  35143. var len = orig.length;
  35144. var copy = [];
  35145. for (var i = 0; i < len; i++) {
  35146. copy.push(orig[i]);
  35147. }
  35148. return copy;
  35149. }
  35150. };
  35151. /**
  35152. * Gets the index buffer
  35153. * @return the index buffer
  35154. */
  35155. Geometry.prototype.getIndexBuffer = function () {
  35156. if (!this.isReady()) {
  35157. return null;
  35158. }
  35159. return this._indexBuffer;
  35160. };
  35161. /** @ignore */
  35162. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35163. if (effect === void 0) { effect = null; }
  35164. if (!effect || !this._vertexArrayObjects) {
  35165. return;
  35166. }
  35167. if (this._vertexArrayObjects[effect.key]) {
  35168. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35169. delete this._vertexArrayObjects[effect.key];
  35170. }
  35171. };
  35172. /**
  35173. * Release the associated resources for a specific mesh
  35174. * @param mesh defines the source mesh
  35175. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35176. */
  35177. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35178. var meshes = this._meshes;
  35179. var index = meshes.indexOf(mesh);
  35180. if (index === -1) {
  35181. return;
  35182. }
  35183. meshes.splice(index, 1);
  35184. mesh._geometry = null;
  35185. if (meshes.length === 0 && shouldDispose) {
  35186. this.dispose();
  35187. }
  35188. };
  35189. /**
  35190. * Apply current geometry to a given mesh
  35191. * @param mesh defines the mesh to apply geometry to
  35192. */
  35193. Geometry.prototype.applyToMesh = function (mesh) {
  35194. if (mesh._geometry === this) {
  35195. return;
  35196. }
  35197. var previousGeometry = mesh._geometry;
  35198. if (previousGeometry) {
  35199. previousGeometry.releaseForMesh(mesh);
  35200. }
  35201. var meshes = this._meshes;
  35202. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35203. mesh._geometry = this;
  35204. this._scene.pushGeometry(this);
  35205. meshes.push(mesh);
  35206. if (this.isReady()) {
  35207. this._applyToMesh(mesh);
  35208. }
  35209. else {
  35210. mesh._boundingInfo = this._boundingInfo;
  35211. }
  35212. };
  35213. Geometry.prototype.updateExtend = function (data, stride) {
  35214. if (data === void 0) { data = null; }
  35215. if (!data) {
  35216. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35217. }
  35218. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35219. };
  35220. Geometry.prototype._applyToMesh = function (mesh) {
  35221. var numOfMeshes = this._meshes.length;
  35222. // vertexBuffers
  35223. for (var kind in this._vertexBuffers) {
  35224. if (numOfMeshes === 1) {
  35225. this._vertexBuffers[kind].create();
  35226. }
  35227. var buffer = this._vertexBuffers[kind].getBuffer();
  35228. if (buffer)
  35229. buffer.references = numOfMeshes;
  35230. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35231. if (!this._extend) {
  35232. this.updateExtend(this._vertexBuffers[kind].getData());
  35233. }
  35234. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35235. mesh._createGlobalSubMesh(false);
  35236. //bounding info was just created again, world matrix should be applied again.
  35237. mesh._updateBoundingInfo();
  35238. }
  35239. }
  35240. // indexBuffer
  35241. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35242. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35243. }
  35244. if (this._indexBuffer) {
  35245. this._indexBuffer.references = numOfMeshes;
  35246. }
  35247. };
  35248. Geometry.prototype.notifyUpdate = function (kind) {
  35249. if (this.onGeometryUpdated) {
  35250. this.onGeometryUpdated(this, kind);
  35251. }
  35252. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35253. var mesh = _a[_i];
  35254. mesh._markSubMeshesAsAttributesDirty();
  35255. }
  35256. };
  35257. /**
  35258. * Load the geometry if it was flagged as delay loaded
  35259. * @param scene defines the hosting scene
  35260. * @param onLoaded defines a callback called when the geometry is loaded
  35261. */
  35262. Geometry.prototype.load = function (scene, onLoaded) {
  35263. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35264. return;
  35265. }
  35266. if (this.isReady()) {
  35267. if (onLoaded) {
  35268. onLoaded();
  35269. }
  35270. return;
  35271. }
  35272. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35273. this._queueLoad(scene, onLoaded);
  35274. };
  35275. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35276. var _this = this;
  35277. if (!this.delayLoadingFile) {
  35278. return;
  35279. }
  35280. scene._addPendingData(this);
  35281. scene._loadFile(this.delayLoadingFile, function (data) {
  35282. if (!_this._delayLoadingFunction) {
  35283. return;
  35284. }
  35285. _this._delayLoadingFunction(JSON.parse(data), _this);
  35286. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35287. _this._delayInfo = [];
  35288. scene._removePendingData(_this);
  35289. var meshes = _this._meshes;
  35290. var numOfMeshes = meshes.length;
  35291. for (var index = 0; index < numOfMeshes; index++) {
  35292. _this._applyToMesh(meshes[index]);
  35293. }
  35294. if (onLoaded) {
  35295. onLoaded();
  35296. }
  35297. }, undefined, true);
  35298. };
  35299. /**
  35300. * Invert the geometry to move from a right handed system to a left handed one.
  35301. */
  35302. Geometry.prototype.toLeftHanded = function () {
  35303. // Flip faces
  35304. var tIndices = this.getIndices(false);
  35305. if (tIndices != null && tIndices.length > 0) {
  35306. for (var i = 0; i < tIndices.length; i += 3) {
  35307. var tTemp = tIndices[i + 0];
  35308. tIndices[i + 0] = tIndices[i + 2];
  35309. tIndices[i + 2] = tTemp;
  35310. }
  35311. this.setIndices(tIndices);
  35312. }
  35313. // Negate position.z
  35314. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35315. if (tPositions != null && tPositions.length > 0) {
  35316. for (var i = 0; i < tPositions.length; i += 3) {
  35317. tPositions[i + 2] = -tPositions[i + 2];
  35318. }
  35319. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35320. }
  35321. // Negate normal.z
  35322. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35323. if (tNormals != null && tNormals.length > 0) {
  35324. for (var i = 0; i < tNormals.length; i += 3) {
  35325. tNormals[i + 2] = -tNormals[i + 2];
  35326. }
  35327. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35328. }
  35329. };
  35330. // Cache
  35331. /** @ignore */
  35332. Geometry.prototype._resetPointsArrayCache = function () {
  35333. this._positions = null;
  35334. };
  35335. /** @ignore */
  35336. Geometry.prototype._generatePointsArray = function () {
  35337. if (this._positions)
  35338. return true;
  35339. this._positions = [];
  35340. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35341. if (!data) {
  35342. return false;
  35343. }
  35344. for (var index = 0; index < data.length; index += 3) {
  35345. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35346. }
  35347. return true;
  35348. };
  35349. /**
  35350. * Gets a value indicating if the geometry is disposed
  35351. * @returns true if the geometry was disposed
  35352. */
  35353. Geometry.prototype.isDisposed = function () {
  35354. return this._isDisposed;
  35355. };
  35356. Geometry.prototype._disposeVertexArrayObjects = function () {
  35357. if (this._vertexArrayObjects) {
  35358. for (var kind in this._vertexArrayObjects) {
  35359. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35360. }
  35361. this._vertexArrayObjects = {};
  35362. }
  35363. };
  35364. /**
  35365. * Free all associated resources
  35366. */
  35367. Geometry.prototype.dispose = function () {
  35368. var meshes = this._meshes;
  35369. var numOfMeshes = meshes.length;
  35370. var index;
  35371. for (index = 0; index < numOfMeshes; index++) {
  35372. this.releaseForMesh(meshes[index]);
  35373. }
  35374. this._meshes = [];
  35375. this._disposeVertexArrayObjects();
  35376. for (var kind in this._vertexBuffers) {
  35377. this._vertexBuffers[kind].dispose();
  35378. }
  35379. this._vertexBuffers = {};
  35380. this._totalVertices = 0;
  35381. if (this._indexBuffer) {
  35382. this._engine._releaseBuffer(this._indexBuffer);
  35383. }
  35384. this._indexBuffer = null;
  35385. this._indices = [];
  35386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35387. this.delayLoadingFile = null;
  35388. this._delayLoadingFunction = null;
  35389. this._delayInfo = [];
  35390. this._boundingInfo = null;
  35391. this._scene.removeGeometry(this);
  35392. this._isDisposed = true;
  35393. };
  35394. /**
  35395. * Clone the current geometry into a new geometry
  35396. * @param id defines the unique ID of the new geometry
  35397. * @returns a new geometry object
  35398. */
  35399. Geometry.prototype.copy = function (id) {
  35400. var vertexData = new BABYLON.VertexData();
  35401. vertexData.indices = [];
  35402. var indices = this.getIndices();
  35403. if (indices) {
  35404. for (var index = 0; index < indices.length; index++) {
  35405. vertexData.indices.push(indices[index]);
  35406. }
  35407. }
  35408. var updatable = false;
  35409. var stopChecking = false;
  35410. var kind;
  35411. for (kind in this._vertexBuffers) {
  35412. // using slice() to make a copy of the array and not just reference it
  35413. var data = this.getVerticesData(kind);
  35414. if (data instanceof Float32Array) {
  35415. vertexData.set(new Float32Array(data), kind);
  35416. }
  35417. else {
  35418. vertexData.set(data.slice(0), kind);
  35419. }
  35420. if (!stopChecking) {
  35421. var vb = this.getVertexBuffer(kind);
  35422. if (vb) {
  35423. updatable = vb.isUpdatable();
  35424. stopChecking = !updatable;
  35425. }
  35426. }
  35427. }
  35428. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35429. geometry.delayLoadState = this.delayLoadState;
  35430. geometry.delayLoadingFile = this.delayLoadingFile;
  35431. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35432. for (kind in this._delayInfo) {
  35433. geometry._delayInfo = geometry._delayInfo || [];
  35434. geometry._delayInfo.push(kind);
  35435. }
  35436. // Bounding info
  35437. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35438. return geometry;
  35439. };
  35440. /**
  35441. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35442. * @return a JSON representation of the current geometry data (without the vertices data)
  35443. */
  35444. Geometry.prototype.serialize = function () {
  35445. var serializationObject = {};
  35446. serializationObject.id = this.id;
  35447. serializationObject.updatable = this._updatable;
  35448. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35449. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35450. }
  35451. return serializationObject;
  35452. };
  35453. Geometry.prototype.toNumberArray = function (origin) {
  35454. if (Array.isArray(origin)) {
  35455. return origin;
  35456. }
  35457. else {
  35458. return Array.prototype.slice.call(origin);
  35459. }
  35460. };
  35461. /**
  35462. * Serialize all vertices data into a JSON oject
  35463. * @returns a JSON representation of the current geometry data
  35464. */
  35465. Geometry.prototype.serializeVerticeData = function () {
  35466. var serializationObject = this.serialize();
  35467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35468. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35469. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35470. serializationObject.positions._updatable = true;
  35471. }
  35472. }
  35473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35474. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35475. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35476. serializationObject.normals._updatable = true;
  35477. }
  35478. }
  35479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35480. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35481. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35482. serializationObject.tangets._updatable = true;
  35483. }
  35484. }
  35485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35486. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35487. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35488. serializationObject.uvs._updatable = true;
  35489. }
  35490. }
  35491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35492. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35494. serializationObject.uv2s._updatable = true;
  35495. }
  35496. }
  35497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35498. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35499. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35500. serializationObject.uv3s._updatable = true;
  35501. }
  35502. }
  35503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35504. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35505. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35506. serializationObject.uv4s._updatable = true;
  35507. }
  35508. }
  35509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35510. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35512. serializationObject.uv5s._updatable = true;
  35513. }
  35514. }
  35515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35516. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35518. serializationObject.uv6s._updatable = true;
  35519. }
  35520. }
  35521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35522. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35524. serializationObject.colors._updatable = true;
  35525. }
  35526. }
  35527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35528. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35529. serializationObject.matricesIndices._isExpanded = true;
  35530. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35531. serializationObject.matricesIndices._updatable = true;
  35532. }
  35533. }
  35534. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35535. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35536. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35537. serializationObject.matricesWeights._updatable = true;
  35538. }
  35539. }
  35540. serializationObject.indices = this.toNumberArray(this.getIndices());
  35541. return serializationObject;
  35542. };
  35543. // Statics
  35544. /**
  35545. * Extracts a clone of a mesh geometry
  35546. * @param mesh defines the source mesh
  35547. * @param id defines the unique ID of the new geometry object
  35548. * @returns the new geometry object
  35549. */
  35550. Geometry.ExtractFromMesh = function (mesh, id) {
  35551. var geometry = mesh._geometry;
  35552. if (!geometry) {
  35553. return null;
  35554. }
  35555. return geometry.copy(id);
  35556. };
  35557. /**
  35558. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35559. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35560. * Be aware Math.random() could cause collisions, but:
  35561. * "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"
  35562. * @returns a string containing a new GUID
  35563. */
  35564. Geometry.RandomId = function () {
  35565. return BABYLON.Tools.RandomId();
  35566. };
  35567. /** @ignore */
  35568. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35569. var scene = mesh.getScene();
  35570. // Geometry
  35571. var geometryId = parsedGeometry.geometryId;
  35572. if (geometryId) {
  35573. var geometry = scene.getGeometryByID(geometryId);
  35574. if (geometry) {
  35575. geometry.applyToMesh(mesh);
  35576. }
  35577. }
  35578. else if (parsedGeometry instanceof ArrayBuffer) {
  35579. var binaryInfo = mesh._binaryInfo;
  35580. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35581. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35583. }
  35584. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35585. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35586. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35587. }
  35588. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35589. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35590. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35591. }
  35592. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35593. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35594. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35595. }
  35596. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35597. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35598. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35599. }
  35600. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35601. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35602. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35603. }
  35604. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35605. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35606. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35607. }
  35608. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35609. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35610. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35611. }
  35612. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35613. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35614. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35615. }
  35616. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35617. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35618. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35619. }
  35620. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35621. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35623. }
  35624. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35625. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35627. }
  35628. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35629. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35630. mesh.setIndices(indicesData, null);
  35631. }
  35632. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35633. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35634. mesh.subMeshes = [];
  35635. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35636. var materialIndex = subMeshesData[(i * 5) + 0];
  35637. var verticesStart = subMeshesData[(i * 5) + 1];
  35638. var verticesCount = subMeshesData[(i * 5) + 2];
  35639. var indexStart = subMeshesData[(i * 5) + 3];
  35640. var indexCount = subMeshesData[(i * 5) + 4];
  35641. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35642. }
  35643. }
  35644. }
  35645. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35646. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35647. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35648. if (parsedGeometry.tangents) {
  35649. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35650. }
  35651. if (parsedGeometry.uvs) {
  35652. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35653. }
  35654. if (parsedGeometry.uvs2) {
  35655. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35656. }
  35657. if (parsedGeometry.uvs3) {
  35658. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35659. }
  35660. if (parsedGeometry.uvs4) {
  35661. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35662. }
  35663. if (parsedGeometry.uvs5) {
  35664. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35665. }
  35666. if (parsedGeometry.uvs6) {
  35667. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35668. }
  35669. if (parsedGeometry.colors) {
  35670. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35671. }
  35672. if (parsedGeometry.matricesIndices) {
  35673. if (!parsedGeometry.matricesIndices._isExpanded) {
  35674. var floatIndices = [];
  35675. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35676. var matricesIndex = parsedGeometry.matricesIndices[i];
  35677. floatIndices.push(matricesIndex & 0x000000FF);
  35678. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35679. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35680. floatIndices.push(matricesIndex >> 24);
  35681. }
  35682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35683. }
  35684. else {
  35685. delete parsedGeometry.matricesIndices._isExpanded;
  35686. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35687. }
  35688. }
  35689. if (parsedGeometry.matricesIndicesExtra) {
  35690. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35691. var floatIndices = [];
  35692. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35693. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35694. floatIndices.push(matricesIndex & 0x000000FF);
  35695. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35696. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35697. floatIndices.push(matricesIndex >> 24);
  35698. }
  35699. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35700. }
  35701. else {
  35702. delete parsedGeometry.matricesIndices._isExpanded;
  35703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35704. }
  35705. }
  35706. if (parsedGeometry.matricesWeights) {
  35707. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35709. }
  35710. if (parsedGeometry.matricesWeightsExtra) {
  35711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35712. }
  35713. mesh.setIndices(parsedGeometry.indices, null);
  35714. }
  35715. // SubMeshes
  35716. if (parsedGeometry.subMeshes) {
  35717. mesh.subMeshes = [];
  35718. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35719. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35720. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35721. }
  35722. }
  35723. // Flat shading
  35724. if (mesh._shouldGenerateFlatShading) {
  35725. mesh.convertToFlatShadedMesh();
  35726. delete mesh._shouldGenerateFlatShading;
  35727. }
  35728. // Update
  35729. mesh.computeWorldMatrix(true);
  35730. // Octree
  35731. var sceneOctree = scene.selectionOctree;
  35732. if (sceneOctree !== undefined && sceneOctree !== null) {
  35733. sceneOctree.addMesh(mesh);
  35734. }
  35735. };
  35736. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35737. var epsilon = 1e-3;
  35738. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35739. return;
  35740. }
  35741. var noInfluenceBoneIndex = 0.0;
  35742. if (parsedGeometry.skeletonId > -1) {
  35743. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35744. if (!skeleton) {
  35745. return;
  35746. }
  35747. noInfluenceBoneIndex = skeleton.bones.length;
  35748. }
  35749. else {
  35750. return;
  35751. }
  35752. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35753. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35754. var matricesWeights = parsedGeometry.matricesWeights;
  35755. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35756. var influencers = parsedGeometry.numBoneInfluencer;
  35757. var size = matricesWeights.length;
  35758. for (var i = 0; i < size; i += 4) {
  35759. var weight = 0.0;
  35760. var firstZeroWeight = -1;
  35761. for (var j = 0; j < 4; j++) {
  35762. var w = matricesWeights[i + j];
  35763. weight += w;
  35764. if (w < epsilon && firstZeroWeight < 0) {
  35765. firstZeroWeight = j;
  35766. }
  35767. }
  35768. if (matricesWeightsExtra) {
  35769. for (var j = 0; j < 4; j++) {
  35770. var w = matricesWeightsExtra[i + j];
  35771. weight += w;
  35772. if (w < epsilon && firstZeroWeight < 0) {
  35773. firstZeroWeight = j + 4;
  35774. }
  35775. }
  35776. }
  35777. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35778. firstZeroWeight = influencers - 1;
  35779. }
  35780. if (weight > epsilon) {
  35781. var mweight = 1.0 / weight;
  35782. for (var j = 0; j < 4; j++) {
  35783. matricesWeights[i + j] *= mweight;
  35784. }
  35785. if (matricesWeightsExtra) {
  35786. for (var j = 0; j < 4; j++) {
  35787. matricesWeightsExtra[i + j] *= mweight;
  35788. }
  35789. }
  35790. }
  35791. else {
  35792. if (firstZeroWeight >= 4) {
  35793. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35794. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35795. }
  35796. else {
  35797. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35798. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35799. }
  35800. }
  35801. }
  35802. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35803. if (parsedGeometry.matricesWeightsExtra) {
  35804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35805. }
  35806. };
  35807. /**
  35808. * Create a new geometry from persisted data (Using .babylon file format)
  35809. * @param parsedVertexData defines the persisted data
  35810. * @param scene defines the hosting scene
  35811. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35812. * @returns the new geometry object
  35813. */
  35814. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35815. if (scene.getGeometryByID(parsedVertexData.id)) {
  35816. return null; // null since geometry could be something else than a box...
  35817. }
  35818. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35819. if (BABYLON.Tags) {
  35820. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35821. }
  35822. if (parsedVertexData.delayLoadingFile) {
  35823. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35824. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35825. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35826. geometry._delayInfo = [];
  35827. if (parsedVertexData.hasUVs) {
  35828. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35829. }
  35830. if (parsedVertexData.hasUVs2) {
  35831. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35832. }
  35833. if (parsedVertexData.hasUVs3) {
  35834. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35835. }
  35836. if (parsedVertexData.hasUVs4) {
  35837. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35838. }
  35839. if (parsedVertexData.hasUVs5) {
  35840. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35841. }
  35842. if (parsedVertexData.hasUVs6) {
  35843. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35844. }
  35845. if (parsedVertexData.hasColors) {
  35846. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35847. }
  35848. if (parsedVertexData.hasMatricesIndices) {
  35849. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35850. }
  35851. if (parsedVertexData.hasMatricesWeights) {
  35852. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35853. }
  35854. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35855. }
  35856. else {
  35857. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35858. }
  35859. scene.pushGeometry(geometry, true);
  35860. return geometry;
  35861. };
  35862. return Geometry;
  35863. }());
  35864. BABYLON.Geometry = Geometry;
  35865. // Primitives
  35866. /// Abstract class
  35867. /**
  35868. * Abstract class used to provide common services for all typed geometries
  35869. */
  35870. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35871. __extends(_PrimitiveGeometry, _super);
  35872. /**
  35873. * Creates a new typed geometry
  35874. * @param id defines the unique ID of the geometry
  35875. * @param scene defines the hosting scene
  35876. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35877. * @param mesh defines the hosting mesh (can be null)
  35878. */
  35879. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35880. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35881. if (mesh === void 0) { mesh = null; }
  35882. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35883. _this._canBeRegenerated = _canBeRegenerated;
  35884. _this._beingRegenerated = true;
  35885. _this.regenerate();
  35886. _this._beingRegenerated = false;
  35887. return _this;
  35888. }
  35889. /**
  35890. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35891. * @returns true if the geometry can be regenerated
  35892. */
  35893. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35894. return this._canBeRegenerated;
  35895. };
  35896. /**
  35897. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35898. */
  35899. _PrimitiveGeometry.prototype.regenerate = function () {
  35900. if (!this._canBeRegenerated) {
  35901. return;
  35902. }
  35903. this._beingRegenerated = true;
  35904. this.setAllVerticesData(this._regenerateVertexData(), false);
  35905. this._beingRegenerated = false;
  35906. };
  35907. /**
  35908. * Clone the geometry
  35909. * @param id defines the unique ID of the new geometry
  35910. * @returns the new geometry
  35911. */
  35912. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35913. return _super.prototype.copy.call(this, id);
  35914. };
  35915. // overrides
  35916. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35917. if (!this._beingRegenerated) {
  35918. return;
  35919. }
  35920. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35921. };
  35922. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35923. if (!this._beingRegenerated) {
  35924. return;
  35925. }
  35926. _super.prototype.setVerticesData.call(this, kind, data, false);
  35927. };
  35928. // to override
  35929. /** @ignore */
  35930. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35931. throw new Error("Abstract method");
  35932. };
  35933. _PrimitiveGeometry.prototype.copy = function (id) {
  35934. throw new Error("Must be overriden in sub-classes.");
  35935. };
  35936. _PrimitiveGeometry.prototype.serialize = function () {
  35937. var serializationObject = _super.prototype.serialize.call(this);
  35938. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35939. return serializationObject;
  35940. };
  35941. return _PrimitiveGeometry;
  35942. }(Geometry));
  35943. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35944. /**
  35945. * Creates a ribbon geometry
  35946. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35947. */
  35948. var RibbonGeometry = /** @class */ (function (_super) {
  35949. __extends(RibbonGeometry, _super);
  35950. /**
  35951. * Creates a ribbon geometry
  35952. * @param id defines the unique ID of the geometry
  35953. * @param scene defines the hosting scene
  35954. * @param pathArray defines the array of paths to use
  35955. * @param closeArray defines if the last path and the first path must be joined
  35956. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35957. * @param offset defines the offset between points
  35958. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35959. * @param mesh defines the hosting mesh (can be null)
  35960. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35961. */
  35962. function RibbonGeometry(id, scene,
  35963. /**
  35964. * Defines the array of paths to use
  35965. */
  35966. pathArray,
  35967. /**
  35968. * Defines if the last and first points of each path in your pathArray must be joined
  35969. */
  35970. closeArray,
  35971. /**
  35972. * Defines if the last and first points of each path in your pathArray must be joined
  35973. */
  35974. closePath,
  35975. /**
  35976. * Defines the offset between points
  35977. */
  35978. offset, canBeRegenerated, mesh,
  35979. /**
  35980. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35981. */
  35982. side) {
  35983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35984. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35985. _this.pathArray = pathArray;
  35986. _this.closeArray = closeArray;
  35987. _this.closePath = closePath;
  35988. _this.offset = offset;
  35989. _this.side = side;
  35990. return _this;
  35991. }
  35992. /** @ignore */
  35993. RibbonGeometry.prototype._regenerateVertexData = function () {
  35994. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35995. };
  35996. RibbonGeometry.prototype.copy = function (id) {
  35997. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35998. };
  35999. return RibbonGeometry;
  36000. }(_PrimitiveGeometry));
  36001. BABYLON.RibbonGeometry = RibbonGeometry;
  36002. /**
  36003. * Creates a box geometry
  36004. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36005. */
  36006. var BoxGeometry = /** @class */ (function (_super) {
  36007. __extends(BoxGeometry, _super);
  36008. /**
  36009. * Creates a box geometry
  36010. * @param id defines the unique ID of the geometry
  36011. * @param scene defines the hosting scene
  36012. * @param size defines the zise of the box (width, height and depth are the same)
  36013. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36014. * @param mesh defines the hosting mesh (can be null)
  36015. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36016. */
  36017. function BoxGeometry(id, scene,
  36018. /**
  36019. * Defines the zise of the box (width, height and depth are the same)
  36020. */
  36021. size, canBeRegenerated, mesh,
  36022. /**
  36023. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36024. */
  36025. side) {
  36026. if (mesh === void 0) { mesh = null; }
  36027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36029. _this.size = size;
  36030. _this.side = side;
  36031. return _this;
  36032. }
  36033. BoxGeometry.prototype._regenerateVertexData = function () {
  36034. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36035. };
  36036. BoxGeometry.prototype.copy = function (id) {
  36037. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36038. };
  36039. BoxGeometry.prototype.serialize = function () {
  36040. var serializationObject = _super.prototype.serialize.call(this);
  36041. serializationObject.size = this.size;
  36042. return serializationObject;
  36043. };
  36044. BoxGeometry.Parse = function (parsedBox, scene) {
  36045. if (scene.getGeometryByID(parsedBox.id)) {
  36046. return null; // null since geometry could be something else than a box...
  36047. }
  36048. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36049. if (BABYLON.Tags) {
  36050. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36051. }
  36052. scene.pushGeometry(box, true);
  36053. return box;
  36054. };
  36055. return BoxGeometry;
  36056. }(_PrimitiveGeometry));
  36057. BABYLON.BoxGeometry = BoxGeometry;
  36058. /**
  36059. * Creates a sphere geometry
  36060. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36061. */
  36062. var SphereGeometry = /** @class */ (function (_super) {
  36063. __extends(SphereGeometry, _super);
  36064. /**
  36065. * Create a new sphere geometry
  36066. * @param id defines the unique ID of the geometry
  36067. * @param scene defines the hosting scene
  36068. * @param segments defines the number of segments to use to create the sphere
  36069. * @param diameter defines the diameter of the sphere
  36070. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36071. * @param mesh defines the hosting mesh (can be null)
  36072. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36073. */
  36074. function SphereGeometry(id, scene,
  36075. /**
  36076. * Defines the number of segments to use to create the sphere
  36077. */
  36078. segments,
  36079. /**
  36080. * Defines the diameter of the sphere
  36081. */
  36082. diameter, canBeRegenerated, mesh,
  36083. /**
  36084. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36085. */
  36086. side) {
  36087. if (mesh === void 0) { mesh = null; }
  36088. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36089. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36090. _this.segments = segments;
  36091. _this.diameter = diameter;
  36092. _this.side = side;
  36093. return _this;
  36094. }
  36095. SphereGeometry.prototype._regenerateVertexData = function () {
  36096. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36097. };
  36098. SphereGeometry.prototype.copy = function (id) {
  36099. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36100. };
  36101. SphereGeometry.prototype.serialize = function () {
  36102. var serializationObject = _super.prototype.serialize.call(this);
  36103. serializationObject.segments = this.segments;
  36104. serializationObject.diameter = this.diameter;
  36105. return serializationObject;
  36106. };
  36107. SphereGeometry.Parse = function (parsedSphere, scene) {
  36108. if (scene.getGeometryByID(parsedSphere.id)) {
  36109. return null; // null since geometry could be something else than a sphere...
  36110. }
  36111. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36112. if (BABYLON.Tags) {
  36113. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36114. }
  36115. scene.pushGeometry(sphere, true);
  36116. return sphere;
  36117. };
  36118. return SphereGeometry;
  36119. }(_PrimitiveGeometry));
  36120. BABYLON.SphereGeometry = SphereGeometry;
  36121. /**
  36122. * Creates a disc geometry
  36123. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36124. */
  36125. var DiscGeometry = /** @class */ (function (_super) {
  36126. __extends(DiscGeometry, _super);
  36127. /**
  36128. * Creates a new disc geometry
  36129. * @param id defines the unique ID of the geometry
  36130. * @param scene defines the hosting scene
  36131. * @param radius defines the radius of the disc
  36132. * @param tessellation defines the tesselation factor to apply to the disc
  36133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36134. * @param mesh defines the hosting mesh (can be null)
  36135. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36136. */
  36137. function DiscGeometry(id, scene,
  36138. /**
  36139. * Defines the radius of the disc
  36140. */
  36141. radius,
  36142. /**
  36143. * Defines the tesselation factor to apply to the disc
  36144. */
  36145. tessellation, canBeRegenerated, mesh,
  36146. /**
  36147. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36148. */
  36149. side) {
  36150. if (mesh === void 0) { mesh = null; }
  36151. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36152. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36153. _this.radius = radius;
  36154. _this.tessellation = tessellation;
  36155. _this.side = side;
  36156. return _this;
  36157. }
  36158. DiscGeometry.prototype._regenerateVertexData = function () {
  36159. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36160. };
  36161. DiscGeometry.prototype.copy = function (id) {
  36162. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36163. };
  36164. return DiscGeometry;
  36165. }(_PrimitiveGeometry));
  36166. BABYLON.DiscGeometry = DiscGeometry;
  36167. /**
  36168. * Creates a new cylinder geometry
  36169. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36170. */
  36171. var CylinderGeometry = /** @class */ (function (_super) {
  36172. __extends(CylinderGeometry, _super);
  36173. /**
  36174. * Creates a new cylinder geometry
  36175. * @param id defines the unique ID of the geometry
  36176. * @param scene defines the hosting scene
  36177. * @param height defines the height of the cylinder
  36178. * @param diameterTop defines the diameter of the cylinder's top cap
  36179. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36180. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36181. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36182. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36183. * @param mesh defines the hosting mesh (can be null)
  36184. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36185. */
  36186. function CylinderGeometry(id, scene,
  36187. /**
  36188. * Defines the height of the cylinder
  36189. */
  36190. height,
  36191. /**
  36192. * Defines the diameter of the cylinder's top cap
  36193. */
  36194. diameterTop,
  36195. /**
  36196. * Defines the diameter of the cylinder's bottom cap
  36197. */
  36198. diameterBottom,
  36199. /**
  36200. * Defines the tessellation factor to apply to the cylinder
  36201. */
  36202. tessellation,
  36203. /**
  36204. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36205. */
  36206. subdivisions, canBeRegenerated, mesh,
  36207. /**
  36208. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36209. */
  36210. side) {
  36211. if (subdivisions === void 0) { subdivisions = 1; }
  36212. if (mesh === void 0) { mesh = null; }
  36213. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36214. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36215. _this.height = height;
  36216. _this.diameterTop = diameterTop;
  36217. _this.diameterBottom = diameterBottom;
  36218. _this.tessellation = tessellation;
  36219. _this.subdivisions = subdivisions;
  36220. _this.side = side;
  36221. return _this;
  36222. }
  36223. CylinderGeometry.prototype._regenerateVertexData = function () {
  36224. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36225. };
  36226. CylinderGeometry.prototype.copy = function (id) {
  36227. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36228. };
  36229. CylinderGeometry.prototype.serialize = function () {
  36230. var serializationObject = _super.prototype.serialize.call(this);
  36231. serializationObject.height = this.height;
  36232. serializationObject.diameterTop = this.diameterTop;
  36233. serializationObject.diameterBottom = this.diameterBottom;
  36234. serializationObject.tessellation = this.tessellation;
  36235. return serializationObject;
  36236. };
  36237. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36238. if (scene.getGeometryByID(parsedCylinder.id)) {
  36239. return null; // null since geometry could be something else than a cylinder...
  36240. }
  36241. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36242. if (BABYLON.Tags) {
  36243. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36244. }
  36245. scene.pushGeometry(cylinder, true);
  36246. return cylinder;
  36247. };
  36248. return CylinderGeometry;
  36249. }(_PrimitiveGeometry));
  36250. BABYLON.CylinderGeometry = CylinderGeometry;
  36251. /**
  36252. * Creates a new torus geometry
  36253. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36254. */
  36255. var TorusGeometry = /** @class */ (function (_super) {
  36256. __extends(TorusGeometry, _super);
  36257. /**
  36258. * Creates a new torus geometry
  36259. * @param id defines the unique ID of the geometry
  36260. * @param scene defines the hosting scene
  36261. * @param diameter defines the diameter of the torus
  36262. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36263. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36264. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36265. * @param mesh defines the hosting mesh (can be null)
  36266. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36267. */
  36268. function TorusGeometry(id, scene,
  36269. /**
  36270. * Defines the diameter of the torus
  36271. */
  36272. diameter,
  36273. /**
  36274. * Defines the thickness of the torus (ie. internal diameter)
  36275. */
  36276. thickness,
  36277. /**
  36278. * Defines the tesselation factor to apply to the torus
  36279. */
  36280. tessellation, canBeRegenerated, mesh,
  36281. /**
  36282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36283. */
  36284. side) {
  36285. if (mesh === void 0) { mesh = null; }
  36286. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36287. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36288. _this.diameter = diameter;
  36289. _this.thickness = thickness;
  36290. _this.tessellation = tessellation;
  36291. _this.side = side;
  36292. return _this;
  36293. }
  36294. TorusGeometry.prototype._regenerateVertexData = function () {
  36295. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36296. };
  36297. TorusGeometry.prototype.copy = function (id) {
  36298. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36299. };
  36300. TorusGeometry.prototype.serialize = function () {
  36301. var serializationObject = _super.prototype.serialize.call(this);
  36302. serializationObject.diameter = this.diameter;
  36303. serializationObject.thickness = this.thickness;
  36304. serializationObject.tessellation = this.tessellation;
  36305. return serializationObject;
  36306. };
  36307. TorusGeometry.Parse = function (parsedTorus, scene) {
  36308. if (scene.getGeometryByID(parsedTorus.id)) {
  36309. return null; // null since geometry could be something else than a torus...
  36310. }
  36311. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36312. if (BABYLON.Tags) {
  36313. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36314. }
  36315. scene.pushGeometry(torus, true);
  36316. return torus;
  36317. };
  36318. return TorusGeometry;
  36319. }(_PrimitiveGeometry));
  36320. BABYLON.TorusGeometry = TorusGeometry;
  36321. /**
  36322. * Creates a new ground geometry
  36323. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36324. */
  36325. var GroundGeometry = /** @class */ (function (_super) {
  36326. __extends(GroundGeometry, _super);
  36327. /**
  36328. * Creates a new ground geometry
  36329. * @param id defines the unique ID of the geometry
  36330. * @param scene defines the hosting scene
  36331. * @param width defines the width of the ground
  36332. * @param height defines the height of the ground
  36333. * @param subdivisions defines the subdivisions to apply to the ground
  36334. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36335. * @param mesh defines the hosting mesh (can be null)
  36336. */
  36337. function GroundGeometry(id, scene,
  36338. /**
  36339. * Defines the width of the ground
  36340. */
  36341. width,
  36342. /**
  36343. * Defines the height of the ground
  36344. */
  36345. height,
  36346. /**
  36347. * Defines the subdivisions to apply to the ground
  36348. */
  36349. subdivisions, canBeRegenerated, mesh) {
  36350. if (mesh === void 0) { mesh = null; }
  36351. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36352. _this.width = width;
  36353. _this.height = height;
  36354. _this.subdivisions = subdivisions;
  36355. return _this;
  36356. }
  36357. GroundGeometry.prototype._regenerateVertexData = function () {
  36358. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36359. };
  36360. GroundGeometry.prototype.copy = function (id) {
  36361. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36362. };
  36363. GroundGeometry.prototype.serialize = function () {
  36364. var serializationObject = _super.prototype.serialize.call(this);
  36365. serializationObject.width = this.width;
  36366. serializationObject.height = this.height;
  36367. serializationObject.subdivisions = this.subdivisions;
  36368. return serializationObject;
  36369. };
  36370. GroundGeometry.Parse = function (parsedGround, scene) {
  36371. if (scene.getGeometryByID(parsedGround.id)) {
  36372. return null; // null since geometry could be something else than a ground...
  36373. }
  36374. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36375. if (BABYLON.Tags) {
  36376. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36377. }
  36378. scene.pushGeometry(ground, true);
  36379. return ground;
  36380. };
  36381. return GroundGeometry;
  36382. }(_PrimitiveGeometry));
  36383. BABYLON.GroundGeometry = GroundGeometry;
  36384. /**
  36385. * Creates a tiled ground geometry
  36386. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36387. */
  36388. var TiledGroundGeometry = /** @class */ (function (_super) {
  36389. __extends(TiledGroundGeometry, _super);
  36390. /**
  36391. * Creates a tiled ground geometry
  36392. * @param id defines the unique ID of the geometry
  36393. * @param scene defines the hosting scene
  36394. * @param xmin defines the minimum value on X axis
  36395. * @param zmin defines the minimum value on Z axis
  36396. * @param xmax defines the maximum value on X axis
  36397. * @param zmax defines the maximum value on Z axis
  36398. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36399. * @param precision defines the precision to use when computing the tiles
  36400. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36401. * @param mesh defines the hosting mesh (can be null)
  36402. */
  36403. function TiledGroundGeometry(id, scene,
  36404. /**
  36405. * Defines the minimum value on X axis
  36406. */
  36407. xmin,
  36408. /**
  36409. * Defines the minimum value on Z axis
  36410. */
  36411. zmin,
  36412. /**
  36413. * Defines the maximum value on X axis
  36414. */
  36415. xmax,
  36416. /**
  36417. * Defines the maximum value on Z axis
  36418. */
  36419. zmax,
  36420. /**
  36421. * Defines the subdivisions to apply to the ground
  36422. */
  36423. subdivisions,
  36424. /**
  36425. * Defines the precision to use when computing the tiles
  36426. */
  36427. precision, canBeRegenerated, mesh) {
  36428. if (mesh === void 0) { mesh = null; }
  36429. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36430. _this.xmin = xmin;
  36431. _this.zmin = zmin;
  36432. _this.xmax = xmax;
  36433. _this.zmax = zmax;
  36434. _this.subdivisions = subdivisions;
  36435. _this.precision = precision;
  36436. return _this;
  36437. }
  36438. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36439. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36440. };
  36441. TiledGroundGeometry.prototype.copy = function (id) {
  36442. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36443. };
  36444. return TiledGroundGeometry;
  36445. }(_PrimitiveGeometry));
  36446. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36447. /**
  36448. * Creates a plane geometry
  36449. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36450. */
  36451. var PlaneGeometry = /** @class */ (function (_super) {
  36452. __extends(PlaneGeometry, _super);
  36453. /**
  36454. * Creates a plane geometry
  36455. * @param id defines the unique ID of the geometry
  36456. * @param scene defines the hosting scene
  36457. * @param size defines the size of the plane (width === height)
  36458. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36459. * @param mesh defines the hosting mesh (can be null)
  36460. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36461. */
  36462. function PlaneGeometry(id, scene,
  36463. /**
  36464. * Defines the size of the plane (width === height)
  36465. */
  36466. size, canBeRegenerated, mesh,
  36467. /**
  36468. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36469. */
  36470. side) {
  36471. if (mesh === void 0) { mesh = null; }
  36472. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36473. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36474. _this.size = size;
  36475. _this.side = side;
  36476. return _this;
  36477. }
  36478. PlaneGeometry.prototype._regenerateVertexData = function () {
  36479. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36480. };
  36481. PlaneGeometry.prototype.copy = function (id) {
  36482. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36483. };
  36484. PlaneGeometry.prototype.serialize = function () {
  36485. var serializationObject = _super.prototype.serialize.call(this);
  36486. serializationObject.size = this.size;
  36487. return serializationObject;
  36488. };
  36489. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36490. if (scene.getGeometryByID(parsedPlane.id)) {
  36491. return null; // null since geometry could be something else than a ground...
  36492. }
  36493. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36494. if (BABYLON.Tags) {
  36495. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36496. }
  36497. scene.pushGeometry(plane, true);
  36498. return plane;
  36499. };
  36500. return PlaneGeometry;
  36501. }(_PrimitiveGeometry));
  36502. BABYLON.PlaneGeometry = PlaneGeometry;
  36503. /**
  36504. * Creates a torus knot geometry
  36505. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36506. */
  36507. var TorusKnotGeometry = /** @class */ (function (_super) {
  36508. __extends(TorusKnotGeometry, _super);
  36509. /**
  36510. * Creates a torus knot geometry
  36511. * @param id defines the unique ID of the geometry
  36512. * @param scene defines the hosting scene
  36513. * @param radius defines the radius of the torus knot
  36514. * @param tube defines the thickness of the torus knot tube
  36515. * @param radialSegments defines the number of radial segments
  36516. * @param tubularSegments defines the number of tubular segments
  36517. * @param p defines the first number of windings
  36518. * @param q defines the second number of windings
  36519. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36520. * @param mesh defines the hosting mesh (can be null)
  36521. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36522. */
  36523. function TorusKnotGeometry(id, scene,
  36524. /**
  36525. * Defines the radius of the torus knot
  36526. */
  36527. radius,
  36528. /**
  36529. * Defines the thickness of the torus knot tube
  36530. */
  36531. tube,
  36532. /**
  36533. * Defines the number of radial segments
  36534. */
  36535. radialSegments,
  36536. /**
  36537. * Defines the number of tubular segments
  36538. */
  36539. tubularSegments,
  36540. /**
  36541. * Defines the first number of windings
  36542. */
  36543. p,
  36544. /**
  36545. * Defines the second number of windings
  36546. */
  36547. q, canBeRegenerated, mesh,
  36548. /**
  36549. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36550. */
  36551. side) {
  36552. if (mesh === void 0) { mesh = null; }
  36553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36555. _this.radius = radius;
  36556. _this.tube = tube;
  36557. _this.radialSegments = radialSegments;
  36558. _this.tubularSegments = tubularSegments;
  36559. _this.p = p;
  36560. _this.q = q;
  36561. _this.side = side;
  36562. return _this;
  36563. }
  36564. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36565. 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 });
  36566. };
  36567. TorusKnotGeometry.prototype.copy = function (id) {
  36568. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36569. };
  36570. TorusKnotGeometry.prototype.serialize = function () {
  36571. var serializationObject = _super.prototype.serialize.call(this);
  36572. serializationObject.radius = this.radius;
  36573. serializationObject.tube = this.tube;
  36574. serializationObject.radialSegments = this.radialSegments;
  36575. serializationObject.tubularSegments = this.tubularSegments;
  36576. serializationObject.p = this.p;
  36577. serializationObject.q = this.q;
  36578. return serializationObject;
  36579. };
  36580. ;
  36581. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36582. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36583. return null; // null since geometry could be something else than a ground...
  36584. }
  36585. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36586. if (BABYLON.Tags) {
  36587. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36588. }
  36589. scene.pushGeometry(torusKnot, true);
  36590. return torusKnot;
  36591. };
  36592. return TorusKnotGeometry;
  36593. }(_PrimitiveGeometry));
  36594. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36595. //}
  36596. })(BABYLON || (BABYLON = {}));
  36597. //# sourceMappingURL=babylon.geometry.js.map
  36598. var BABYLON;
  36599. (function (BABYLON) {
  36600. /**
  36601. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36602. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36603. */
  36604. var PostProcessManager = /** @class */ (function () {
  36605. /**
  36606. * Creates a new instance of @see PostProcess
  36607. * @param scene The scene that the post process is associated with.
  36608. */
  36609. function PostProcessManager(scene) {
  36610. this._vertexBuffers = {};
  36611. this._scene = scene;
  36612. }
  36613. PostProcessManager.prototype._prepareBuffers = function () {
  36614. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36615. return;
  36616. }
  36617. // VBO
  36618. var vertices = [];
  36619. vertices.push(1, 1);
  36620. vertices.push(-1, 1);
  36621. vertices.push(-1, -1);
  36622. vertices.push(1, -1);
  36623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36624. this._buildIndexBuffer();
  36625. };
  36626. PostProcessManager.prototype._buildIndexBuffer = function () {
  36627. // Indices
  36628. var indices = [];
  36629. indices.push(0);
  36630. indices.push(1);
  36631. indices.push(2);
  36632. indices.push(0);
  36633. indices.push(2);
  36634. indices.push(3);
  36635. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36636. };
  36637. /**
  36638. * Rebuilds the vertex buffers of the manager.
  36639. */
  36640. PostProcessManager.prototype._rebuild = function () {
  36641. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36642. if (!vb) {
  36643. return;
  36644. }
  36645. vb._rebuild();
  36646. this._buildIndexBuffer();
  36647. };
  36648. // Methods
  36649. /**
  36650. * Prepares a frame to be run through a post process.
  36651. * @param sourceTexture The input texture to the post procesess. (default: null)
  36652. * @param postProcesses An array of post processes to be run. (default: null)
  36653. * @returns True if the post processes were able to be run.
  36654. */
  36655. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36656. if (sourceTexture === void 0) { sourceTexture = null; }
  36657. if (postProcesses === void 0) { postProcesses = null; }
  36658. var camera = this._scene.activeCamera;
  36659. if (!camera) {
  36660. return false;
  36661. }
  36662. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36663. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36664. return false;
  36665. }
  36666. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36667. return true;
  36668. };
  36669. /**
  36670. * Manually render a set of post processes to a texture.
  36671. * @param postProcesses An array of post processes to be run.
  36672. * @param targetTexture The target texture to render to.
  36673. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36674. */
  36675. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36676. if (targetTexture === void 0) { targetTexture = null; }
  36677. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36678. var engine = this._scene.getEngine();
  36679. for (var index = 0; index < postProcesses.length; index++) {
  36680. if (index < postProcesses.length - 1) {
  36681. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36682. }
  36683. else {
  36684. if (targetTexture) {
  36685. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36686. }
  36687. else {
  36688. engine.restoreDefaultFramebuffer();
  36689. }
  36690. }
  36691. var pp = postProcesses[index];
  36692. var effect = pp.apply();
  36693. if (effect) {
  36694. pp.onBeforeRenderObservable.notifyObservers(effect);
  36695. // VBOs
  36696. this._prepareBuffers();
  36697. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36698. // Draw order
  36699. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36700. pp.onAfterRenderObservable.notifyObservers(effect);
  36701. }
  36702. }
  36703. // Restore depth buffer
  36704. engine.setDepthBuffer(true);
  36705. engine.setDepthWrite(true);
  36706. };
  36707. /**
  36708. * Finalize the result of the output of the postprocesses.
  36709. * @param doNotPresent If true the result will not be displayed to the screen.
  36710. * @param targetTexture The target texture to render to.
  36711. * @param faceIndex The index of the face to bind the target texture to.
  36712. * @param postProcesses The array of post processes to render.
  36713. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36714. */
  36715. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36716. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36717. var camera = this._scene.activeCamera;
  36718. if (!camera) {
  36719. return;
  36720. }
  36721. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36722. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36723. return;
  36724. }
  36725. var engine = this._scene.getEngine();
  36726. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36727. if (index < len - 1) {
  36728. postProcesses[index + 1].activate(camera, targetTexture);
  36729. }
  36730. else {
  36731. if (targetTexture) {
  36732. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36733. }
  36734. else {
  36735. engine.restoreDefaultFramebuffer();
  36736. }
  36737. }
  36738. if (doNotPresent) {
  36739. break;
  36740. }
  36741. var pp = postProcesses[index];
  36742. var effect = pp.apply();
  36743. if (effect) {
  36744. pp.onBeforeRenderObservable.notifyObservers(effect);
  36745. // VBOs
  36746. this._prepareBuffers();
  36747. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36748. // Draw order
  36749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36750. pp.onAfterRenderObservable.notifyObservers(effect);
  36751. }
  36752. }
  36753. // Restore states
  36754. engine.setDepthBuffer(true);
  36755. engine.setDepthWrite(true);
  36756. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36757. };
  36758. /**
  36759. * Disposes of the post process manager.
  36760. */
  36761. PostProcessManager.prototype.dispose = function () {
  36762. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36763. if (buffer) {
  36764. buffer.dispose();
  36765. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36766. }
  36767. if (this._indexBuffer) {
  36768. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36769. this._indexBuffer = null;
  36770. }
  36771. };
  36772. return PostProcessManager;
  36773. }());
  36774. BABYLON.PostProcessManager = PostProcessManager;
  36775. })(BABYLON || (BABYLON = {}));
  36776. //# sourceMappingURL=babylon.postProcessManager.js.map
  36777. var BABYLON;
  36778. (function (BABYLON) {
  36779. /**
  36780. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36781. */
  36782. var PerformanceMonitor = /** @class */ (function () {
  36783. /**
  36784. * constructor
  36785. * @param frameSampleSize The number of samples required to saturate the sliding window
  36786. */
  36787. function PerformanceMonitor(frameSampleSize) {
  36788. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36789. this._enabled = true;
  36790. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36791. }
  36792. /**
  36793. * Samples current frame
  36794. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36795. */
  36796. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36797. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36798. if (!this._enabled)
  36799. return;
  36800. if (this._lastFrameTimeMs != null) {
  36801. var dt = timeMs - this._lastFrameTimeMs;
  36802. this._rollingFrameTime.add(dt);
  36803. }
  36804. this._lastFrameTimeMs = timeMs;
  36805. };
  36806. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36807. /**
  36808. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36809. * @return Average frame time in milliseconds
  36810. */
  36811. get: function () {
  36812. return this._rollingFrameTime.average;
  36813. },
  36814. enumerable: true,
  36815. configurable: true
  36816. });
  36817. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36818. /**
  36819. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36820. * @return Frame time variance in milliseconds squared
  36821. */
  36822. get: function () {
  36823. return this._rollingFrameTime.variance;
  36824. },
  36825. enumerable: true,
  36826. configurable: true
  36827. });
  36828. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36829. /**
  36830. * Returns the frame time of the most recent frame
  36831. * @return Frame time in milliseconds
  36832. */
  36833. get: function () {
  36834. return this._rollingFrameTime.history(0);
  36835. },
  36836. enumerable: true,
  36837. configurable: true
  36838. });
  36839. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36840. /**
  36841. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36842. * @return Framerate in frames per second
  36843. */
  36844. get: function () {
  36845. return 1000.0 / this._rollingFrameTime.average;
  36846. },
  36847. enumerable: true,
  36848. configurable: true
  36849. });
  36850. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36851. /**
  36852. * Returns the average framerate in frames per second using the most recent frame time
  36853. * @return Framerate in frames per second
  36854. */
  36855. get: function () {
  36856. var history = this._rollingFrameTime.history(0);
  36857. if (history === 0) {
  36858. return 0;
  36859. }
  36860. return 1000.0 / history;
  36861. },
  36862. enumerable: true,
  36863. configurable: true
  36864. });
  36865. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36866. /**
  36867. * Returns true if enough samples have been taken to completely fill the sliding window
  36868. * @return true if saturated
  36869. */
  36870. get: function () {
  36871. return this._rollingFrameTime.isSaturated();
  36872. },
  36873. enumerable: true,
  36874. configurable: true
  36875. });
  36876. /**
  36877. * Enables contributions to the sliding window sample set
  36878. */
  36879. PerformanceMonitor.prototype.enable = function () {
  36880. this._enabled = true;
  36881. };
  36882. /**
  36883. * Disables contributions to the sliding window sample set
  36884. * Samples will not be interpolated over the disabled period
  36885. */
  36886. PerformanceMonitor.prototype.disable = function () {
  36887. this._enabled = false;
  36888. //clear last sample to avoid interpolating over the disabled period when next enabled
  36889. this._lastFrameTimeMs = null;
  36890. };
  36891. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36892. /**
  36893. * Returns true if sampling is enabled
  36894. * @return true if enabled
  36895. */
  36896. get: function () {
  36897. return this._enabled;
  36898. },
  36899. enumerable: true,
  36900. configurable: true
  36901. });
  36902. /**
  36903. * Resets performance monitor
  36904. */
  36905. PerformanceMonitor.prototype.reset = function () {
  36906. //clear last sample to avoid interpolating over the disabled period when next enabled
  36907. this._lastFrameTimeMs = null;
  36908. //wipe record
  36909. this._rollingFrameTime.reset();
  36910. };
  36911. return PerformanceMonitor;
  36912. }());
  36913. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36914. /**
  36915. * RollingAverage
  36916. *
  36917. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36918. */
  36919. var RollingAverage = /** @class */ (function () {
  36920. /**
  36921. * constructor
  36922. * @param length The number of samples required to saturate the sliding window
  36923. */
  36924. function RollingAverage(length) {
  36925. this._samples = new Array(length);
  36926. this.reset();
  36927. }
  36928. /**
  36929. * Adds a sample to the sample set
  36930. * @param v The sample value
  36931. */
  36932. RollingAverage.prototype.add = function (v) {
  36933. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36934. var delta;
  36935. //we need to check if we've already wrapped round
  36936. if (this.isSaturated()) {
  36937. //remove bottom of stack from mean
  36938. var bottomValue = this._samples[this._pos];
  36939. delta = bottomValue - this.average;
  36940. this.average -= delta / (this._sampleCount - 1);
  36941. this._m2 -= delta * (bottomValue - this.average);
  36942. }
  36943. else {
  36944. this._sampleCount++;
  36945. }
  36946. //add new value to mean
  36947. delta = v - this.average;
  36948. this.average += delta / (this._sampleCount);
  36949. this._m2 += delta * (v - this.average);
  36950. //set the new variance
  36951. this.variance = this._m2 / (this._sampleCount - 1);
  36952. this._samples[this._pos] = v;
  36953. this._pos++;
  36954. this._pos %= this._samples.length; //positive wrap around
  36955. };
  36956. /**
  36957. * Returns previously added values or null if outside of history or outside the sliding window domain
  36958. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36959. * @return Value previously recorded with add() or null if outside of range
  36960. */
  36961. RollingAverage.prototype.history = function (i) {
  36962. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36963. return 0;
  36964. }
  36965. var i0 = this._wrapPosition(this._pos - 1.0);
  36966. return this._samples[this._wrapPosition(i0 - i)];
  36967. };
  36968. /**
  36969. * Returns true if enough samples have been taken to completely fill the sliding window
  36970. * @return true if sample-set saturated
  36971. */
  36972. RollingAverage.prototype.isSaturated = function () {
  36973. return this._sampleCount >= this._samples.length;
  36974. };
  36975. /**
  36976. * Resets the rolling average (equivalent to 0 samples taken so far)
  36977. */
  36978. RollingAverage.prototype.reset = function () {
  36979. this.average = 0;
  36980. this.variance = 0;
  36981. this._sampleCount = 0;
  36982. this._pos = 0;
  36983. this._m2 = 0;
  36984. };
  36985. /**
  36986. * Wraps a value around the sample range boundaries
  36987. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36988. * @return Wrapped position in sample range
  36989. */
  36990. RollingAverage.prototype._wrapPosition = function (i) {
  36991. var max = this._samples.length;
  36992. return ((i % max) + max) % max;
  36993. };
  36994. return RollingAverage;
  36995. }());
  36996. BABYLON.RollingAverage = RollingAverage;
  36997. })(BABYLON || (BABYLON = {}));
  36998. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36999. var BABYLON;
  37000. (function (BABYLON) {
  37001. /**
  37002. * This groups together the common properties used for image processing either in direct forward pass
  37003. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37004. * or not.
  37005. */
  37006. var ImageProcessingConfiguration = /** @class */ (function () {
  37007. function ImageProcessingConfiguration() {
  37008. /**
  37009. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37010. */
  37011. this.colorCurves = new BABYLON.ColorCurves();
  37012. this._colorCurvesEnabled = false;
  37013. this._colorGradingEnabled = false;
  37014. this._colorGradingWithGreenDepth = true;
  37015. this._colorGradingBGR = true;
  37016. this._exposure = 1.0;
  37017. this._toneMappingEnabled = false;
  37018. this._contrast = 1.0;
  37019. /**
  37020. * Vignette stretch size.
  37021. */
  37022. this.vignetteStretch = 0;
  37023. /**
  37024. * Vignette centre X Offset.
  37025. */
  37026. this.vignetteCentreX = 0;
  37027. /**
  37028. * Vignette centre Y Offset.
  37029. */
  37030. this.vignetteCentreY = 0;
  37031. /**
  37032. * Vignette weight or intensity of the vignette effect.
  37033. */
  37034. this.vignetteWeight = 1.5;
  37035. /**
  37036. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37037. * if vignetteEnabled is set to true.
  37038. */
  37039. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37040. /**
  37041. * Camera field of view used by the Vignette effect.
  37042. */
  37043. this.vignetteCameraFov = 0.5;
  37044. this._grainEnabled = false;
  37045. this._grainIntensity = 30;
  37046. this._grainAnimated = false;
  37047. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37048. this._vignetteEnabled = false;
  37049. this._applyByPostProcess = false;
  37050. this._isEnabled = true;
  37051. /**
  37052. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37053. * @type {BABYLON.Observable}
  37054. */
  37055. this.onUpdateParameters = new BABYLON.Observable();
  37056. }
  37057. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37058. /**
  37059. * Gets wether the color curves effect is enabled.
  37060. */
  37061. get: function () {
  37062. return this._colorCurvesEnabled;
  37063. },
  37064. /**
  37065. * Sets wether the color curves effect is enabled.
  37066. */
  37067. set: function (value) {
  37068. if (this._colorCurvesEnabled === value) {
  37069. return;
  37070. }
  37071. this._colorCurvesEnabled = value;
  37072. this._updateParameters();
  37073. },
  37074. enumerable: true,
  37075. configurable: true
  37076. });
  37077. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37078. /**
  37079. * Gets wether the color grading effect is enabled.
  37080. */
  37081. get: function () {
  37082. return this._colorGradingEnabled;
  37083. },
  37084. /**
  37085. * Sets wether the color grading effect is enabled.
  37086. */
  37087. set: function (value) {
  37088. if (this._colorGradingEnabled === value) {
  37089. return;
  37090. }
  37091. this._colorGradingEnabled = value;
  37092. this._updateParameters();
  37093. },
  37094. enumerable: true,
  37095. configurable: true
  37096. });
  37097. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37098. /**
  37099. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37100. */
  37101. get: function () {
  37102. return this._colorGradingWithGreenDepth;
  37103. },
  37104. /**
  37105. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37106. */
  37107. set: function (value) {
  37108. if (this._colorGradingWithGreenDepth === value) {
  37109. return;
  37110. }
  37111. this._colorGradingWithGreenDepth = value;
  37112. this._updateParameters();
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37118. /**
  37119. * Gets wether the color grading texture contains BGR values.
  37120. */
  37121. get: function () {
  37122. return this._colorGradingBGR;
  37123. },
  37124. /**
  37125. * Sets wether the color grading texture contains BGR values.
  37126. */
  37127. set: function (value) {
  37128. if (this._colorGradingBGR === value) {
  37129. return;
  37130. }
  37131. this._colorGradingBGR = value;
  37132. this._updateParameters();
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37138. /**
  37139. * Gets the Exposure used in the effect.
  37140. */
  37141. get: function () {
  37142. return this._exposure;
  37143. },
  37144. /**
  37145. * Sets the Exposure used in the effect.
  37146. */
  37147. set: function (value) {
  37148. if (this._exposure === value) {
  37149. return;
  37150. }
  37151. this._exposure = value;
  37152. this._updateParameters();
  37153. },
  37154. enumerable: true,
  37155. configurable: true
  37156. });
  37157. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37158. /**
  37159. * Gets wether the tone mapping effect is enabled.
  37160. */
  37161. get: function () {
  37162. return this._toneMappingEnabled;
  37163. },
  37164. /**
  37165. * Sets wether the tone mapping effect is enabled.
  37166. */
  37167. set: function (value) {
  37168. if (this._toneMappingEnabled === value) {
  37169. return;
  37170. }
  37171. this._toneMappingEnabled = value;
  37172. this._updateParameters();
  37173. },
  37174. enumerable: true,
  37175. configurable: true
  37176. });
  37177. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37178. /**
  37179. * Gets the contrast used in the effect.
  37180. */
  37181. get: function () {
  37182. return this._contrast;
  37183. },
  37184. /**
  37185. * Sets the contrast used in the effect.
  37186. */
  37187. set: function (value) {
  37188. if (this._contrast === value) {
  37189. return;
  37190. }
  37191. this._contrast = value;
  37192. this._updateParameters();
  37193. },
  37194. enumerable: true,
  37195. configurable: true
  37196. });
  37197. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37198. /**
  37199. * If the grain effect should be enabled.
  37200. */
  37201. get: function () {
  37202. return this._grainEnabled;
  37203. },
  37204. set: function (value) {
  37205. if (this._grainEnabled === value) {
  37206. return;
  37207. }
  37208. this._grainEnabled = value;
  37209. this._updateParameters();
  37210. },
  37211. enumerable: true,
  37212. configurable: true
  37213. });
  37214. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37215. /**
  37216. * Amount of grain to be applied by the grain effect.
  37217. */
  37218. get: function () {
  37219. return this._grainIntensity;
  37220. },
  37221. set: function (value) {
  37222. if (this._grainIntensity === value) {
  37223. return;
  37224. }
  37225. this._grainIntensity = value;
  37226. },
  37227. enumerable: true,
  37228. configurable: true
  37229. });
  37230. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37231. /**
  37232. * If the grain effect should be animated.
  37233. */
  37234. get: function () {
  37235. return this._grainAnimated;
  37236. },
  37237. set: function (value) {
  37238. if (this._grainAnimated === value) {
  37239. return;
  37240. }
  37241. this._grainAnimated = value;
  37242. this._updateParameters();
  37243. },
  37244. enumerable: true,
  37245. configurable: true
  37246. });
  37247. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37248. /**
  37249. * Gets the vignette blend mode allowing different kind of effect.
  37250. */
  37251. get: function () {
  37252. return this._vignetteBlendMode;
  37253. },
  37254. /**
  37255. * Sets the vignette blend mode allowing different kind of effect.
  37256. */
  37257. set: function (value) {
  37258. if (this._vignetteBlendMode === value) {
  37259. return;
  37260. }
  37261. this._vignetteBlendMode = value;
  37262. this._updateParameters();
  37263. },
  37264. enumerable: true,
  37265. configurable: true
  37266. });
  37267. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37268. /**
  37269. * Gets wether the vignette effect is enabled.
  37270. */
  37271. get: function () {
  37272. return this._vignetteEnabled;
  37273. },
  37274. /**
  37275. * Sets wether the vignette effect is enabled.
  37276. */
  37277. set: function (value) {
  37278. if (this._vignetteEnabled === value) {
  37279. return;
  37280. }
  37281. this._vignetteEnabled = value;
  37282. this._updateParameters();
  37283. },
  37284. enumerable: true,
  37285. configurable: true
  37286. });
  37287. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37288. /**
  37289. * Gets wether the image processing is applied through a post process or not.
  37290. */
  37291. get: function () {
  37292. return this._applyByPostProcess;
  37293. },
  37294. /**
  37295. * Sets wether the image processing is applied through a post process or not.
  37296. */
  37297. set: function (value) {
  37298. if (this._applyByPostProcess === value) {
  37299. return;
  37300. }
  37301. this._applyByPostProcess = value;
  37302. this._updateParameters();
  37303. },
  37304. enumerable: true,
  37305. configurable: true
  37306. });
  37307. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37308. /**
  37309. * Gets wether the image processing is enabled or not.
  37310. */
  37311. get: function () {
  37312. return this._isEnabled;
  37313. },
  37314. /**
  37315. * Sets wether the image processing is enabled or not.
  37316. */
  37317. set: function (value) {
  37318. if (this._isEnabled === value) {
  37319. return;
  37320. }
  37321. this._isEnabled = value;
  37322. this._updateParameters();
  37323. },
  37324. enumerable: true,
  37325. configurable: true
  37326. });
  37327. /**
  37328. * Method called each time the image processing information changes requires to recompile the effect.
  37329. */
  37330. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37331. this.onUpdateParameters.notifyObservers(this);
  37332. };
  37333. ImageProcessingConfiguration.prototype.getClassName = function () {
  37334. return "ImageProcessingConfiguration";
  37335. };
  37336. /**
  37337. * Prepare the list of uniforms associated with the Image Processing effects.
  37338. * @param uniformsList The list of uniforms used in the effect
  37339. * @param defines the list of defines currently in use
  37340. */
  37341. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37342. if (defines.EXPOSURE) {
  37343. uniforms.push("exposureLinear");
  37344. }
  37345. if (defines.CONTRAST) {
  37346. uniforms.push("contrast");
  37347. }
  37348. if (defines.COLORGRADING) {
  37349. uniforms.push("colorTransformSettings");
  37350. }
  37351. if (defines.VIGNETTE) {
  37352. uniforms.push("vInverseScreenSize");
  37353. uniforms.push("vignetteSettings1");
  37354. uniforms.push("vignetteSettings2");
  37355. }
  37356. if (defines.COLORCURVES) {
  37357. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37358. }
  37359. if (defines.GRAIN) {
  37360. uniforms.push("grainVarianceAmount");
  37361. uniforms.push("grainAnimatedSeed");
  37362. }
  37363. };
  37364. /**
  37365. * Prepare the list of samplers associated with the Image Processing effects.
  37366. * @param uniformsList The list of uniforms used in the effect
  37367. * @param defines the list of defines currently in use
  37368. */
  37369. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37370. if (defines.COLORGRADING) {
  37371. samplersList.push("txColorTransform");
  37372. }
  37373. };
  37374. /**
  37375. * Prepare the list of defines associated to the shader.
  37376. * @param defines the list of defines to complete
  37377. */
  37378. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37379. if (forPostProcess === void 0) { forPostProcess = false; }
  37380. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37381. defines.VIGNETTE = false;
  37382. defines.TONEMAPPING = false;
  37383. defines.CONTRAST = false;
  37384. defines.EXPOSURE = false;
  37385. defines.COLORCURVES = false;
  37386. defines.COLORGRADING = false;
  37387. defines.COLORGRADING3D = false;
  37388. defines.IMAGEPROCESSING = false;
  37389. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37390. return;
  37391. }
  37392. defines.VIGNETTE = this.vignetteEnabled;
  37393. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37394. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37395. defines.TONEMAPPING = this.toneMappingEnabled;
  37396. defines.CONTRAST = (this.contrast !== 1.0);
  37397. defines.EXPOSURE = (this.exposure !== 1.0);
  37398. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37399. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37400. if (defines.COLORGRADING) {
  37401. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37402. }
  37403. else {
  37404. defines.COLORGRADING3D = false;
  37405. }
  37406. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37407. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37408. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37409. defines.GRAIN = this.grainEnabled;
  37410. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37411. };
  37412. /**
  37413. * Returns true if all the image processing information are ready.
  37414. */
  37415. ImageProcessingConfiguration.prototype.isReady = function () {
  37416. // Color Grading texure can not be none blocking.
  37417. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37418. };
  37419. /**
  37420. * Binds the image processing to the shader.
  37421. * @param effect The effect to bind to
  37422. */
  37423. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37424. if (aspectRatio === void 0) { aspectRatio = 1; }
  37425. // Color Curves
  37426. if (this._colorCurvesEnabled && this.colorCurves) {
  37427. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37428. }
  37429. // Vignette
  37430. if (this._vignetteEnabled) {
  37431. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37432. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37433. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37434. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37435. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37436. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37437. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37438. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37439. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37440. var vignettePower = -2.0 * this.vignetteWeight;
  37441. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37442. }
  37443. // Exposure
  37444. effect.setFloat("exposureLinear", this.exposure);
  37445. // Contrast
  37446. effect.setFloat("contrast", this.contrast);
  37447. // Color transform settings
  37448. if (this.colorGradingTexture) {
  37449. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37450. var textureSize = this.colorGradingTexture.getSize().height;
  37451. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37452. 0.5 / textureSize, // textureOffset
  37453. textureSize, // textureSize
  37454. this.colorGradingTexture.level // weight
  37455. );
  37456. }
  37457. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37458. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37459. };
  37460. /**
  37461. * Clones the current image processing instance.
  37462. * @return The cloned image processing
  37463. */
  37464. ImageProcessingConfiguration.prototype.clone = function () {
  37465. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37466. };
  37467. /**
  37468. * Serializes the current image processing instance to a json representation.
  37469. * @return a JSON representation
  37470. */
  37471. ImageProcessingConfiguration.prototype.serialize = function () {
  37472. return BABYLON.SerializationHelper.Serialize(this);
  37473. };
  37474. /**
  37475. * Parses the image processing from a json representation.
  37476. * @param source the JSON source to parse
  37477. * @return The parsed image processing
  37478. */
  37479. ImageProcessingConfiguration.Parse = function (source) {
  37480. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37481. };
  37482. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37483. /**
  37484. * Used to apply the vignette as a mix with the pixel color.
  37485. */
  37486. get: function () {
  37487. return this._VIGNETTEMODE_MULTIPLY;
  37488. },
  37489. enumerable: true,
  37490. configurable: true
  37491. });
  37492. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37493. /**
  37494. * Used to apply the vignette as a replacement of the pixel color.
  37495. */
  37496. get: function () {
  37497. return this._VIGNETTEMODE_OPAQUE;
  37498. },
  37499. enumerable: true,
  37500. configurable: true
  37501. });
  37502. // Static constants associated to the image processing.
  37503. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37504. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37505. __decorate([
  37506. BABYLON.serializeAsColorCurves()
  37507. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37508. __decorate([
  37509. BABYLON.serialize()
  37510. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37511. __decorate([
  37512. BABYLON.serializeAsTexture()
  37513. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37514. __decorate([
  37515. BABYLON.serialize()
  37516. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37517. __decorate([
  37518. BABYLON.serialize()
  37519. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37520. __decorate([
  37521. BABYLON.serialize()
  37522. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37523. __decorate([
  37524. BABYLON.serialize()
  37525. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37526. __decorate([
  37527. BABYLON.serialize()
  37528. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37529. __decorate([
  37530. BABYLON.serialize()
  37531. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37532. __decorate([
  37533. BABYLON.serialize()
  37534. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37535. __decorate([
  37536. BABYLON.serialize()
  37537. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37538. __decorate([
  37539. BABYLON.serialize()
  37540. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37541. __decorate([
  37542. BABYLON.serialize()
  37543. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37544. __decorate([
  37545. BABYLON.serializeAsColor4()
  37546. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37547. __decorate([
  37548. BABYLON.serialize()
  37549. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37550. __decorate([
  37551. BABYLON.serialize()
  37552. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37553. __decorate([
  37554. BABYLON.serialize()
  37555. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37556. __decorate([
  37557. BABYLON.serialize()
  37558. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37559. __decorate([
  37560. BABYLON.serialize()
  37561. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37562. __decorate([
  37563. BABYLON.serialize()
  37564. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37565. __decorate([
  37566. BABYLON.serialize()
  37567. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37568. __decorate([
  37569. BABYLON.serialize()
  37570. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37571. return ImageProcessingConfiguration;
  37572. }());
  37573. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37574. })(BABYLON || (BABYLON = {}));
  37575. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37576. var BABYLON;
  37577. (function (BABYLON) {
  37578. /**
  37579. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37580. * It can help converting any input color in a desired output one. This can then be used to create effects
  37581. * from sepia, black and white to sixties or futuristic rendering...
  37582. *
  37583. * The only supported format is currently 3dl.
  37584. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37585. */
  37586. var ColorGradingTexture = /** @class */ (function (_super) {
  37587. __extends(ColorGradingTexture, _super);
  37588. /**
  37589. * Instantiates a ColorGradingTexture from the following parameters.
  37590. *
  37591. * @param url The location of the color gradind data (currently only supporting 3dl)
  37592. * @param scene The scene the texture will be used in
  37593. */
  37594. function ColorGradingTexture(url, scene) {
  37595. var _this = _super.call(this, scene) || this;
  37596. if (!url) {
  37597. return _this;
  37598. }
  37599. _this._engine = scene.getEngine();
  37600. _this._textureMatrix = BABYLON.Matrix.Identity();
  37601. _this.name = url;
  37602. _this.url = url;
  37603. _this.hasAlpha = false;
  37604. _this.isCube = false;
  37605. _this.is3D = _this._engine.webGLVersion > 1;
  37606. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37607. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37608. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37609. _this.anisotropicFilteringLevel = 1;
  37610. _this._texture = _this._getFromCache(url, true);
  37611. if (!_this._texture) {
  37612. if (!scene.useDelayedTextureLoading) {
  37613. _this.loadTexture();
  37614. }
  37615. else {
  37616. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37617. }
  37618. }
  37619. return _this;
  37620. }
  37621. /**
  37622. * Returns the texture matrix used in most of the material.
  37623. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37624. */
  37625. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37626. return this._textureMatrix;
  37627. };
  37628. /**
  37629. * Occurs when the file being loaded is a .3dl LUT file.
  37630. */
  37631. ColorGradingTexture.prototype.load3dlTexture = function () {
  37632. var engine = this._engine;
  37633. var texture;
  37634. if (engine.webGLVersion === 1) {
  37635. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37636. }
  37637. else {
  37638. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37639. }
  37640. this._texture = texture;
  37641. var callback = function (text) {
  37642. if (typeof text !== "string") {
  37643. return;
  37644. }
  37645. var data = null;
  37646. var tempData = null;
  37647. var line;
  37648. var lines = text.split('\n');
  37649. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37650. var maxColor = 0;
  37651. for (var i = 0; i < lines.length; i++) {
  37652. line = lines[i];
  37653. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37654. continue;
  37655. if (line.indexOf('#') === 0)
  37656. continue;
  37657. var words = line.split(" ");
  37658. if (size === 0) {
  37659. // Number of space + one
  37660. size = words.length;
  37661. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37662. tempData = new Float32Array(size * size * size * 4);
  37663. continue;
  37664. }
  37665. if (size != 0) {
  37666. var r = Math.max(parseInt(words[0]), 0);
  37667. var g = Math.max(parseInt(words[1]), 0);
  37668. var b = Math.max(parseInt(words[2]), 0);
  37669. maxColor = Math.max(r, maxColor);
  37670. maxColor = Math.max(g, maxColor);
  37671. maxColor = Math.max(b, maxColor);
  37672. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37673. if (tempData) {
  37674. tempData[pixelStorageIndex + 0] = r;
  37675. tempData[pixelStorageIndex + 1] = g;
  37676. tempData[pixelStorageIndex + 2] = b;
  37677. }
  37678. pixelIndexSlice++;
  37679. if (pixelIndexSlice % size == 0) {
  37680. pixelIndexH++;
  37681. pixelIndexSlice = 0;
  37682. if (pixelIndexH % size == 0) {
  37683. pixelIndexW++;
  37684. pixelIndexH = 0;
  37685. }
  37686. }
  37687. }
  37688. }
  37689. if (tempData && data) {
  37690. for (var i = 0; i < tempData.length; i++) {
  37691. if (i > 0 && (i + 1) % 4 === 0) {
  37692. data[i] = 255;
  37693. }
  37694. else {
  37695. var value = tempData[i];
  37696. data[i] = (value / maxColor * 255);
  37697. }
  37698. }
  37699. }
  37700. if (texture.is3D) {
  37701. texture.updateSize(size, size, size);
  37702. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37703. }
  37704. else {
  37705. texture.updateSize(size * size, size);
  37706. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37707. }
  37708. };
  37709. var scene = this.getScene();
  37710. if (scene) {
  37711. scene._loadFile(this.url, callback);
  37712. }
  37713. else {
  37714. this._engine._loadFile(this.url, callback);
  37715. }
  37716. return this._texture;
  37717. };
  37718. /**
  37719. * Starts the loading process of the texture.
  37720. */
  37721. ColorGradingTexture.prototype.loadTexture = function () {
  37722. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37723. this.load3dlTexture();
  37724. }
  37725. };
  37726. /**
  37727. * Clones the color gradind texture.
  37728. */
  37729. ColorGradingTexture.prototype.clone = function () {
  37730. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37731. // Base texture
  37732. newTexture.level = this.level;
  37733. return newTexture;
  37734. };
  37735. /**
  37736. * Called during delayed load for textures.
  37737. */
  37738. ColorGradingTexture.prototype.delayLoad = function () {
  37739. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37740. return;
  37741. }
  37742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37743. this._texture = this._getFromCache(this.url, true);
  37744. if (!this._texture) {
  37745. this.loadTexture();
  37746. }
  37747. };
  37748. /**
  37749. * Parses a color grading texture serialized by Babylon.
  37750. * @param parsedTexture The texture information being parsedTexture
  37751. * @param scene The scene to load the texture in
  37752. * @param rootUrl The root url of the data assets to load
  37753. * @return A color gradind texture
  37754. */
  37755. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37756. var texture = null;
  37757. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37758. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37759. texture.name = parsedTexture.name;
  37760. texture.level = parsedTexture.level;
  37761. }
  37762. return texture;
  37763. };
  37764. /**
  37765. * Serializes the LUT texture to json format.
  37766. */
  37767. ColorGradingTexture.prototype.serialize = function () {
  37768. if (!this.name) {
  37769. return null;
  37770. }
  37771. var serializationObject = {};
  37772. serializationObject.name = this.name;
  37773. serializationObject.level = this.level;
  37774. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37775. return serializationObject;
  37776. };
  37777. /**
  37778. * Empty line regex stored for GC.
  37779. */
  37780. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37781. return ColorGradingTexture;
  37782. }(BABYLON.BaseTexture));
  37783. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37784. })(BABYLON || (BABYLON = {}));
  37785. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37786. var BABYLON;
  37787. (function (BABYLON) {
  37788. /**
  37789. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37790. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37791. * 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;
  37792. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37793. */
  37794. var ColorCurves = /** @class */ (function () {
  37795. function ColorCurves() {
  37796. this._dirty = true;
  37797. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37798. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37799. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37800. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37801. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37802. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37803. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37804. this._globalHue = 30;
  37805. this._globalDensity = 0;
  37806. this._globalSaturation = 0;
  37807. this._globalExposure = 0;
  37808. this._highlightsHue = 30;
  37809. this._highlightsDensity = 0;
  37810. this._highlightsSaturation = 0;
  37811. this._highlightsExposure = 0;
  37812. this._midtonesHue = 30;
  37813. this._midtonesDensity = 0;
  37814. this._midtonesSaturation = 0;
  37815. this._midtonesExposure = 0;
  37816. this._shadowsHue = 30;
  37817. this._shadowsDensity = 0;
  37818. this._shadowsSaturation = 0;
  37819. this._shadowsExposure = 0;
  37820. }
  37821. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37822. /**
  37823. * Gets the global Hue value.
  37824. * 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).
  37825. */
  37826. get: function () {
  37827. return this._globalHue;
  37828. },
  37829. /**
  37830. * Sets the global Hue value.
  37831. * 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).
  37832. */
  37833. set: function (value) {
  37834. this._globalHue = value;
  37835. this._dirty = true;
  37836. },
  37837. enumerable: true,
  37838. configurable: true
  37839. });
  37840. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37841. /**
  37842. * Gets the global Density value.
  37843. * 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.
  37844. * Values less than zero provide a filter of opposite hue.
  37845. */
  37846. get: function () {
  37847. return this._globalDensity;
  37848. },
  37849. /**
  37850. * Sets the global Density value.
  37851. * 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.
  37852. * Values less than zero provide a filter of opposite hue.
  37853. */
  37854. set: function (value) {
  37855. this._globalDensity = value;
  37856. this._dirty = true;
  37857. },
  37858. enumerable: true,
  37859. configurable: true
  37860. });
  37861. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37862. /**
  37863. * Gets the global Saturation value.
  37864. * 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.
  37865. */
  37866. get: function () {
  37867. return this._globalSaturation;
  37868. },
  37869. /**
  37870. * Sets the global Saturation value.
  37871. * 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.
  37872. */
  37873. set: function (value) {
  37874. this._globalSaturation = value;
  37875. this._dirty = true;
  37876. },
  37877. enumerable: true,
  37878. configurable: true
  37879. });
  37880. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37881. /**
  37882. * Gets the highlights Hue value.
  37883. * 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).
  37884. */
  37885. get: function () {
  37886. return this._highlightsHue;
  37887. },
  37888. /**
  37889. * Sets the highlights Hue value.
  37890. * 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).
  37891. */
  37892. set: function (value) {
  37893. this._highlightsHue = value;
  37894. this._dirty = true;
  37895. },
  37896. enumerable: true,
  37897. configurable: true
  37898. });
  37899. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37900. /**
  37901. * Gets the highlights Density value.
  37902. * 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.
  37903. * Values less than zero provide a filter of opposite hue.
  37904. */
  37905. get: function () {
  37906. return this._highlightsDensity;
  37907. },
  37908. /**
  37909. * Sets the highlights Density value.
  37910. * 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.
  37911. * Values less than zero provide a filter of opposite hue.
  37912. */
  37913. set: function (value) {
  37914. this._highlightsDensity = value;
  37915. this._dirty = true;
  37916. },
  37917. enumerable: true,
  37918. configurable: true
  37919. });
  37920. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37921. /**
  37922. * Gets the highlights Saturation value.
  37923. * 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.
  37924. */
  37925. get: function () {
  37926. return this._highlightsSaturation;
  37927. },
  37928. /**
  37929. * Sets the highlights Saturation value.
  37930. * 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.
  37931. */
  37932. set: function (value) {
  37933. this._highlightsSaturation = value;
  37934. this._dirty = true;
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37940. /**
  37941. * Gets the highlights Exposure value.
  37942. * 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.
  37943. */
  37944. get: function () {
  37945. return this._highlightsExposure;
  37946. },
  37947. /**
  37948. * Sets the highlights Exposure value.
  37949. * 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.
  37950. */
  37951. set: function (value) {
  37952. this._highlightsExposure = value;
  37953. this._dirty = true;
  37954. },
  37955. enumerable: true,
  37956. configurable: true
  37957. });
  37958. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37959. /**
  37960. * Gets the midtones Hue value.
  37961. * 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).
  37962. */
  37963. get: function () {
  37964. return this._midtonesHue;
  37965. },
  37966. /**
  37967. * Sets the midtones Hue value.
  37968. * 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).
  37969. */
  37970. set: function (value) {
  37971. this._midtonesHue = value;
  37972. this._dirty = true;
  37973. },
  37974. enumerable: true,
  37975. configurable: true
  37976. });
  37977. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37978. /**
  37979. * Gets the midtones Density value.
  37980. * 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.
  37981. * Values less than zero provide a filter of opposite hue.
  37982. */
  37983. get: function () {
  37984. return this._midtonesDensity;
  37985. },
  37986. /**
  37987. * Sets the midtones Density value.
  37988. * 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.
  37989. * Values less than zero provide a filter of opposite hue.
  37990. */
  37991. set: function (value) {
  37992. this._midtonesDensity = value;
  37993. this._dirty = true;
  37994. },
  37995. enumerable: true,
  37996. configurable: true
  37997. });
  37998. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37999. /**
  38000. * Gets the midtones Saturation value.
  38001. * 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.
  38002. */
  38003. get: function () {
  38004. return this._midtonesSaturation;
  38005. },
  38006. /**
  38007. * Sets the midtones Saturation value.
  38008. * 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.
  38009. */
  38010. set: function (value) {
  38011. this._midtonesSaturation = value;
  38012. this._dirty = true;
  38013. },
  38014. enumerable: true,
  38015. configurable: true
  38016. });
  38017. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38018. /**
  38019. * Gets the midtones Exposure value.
  38020. * 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.
  38021. */
  38022. get: function () {
  38023. return this._midtonesExposure;
  38024. },
  38025. /**
  38026. * Sets the midtones Exposure value.
  38027. * 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.
  38028. */
  38029. set: function (value) {
  38030. this._midtonesExposure = value;
  38031. this._dirty = true;
  38032. },
  38033. enumerable: true,
  38034. configurable: true
  38035. });
  38036. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38037. /**
  38038. * Gets the shadows Hue value.
  38039. * 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).
  38040. */
  38041. get: function () {
  38042. return this._shadowsHue;
  38043. },
  38044. /**
  38045. * Sets the shadows Hue value.
  38046. * 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).
  38047. */
  38048. set: function (value) {
  38049. this._shadowsHue = value;
  38050. this._dirty = true;
  38051. },
  38052. enumerable: true,
  38053. configurable: true
  38054. });
  38055. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38056. /**
  38057. * Gets the shadows Density value.
  38058. * 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.
  38059. * Values less than zero provide a filter of opposite hue.
  38060. */
  38061. get: function () {
  38062. return this._shadowsDensity;
  38063. },
  38064. /**
  38065. * Sets the shadows Density value.
  38066. * 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.
  38067. * Values less than zero provide a filter of opposite hue.
  38068. */
  38069. set: function (value) {
  38070. this._shadowsDensity = value;
  38071. this._dirty = true;
  38072. },
  38073. enumerable: true,
  38074. configurable: true
  38075. });
  38076. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38077. /**
  38078. * Gets the shadows Saturation value.
  38079. * 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.
  38080. */
  38081. get: function () {
  38082. return this._shadowsSaturation;
  38083. },
  38084. /**
  38085. * Sets the shadows Saturation value.
  38086. * 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.
  38087. */
  38088. set: function (value) {
  38089. this._shadowsSaturation = value;
  38090. this._dirty = true;
  38091. },
  38092. enumerable: true,
  38093. configurable: true
  38094. });
  38095. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38096. /**
  38097. * Gets the shadows Exposure value.
  38098. * 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.
  38099. */
  38100. get: function () {
  38101. return this._shadowsExposure;
  38102. },
  38103. /**
  38104. * Sets the shadows Exposure value.
  38105. * 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.
  38106. */
  38107. set: function (value) {
  38108. this._shadowsExposure = value;
  38109. this._dirty = true;
  38110. },
  38111. enumerable: true,
  38112. configurable: true
  38113. });
  38114. ColorCurves.prototype.getClassName = function () {
  38115. return "ColorCurves";
  38116. };
  38117. /**
  38118. * Binds the color curves to the shader.
  38119. * @param colorCurves The color curve to bind
  38120. * @param effect The effect to bind to
  38121. */
  38122. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38123. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38124. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38125. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38126. if (colorCurves._dirty) {
  38127. colorCurves._dirty = false;
  38128. // Fill in global info.
  38129. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38130. // Compute highlights info.
  38131. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38132. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38133. // Compute midtones info.
  38134. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38135. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38136. // Compute shadows info.
  38137. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38138. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38139. // Compute deltas (neutral is midtones).
  38140. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38141. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38142. }
  38143. if (effect) {
  38144. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38145. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38146. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38147. }
  38148. };
  38149. /**
  38150. * Prepare the list of uniforms associated with the ColorCurves effects.
  38151. * @param uniformsList The list of uniforms used in the effect
  38152. */
  38153. ColorCurves.PrepareUniforms = function (uniformsList) {
  38154. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38155. };
  38156. /**
  38157. * Returns color grading data based on a hue, density, saturation and exposure value.
  38158. * @param filterHue The hue of the color filter.
  38159. * @param filterDensity The density of the color filter.
  38160. * @param saturation The saturation.
  38161. * @param exposure The exposure.
  38162. * @param result The result data container.
  38163. */
  38164. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38165. if (hue == null) {
  38166. return;
  38167. }
  38168. hue = ColorCurves.clamp(hue, 0, 360);
  38169. density = ColorCurves.clamp(density, -100, 100);
  38170. saturation = ColorCurves.clamp(saturation, -100, 100);
  38171. exposure = ColorCurves.clamp(exposure, -100, 100);
  38172. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38173. // so that the maximum filter density is only 50% control. This provides fine control
  38174. // for small values and reasonable range.
  38175. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38176. density *= 0.5;
  38177. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38178. if (density < 0) {
  38179. density *= -1;
  38180. hue = (hue + 180) % 360;
  38181. }
  38182. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38183. result.scaleToRef(2, result);
  38184. result.a = 1 + 0.01 * saturation;
  38185. };
  38186. /**
  38187. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38188. * @param value The input slider value in range [-100,100].
  38189. * @returns Adjusted value.
  38190. */
  38191. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38192. value /= 100;
  38193. var x = Math.abs(value);
  38194. x = Math.pow(x, 2);
  38195. if (value < 0) {
  38196. x *= -1;
  38197. }
  38198. x *= 100;
  38199. return x;
  38200. };
  38201. /**
  38202. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38203. * @param hue The hue (H) input.
  38204. * @param saturation The saturation (S) input.
  38205. * @param brightness The brightness (B) input.
  38206. * @result An RGBA color represented as Vector4.
  38207. */
  38208. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38209. var h = ColorCurves.clamp(hue, 0, 360);
  38210. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38211. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38212. if (s === 0) {
  38213. result.r = v;
  38214. result.g = v;
  38215. result.b = v;
  38216. }
  38217. else {
  38218. // sector 0 to 5
  38219. h /= 60;
  38220. var i = Math.floor(h);
  38221. // fractional part of h
  38222. var f = h - i;
  38223. var p = v * (1 - s);
  38224. var q = v * (1 - s * f);
  38225. var t = v * (1 - s * (1 - f));
  38226. switch (i) {
  38227. case 0:
  38228. result.r = v;
  38229. result.g = t;
  38230. result.b = p;
  38231. break;
  38232. case 1:
  38233. result.r = q;
  38234. result.g = v;
  38235. result.b = p;
  38236. break;
  38237. case 2:
  38238. result.r = p;
  38239. result.g = v;
  38240. result.b = t;
  38241. break;
  38242. case 3:
  38243. result.r = p;
  38244. result.g = q;
  38245. result.b = v;
  38246. break;
  38247. case 4:
  38248. result.r = t;
  38249. result.g = p;
  38250. result.b = v;
  38251. break;
  38252. default:// case 5:
  38253. result.r = v;
  38254. result.g = p;
  38255. result.b = q;
  38256. break;
  38257. }
  38258. }
  38259. result.a = 1;
  38260. };
  38261. /**
  38262. * Returns a value clamped between min and max
  38263. * @param value The value to clamp
  38264. * @param min The minimum of value
  38265. * @param max The maximum of value
  38266. * @returns The clamped value.
  38267. */
  38268. ColorCurves.clamp = function (value, min, max) {
  38269. return Math.min(Math.max(value, min), max);
  38270. };
  38271. /**
  38272. * Clones the current color curve instance.
  38273. * @return The cloned curves
  38274. */
  38275. ColorCurves.prototype.clone = function () {
  38276. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38277. };
  38278. /**
  38279. * Serializes the current color curve instance to a json representation.
  38280. * @return a JSON representation
  38281. */
  38282. ColorCurves.prototype.serialize = function () {
  38283. return BABYLON.SerializationHelper.Serialize(this);
  38284. };
  38285. /**
  38286. * Parses the color curve from a json representation.
  38287. * @param source the JSON source to parse
  38288. * @return The parsed curves
  38289. */
  38290. ColorCurves.Parse = function (source) {
  38291. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38292. };
  38293. __decorate([
  38294. BABYLON.serialize()
  38295. ], ColorCurves.prototype, "_globalHue", void 0);
  38296. __decorate([
  38297. BABYLON.serialize()
  38298. ], ColorCurves.prototype, "_globalDensity", void 0);
  38299. __decorate([
  38300. BABYLON.serialize()
  38301. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38302. __decorate([
  38303. BABYLON.serialize()
  38304. ], ColorCurves.prototype, "_globalExposure", void 0);
  38305. __decorate([
  38306. BABYLON.serialize()
  38307. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38308. __decorate([
  38309. BABYLON.serialize()
  38310. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38311. __decorate([
  38312. BABYLON.serialize()
  38313. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38314. __decorate([
  38315. BABYLON.serialize()
  38316. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38317. __decorate([
  38318. BABYLON.serialize()
  38319. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38320. __decorate([
  38321. BABYLON.serialize()
  38322. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38323. __decorate([
  38324. BABYLON.serialize()
  38325. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38326. __decorate([
  38327. BABYLON.serialize()
  38328. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38329. return ColorCurves;
  38330. }());
  38331. BABYLON.ColorCurves = ColorCurves;
  38332. })(BABYLON || (BABYLON = {}));
  38333. //# sourceMappingURL=babylon.colorCurves.js.map
  38334. //# sourceMappingURL=babylon.behavior.js.map
  38335. var BABYLON;
  38336. (function (BABYLON) {
  38337. /**
  38338. * "Static Class" containing the most commonly used helper while dealing with material for
  38339. * rendering purpose.
  38340. *
  38341. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38342. *
  38343. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38344. */
  38345. var MaterialHelper = /** @class */ (function () {
  38346. function MaterialHelper() {
  38347. }
  38348. /**
  38349. * Bind the current view position to an effect.
  38350. * @param effect The effect to be bound
  38351. * @param scene The scene the eyes position is used from
  38352. */
  38353. MaterialHelper.BindEyePosition = function (effect, scene) {
  38354. if (scene._forcedViewPosition) {
  38355. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38356. return;
  38357. }
  38358. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38359. };
  38360. /**
  38361. * Helps preparing the defines values about the UVs in used in the effect.
  38362. * UVs are shared as much as we can accross chanels in the shaders.
  38363. * @param texture The texture we are preparing the UVs for
  38364. * @param defines The defines to update
  38365. * @param key The chanel key "diffuse", "specular"... used in the shader
  38366. */
  38367. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38368. defines._needUVs = true;
  38369. defines[key] = true;
  38370. if (texture.getTextureMatrix().isIdentity(true)) {
  38371. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38372. if (texture.coordinatesIndex === 0) {
  38373. defines["MAINUV1"] = true;
  38374. }
  38375. else {
  38376. defines["MAINUV2"] = true;
  38377. }
  38378. }
  38379. else {
  38380. defines[key + "DIRECTUV"] = 0;
  38381. }
  38382. };
  38383. /**
  38384. * Binds a texture matrix value to its corrsponding uniform
  38385. * @param texture The texture to bind the matrix for
  38386. * @param uniformBuffer The uniform buffer receivin the data
  38387. * @param key The chanel key "diffuse", "specular"... used in the shader
  38388. */
  38389. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38390. var matrix = texture.getTextureMatrix();
  38391. if (!matrix.isIdentity(true)) {
  38392. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38393. }
  38394. };
  38395. /**
  38396. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38397. * @param mesh defines the current mesh
  38398. * @param scene defines the current scene
  38399. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38400. * @param pointsCloud defines if point cloud rendering has to be turned on
  38401. * @param fogEnabled defines if fog has to be turned on
  38402. * @param alphaTest defines if alpha testing has to be turned on
  38403. * @param defines defines the current list of defines
  38404. */
  38405. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38406. if (defines._areMiscDirty) {
  38407. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38408. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38409. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38410. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38411. defines["ALPHATEST"] = alphaTest;
  38412. }
  38413. };
  38414. /**
  38415. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38416. * @param scene defines the current scene
  38417. * @param engine defines the current engine
  38418. * @param defines specifies the list of active defines
  38419. * @param useInstances defines if instances have to be turned on
  38420. * @param useClipPlane defines if clip plane have to be turned on
  38421. */
  38422. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38423. if (useClipPlane === void 0) { useClipPlane = null; }
  38424. var changed = false;
  38425. if (useClipPlane == null) {
  38426. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38427. }
  38428. if (defines["CLIPPLANE"] !== useClipPlane) {
  38429. defines["CLIPPLANE"] = useClipPlane;
  38430. changed = true;
  38431. }
  38432. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38433. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38434. changed = true;
  38435. }
  38436. if (defines["INSTANCES"] !== useInstances) {
  38437. defines["INSTANCES"] = useInstances;
  38438. changed = true;
  38439. }
  38440. if (changed) {
  38441. defines.markAsUnprocessed();
  38442. }
  38443. };
  38444. /**
  38445. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38446. * @param mesh The mesh containing the geometry data we will draw
  38447. * @param defines The defines to update
  38448. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38449. * @param useBones Precise whether bones should be used or not (override mesh info)
  38450. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38451. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38452. * @returns false if defines are considered not dirty and have not been checked
  38453. */
  38454. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38455. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38456. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38457. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38458. return false;
  38459. }
  38460. defines._normals = defines._needNormals;
  38461. defines._uvs = defines._needUVs;
  38462. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38463. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38464. defines["TANGENT"] = true;
  38465. }
  38466. if (defines._needUVs) {
  38467. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38468. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38469. }
  38470. else {
  38471. defines["UV1"] = false;
  38472. defines["UV2"] = false;
  38473. }
  38474. if (useVertexColor) {
  38475. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38476. defines["VERTEXCOLOR"] = hasVertexColors;
  38477. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38478. }
  38479. if (useBones) {
  38480. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38481. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38482. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38483. }
  38484. else {
  38485. defines["NUM_BONE_INFLUENCERS"] = 0;
  38486. defines["BonesPerMesh"] = 0;
  38487. }
  38488. }
  38489. if (useMorphTargets) {
  38490. var manager = mesh.morphTargetManager;
  38491. if (manager) {
  38492. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38493. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38494. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38495. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38496. }
  38497. else {
  38498. defines["MORPHTARGETS_TANGENT"] = false;
  38499. defines["MORPHTARGETS_NORMAL"] = false;
  38500. defines["MORPHTARGETS"] = false;
  38501. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38502. }
  38503. }
  38504. return true;
  38505. };
  38506. /**
  38507. * Prepares the defines related to the light information passed in parameter
  38508. * @param scene The scene we are intending to draw
  38509. * @param mesh The mesh the effect is compiling for
  38510. * @param defines The defines to update
  38511. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38512. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38513. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38514. * @returns true if normals will be required for the rest of the effect
  38515. */
  38516. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38517. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38518. if (disableLighting === void 0) { disableLighting = false; }
  38519. if (!defines._areLightsDirty) {
  38520. return defines._needNormals;
  38521. }
  38522. var lightIndex = 0;
  38523. var needNormals = false;
  38524. var needRebuild = false;
  38525. var lightmapMode = false;
  38526. var shadowEnabled = false;
  38527. var specularEnabled = false;
  38528. if (scene.lightsEnabled && !disableLighting) {
  38529. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38530. var light = _a[_i];
  38531. needNormals = true;
  38532. if (defines["LIGHT" + lightIndex] === undefined) {
  38533. needRebuild = true;
  38534. }
  38535. defines["LIGHT" + lightIndex] = true;
  38536. defines["SPOTLIGHT" + lightIndex] = false;
  38537. defines["HEMILIGHT" + lightIndex] = false;
  38538. defines["POINTLIGHT" + lightIndex] = false;
  38539. defines["DIRLIGHT" + lightIndex] = false;
  38540. var type;
  38541. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38542. type = "SPOTLIGHT" + lightIndex;
  38543. var spotLight = light;
  38544. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38545. }
  38546. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38547. type = "HEMILIGHT" + lightIndex;
  38548. }
  38549. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38550. type = "POINTLIGHT" + lightIndex;
  38551. }
  38552. else {
  38553. type = "DIRLIGHT" + lightIndex;
  38554. }
  38555. defines[type] = true;
  38556. // Specular
  38557. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38558. specularEnabled = true;
  38559. }
  38560. // Shadows
  38561. defines["SHADOW" + lightIndex] = false;
  38562. defines["SHADOWPCF" + lightIndex] = false;
  38563. defines["SHADOWESM" + lightIndex] = false;
  38564. defines["SHADOWCUBE" + lightIndex] = false;
  38565. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38566. var shadowGenerator = light.getShadowGenerator();
  38567. if (shadowGenerator) {
  38568. shadowEnabled = true;
  38569. shadowGenerator.prepareDefines(defines, lightIndex);
  38570. }
  38571. }
  38572. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38573. lightmapMode = true;
  38574. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38575. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38576. }
  38577. else {
  38578. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38579. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38580. }
  38581. lightIndex++;
  38582. if (lightIndex === maxSimultaneousLights)
  38583. break;
  38584. }
  38585. }
  38586. defines["SPECULARTERM"] = specularEnabled;
  38587. defines["SHADOWS"] = shadowEnabled;
  38588. // Resetting all other lights if any
  38589. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38590. if (defines["LIGHT" + index] !== undefined) {
  38591. defines["LIGHT" + index] = false;
  38592. defines["HEMILIGHT" + lightIndex] = false;
  38593. defines["POINTLIGHT" + lightIndex] = false;
  38594. defines["DIRLIGHT" + lightIndex] = false;
  38595. defines["SPOTLIGHT" + lightIndex] = false;
  38596. defines["SHADOW" + lightIndex] = false;
  38597. }
  38598. }
  38599. var caps = scene.getEngine().getCaps();
  38600. if (defines["SHADOWFLOAT"] === undefined) {
  38601. needRebuild = true;
  38602. }
  38603. defines["SHADOWFLOAT"] = shadowEnabled &&
  38604. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38605. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38606. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38607. if (needRebuild) {
  38608. defines.rebuild();
  38609. }
  38610. return needNormals;
  38611. };
  38612. /**
  38613. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38614. * that won t be acctive due to defines being turned off.
  38615. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38616. * @param samplersList The samplers list
  38617. * @param defines The defines helping in the list generation
  38618. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38619. */
  38620. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38621. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38622. var uniformsList;
  38623. var uniformBuffersList = null;
  38624. if (uniformsListOrOptions.uniformsNames) {
  38625. var options = uniformsListOrOptions;
  38626. uniformsList = options.uniformsNames;
  38627. uniformBuffersList = options.uniformBuffersNames;
  38628. samplersList = options.samplers;
  38629. defines = options.defines;
  38630. maxSimultaneousLights = options.maxSimultaneousLights;
  38631. }
  38632. else {
  38633. uniformsList = uniformsListOrOptions;
  38634. if (!samplersList) {
  38635. samplersList = [];
  38636. }
  38637. }
  38638. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38639. if (!defines["LIGHT" + lightIndex]) {
  38640. break;
  38641. }
  38642. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38643. if (uniformBuffersList) {
  38644. uniformBuffersList.push("Light" + lightIndex);
  38645. }
  38646. samplersList.push("shadowSampler" + lightIndex);
  38647. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38648. samplersList.push("projectionLightSampler" + lightIndex);
  38649. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38650. }
  38651. }
  38652. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38653. uniformsList.push("morphTargetInfluences");
  38654. }
  38655. };
  38656. /**
  38657. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38658. * @param defines The defines to update while falling back
  38659. * @param fallbacks The authorized effect fallbacks
  38660. * @param maxSimultaneousLights The maximum number of lights allowed
  38661. * @param rank the current rank of the Effect
  38662. * @returns The newly affected rank
  38663. */
  38664. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38665. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38666. if (rank === void 0) { rank = 0; }
  38667. var lightFallbackRank = 0;
  38668. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38669. if (!defines["LIGHT" + lightIndex]) {
  38670. break;
  38671. }
  38672. if (lightIndex > 0) {
  38673. lightFallbackRank = rank + lightIndex;
  38674. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38675. }
  38676. if (!defines["SHADOWS"]) {
  38677. if (defines["SHADOW" + lightIndex]) {
  38678. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38679. }
  38680. if (defines["SHADOWPCF" + lightIndex]) {
  38681. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38682. }
  38683. if (defines["SHADOWESM" + lightIndex]) {
  38684. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38685. }
  38686. }
  38687. }
  38688. return lightFallbackRank++;
  38689. };
  38690. /**
  38691. * Prepares the list of attributes required for morph targets according to the effect defines.
  38692. * @param attribs The current list of supported attribs
  38693. * @param mesh The mesh to prepare the morph targets attributes for
  38694. * @param defines The current Defines of the effect
  38695. */
  38696. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38697. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38698. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38699. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38700. var manager = mesh.morphTargetManager;
  38701. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38702. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38703. for (var index = 0; index < influencers; index++) {
  38704. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38705. if (normal) {
  38706. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38707. }
  38708. if (tangent) {
  38709. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38710. }
  38711. if (attribs.length > maxAttributesCount) {
  38712. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38713. }
  38714. }
  38715. }
  38716. };
  38717. /**
  38718. * Prepares the list of attributes required for bones according to the effect defines.
  38719. * @param attribs The current list of supported attribs
  38720. * @param mesh The mesh to prepare the bones attributes for
  38721. * @param defines The current Defines of the effect
  38722. * @param fallbacks The current efffect fallback strategy
  38723. */
  38724. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38725. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38726. fallbacks.addCPUSkinningFallback(0, mesh);
  38727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38729. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38732. }
  38733. }
  38734. };
  38735. /**
  38736. * Prepares the list of attributes required for instances according to the effect defines.
  38737. * @param attribs The current list of supported attribs
  38738. * @param defines The current Defines of the effect
  38739. */
  38740. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38741. if (defines["INSTANCES"]) {
  38742. attribs.push("world0");
  38743. attribs.push("world1");
  38744. attribs.push("world2");
  38745. attribs.push("world3");
  38746. }
  38747. };
  38748. /**
  38749. * Binds the light shadow information to the effect for the given mesh.
  38750. * @param light The light containing the generator
  38751. * @param scene The scene the lights belongs to
  38752. * @param mesh The mesh we are binding the information to render
  38753. * @param lightIndex The light index in the effect used to render the mesh
  38754. * @param effect The effect we are binding the data to
  38755. */
  38756. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38757. if (light.shadowEnabled && mesh.receiveShadows) {
  38758. var shadowGenerator = light.getShadowGenerator();
  38759. if (shadowGenerator) {
  38760. shadowGenerator.bindShadowLight(lightIndex, effect);
  38761. }
  38762. }
  38763. };
  38764. /**
  38765. * Binds the light information to the effect.
  38766. * @param light The light containing the generator
  38767. * @param effect The effect we are binding the data to
  38768. * @param lightIndex The light index in the effect used to render
  38769. */
  38770. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38771. light.transferToEffect(effect, lightIndex + "");
  38772. };
  38773. /**
  38774. * Binds the lights information from the scene to the effect for the given mesh.
  38775. * @param scene The scene the lights belongs to
  38776. * @param mesh The mesh we are binding the information to render
  38777. * @param effect The effect we are binding the data to
  38778. * @param defines The generated defines for the effect
  38779. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38780. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38781. */
  38782. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38783. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38784. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38785. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38786. for (var i = 0; i < len; i++) {
  38787. var light = mesh._lightSources[i];
  38788. var iAsString = i.toString();
  38789. var scaledIntensity = light.getScaledIntensity();
  38790. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38791. MaterialHelper.BindLightProperties(light, effect, i);
  38792. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38793. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38794. if (defines["SPECULARTERM"]) {
  38795. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38796. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38797. }
  38798. // Shadows
  38799. if (scene.shadowsEnabled) {
  38800. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38801. }
  38802. light._uniformBuffer.update();
  38803. }
  38804. };
  38805. /**
  38806. * Binds the fog information from the scene to the effect for the given mesh.
  38807. * @param scene The scene the lights belongs to
  38808. * @param mesh The mesh we are binding the information to render
  38809. * @param effect The effect we are binding the data to
  38810. */
  38811. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38812. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38813. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38814. effect.setColor3("vFogColor", scene.fogColor);
  38815. }
  38816. };
  38817. /**
  38818. * Binds the bones information from the mesh to the effect.
  38819. * @param mesh The mesh we are binding the information to render
  38820. * @param effect The effect we are binding the data to
  38821. */
  38822. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38823. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38824. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38825. if (matrices && effect) {
  38826. effect.setMatrices("mBones", matrices);
  38827. }
  38828. }
  38829. };
  38830. /**
  38831. * Binds the morph targets information from the mesh to the effect.
  38832. * @param abstractMesh The mesh we are binding the information to render
  38833. * @param effect The effect we are binding the data to
  38834. */
  38835. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38836. var manager = abstractMesh.morphTargetManager;
  38837. if (!abstractMesh || !manager) {
  38838. return;
  38839. }
  38840. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38841. };
  38842. /**
  38843. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38844. * @param defines The generated defines used in the effect
  38845. * @param effect The effect we are binding the data to
  38846. * @param scene The scene we are willing to render with logarithmic scale for
  38847. */
  38848. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38849. if (defines["LOGARITHMICDEPTH"]) {
  38850. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38851. }
  38852. };
  38853. /**
  38854. * Binds the clip plane information from the scene to the effect.
  38855. * @param scene The scene the clip plane information are extracted from
  38856. * @param effect The effect we are binding the data to
  38857. */
  38858. MaterialHelper.BindClipPlane = function (effect, scene) {
  38859. if (scene.clipPlane) {
  38860. var clipPlane = scene.clipPlane;
  38861. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38862. }
  38863. };
  38864. return MaterialHelper;
  38865. }());
  38866. BABYLON.MaterialHelper = MaterialHelper;
  38867. })(BABYLON || (BABYLON = {}));
  38868. //# sourceMappingURL=babylon.materialHelper.js.map
  38869. var BABYLON;
  38870. (function (BABYLON) {
  38871. var PushMaterial = /** @class */ (function (_super) {
  38872. __extends(PushMaterial, _super);
  38873. function PushMaterial(name, scene) {
  38874. var _this = _super.call(this, name, scene) || this;
  38875. _this._normalMatrix = new BABYLON.Matrix();
  38876. _this.storeEffectOnSubMeshes = true;
  38877. return _this;
  38878. }
  38879. PushMaterial.prototype.getEffect = function () {
  38880. return this._activeEffect;
  38881. };
  38882. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38883. if (!mesh) {
  38884. return false;
  38885. }
  38886. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38887. return true;
  38888. }
  38889. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38890. };
  38891. /**
  38892. * Binds the given world matrix to the active effect
  38893. *
  38894. * @param world the matrix to bind
  38895. */
  38896. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38897. this._activeEffect.setMatrix("world", world);
  38898. };
  38899. /**
  38900. * Binds the given normal matrix to the active effect
  38901. *
  38902. * @param normalMatrix the matrix to bind
  38903. */
  38904. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38905. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38906. };
  38907. PushMaterial.prototype.bind = function (world, mesh) {
  38908. if (!mesh) {
  38909. return;
  38910. }
  38911. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38912. };
  38913. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38914. if (effect === void 0) { effect = null; }
  38915. _super.prototype._afterBind.call(this, mesh);
  38916. this.getScene()._cachedEffect = effect;
  38917. };
  38918. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38919. if (visibility === void 0) { visibility = 1; }
  38920. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38921. };
  38922. return PushMaterial;
  38923. }(BABYLON.Material));
  38924. BABYLON.PushMaterial = PushMaterial;
  38925. })(BABYLON || (BABYLON = {}));
  38926. //# sourceMappingURL=babylon.pushMaterial.js.map
  38927. var BABYLON;
  38928. (function (BABYLON) {
  38929. /** @ignore */
  38930. var StandardMaterialDefines = /** @class */ (function (_super) {
  38931. __extends(StandardMaterialDefines, _super);
  38932. function StandardMaterialDefines() {
  38933. var _this = _super.call(this) || this;
  38934. _this.MAINUV1 = false;
  38935. _this.MAINUV2 = false;
  38936. _this.DIFFUSE = false;
  38937. _this.DIFFUSEDIRECTUV = 0;
  38938. _this.AMBIENT = false;
  38939. _this.AMBIENTDIRECTUV = 0;
  38940. _this.OPACITY = false;
  38941. _this.OPACITYDIRECTUV = 0;
  38942. _this.OPACITYRGB = false;
  38943. _this.REFLECTION = false;
  38944. _this.EMISSIVE = false;
  38945. _this.EMISSIVEDIRECTUV = 0;
  38946. _this.SPECULAR = false;
  38947. _this.SPECULARDIRECTUV = 0;
  38948. _this.BUMP = false;
  38949. _this.BUMPDIRECTUV = 0;
  38950. _this.PARALLAX = false;
  38951. _this.PARALLAXOCCLUSION = false;
  38952. _this.SPECULAROVERALPHA = false;
  38953. _this.CLIPPLANE = false;
  38954. _this.ALPHATEST = false;
  38955. _this.DEPTHPREPASS = false;
  38956. _this.ALPHAFROMDIFFUSE = false;
  38957. _this.POINTSIZE = false;
  38958. _this.FOG = false;
  38959. _this.SPECULARTERM = false;
  38960. _this.DIFFUSEFRESNEL = false;
  38961. _this.OPACITYFRESNEL = false;
  38962. _this.REFLECTIONFRESNEL = false;
  38963. _this.REFRACTIONFRESNEL = false;
  38964. _this.EMISSIVEFRESNEL = false;
  38965. _this.FRESNEL = false;
  38966. _this.NORMAL = false;
  38967. _this.UV1 = false;
  38968. _this.UV2 = false;
  38969. _this.VERTEXCOLOR = false;
  38970. _this.VERTEXALPHA = false;
  38971. _this.NUM_BONE_INFLUENCERS = 0;
  38972. _this.BonesPerMesh = 0;
  38973. _this.INSTANCES = false;
  38974. _this.GLOSSINESS = false;
  38975. _this.ROUGHNESS = false;
  38976. _this.EMISSIVEASILLUMINATION = false;
  38977. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38978. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38979. _this.LIGHTMAP = false;
  38980. _this.LIGHTMAPDIRECTUV = 0;
  38981. _this.OBJECTSPACE_NORMALMAP = false;
  38982. _this.USELIGHTMAPASSHADOWMAP = false;
  38983. _this.REFLECTIONMAP_3D = false;
  38984. _this.REFLECTIONMAP_SPHERICAL = false;
  38985. _this.REFLECTIONMAP_PLANAR = false;
  38986. _this.REFLECTIONMAP_CUBIC = false;
  38987. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38988. _this.REFLECTIONMAP_PROJECTION = false;
  38989. _this.REFLECTIONMAP_SKYBOX = false;
  38990. _this.REFLECTIONMAP_EXPLICIT = false;
  38991. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38992. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38993. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38994. _this.INVERTCUBICMAP = false;
  38995. _this.LOGARITHMICDEPTH = false;
  38996. _this.REFRACTION = false;
  38997. _this.REFRACTIONMAP_3D = false;
  38998. _this.REFLECTIONOVERALPHA = false;
  38999. _this.TWOSIDEDLIGHTING = false;
  39000. _this.SHADOWFLOAT = false;
  39001. _this.MORPHTARGETS = false;
  39002. _this.MORPHTARGETS_NORMAL = false;
  39003. _this.MORPHTARGETS_TANGENT = false;
  39004. _this.NUM_MORPH_INFLUENCERS = 0;
  39005. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39006. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39007. _this.IMAGEPROCESSING = false;
  39008. _this.VIGNETTE = false;
  39009. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39010. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39011. _this.TONEMAPPING = false;
  39012. _this.CONTRAST = false;
  39013. _this.COLORCURVES = false;
  39014. _this.COLORGRADING = false;
  39015. _this.COLORGRADING3D = false;
  39016. _this.SAMPLER3DGREENDEPTH = false;
  39017. _this.SAMPLER3DBGRMAP = false;
  39018. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39019. _this.EXPOSURE = false;
  39020. _this.GRAIN = false;
  39021. _this.rebuild();
  39022. return _this;
  39023. }
  39024. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39025. var modes = [
  39026. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39027. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39028. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39029. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39030. ];
  39031. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39032. var mode = modes_1[_i];
  39033. this[mode] = (mode === modeToEnable);
  39034. }
  39035. };
  39036. return StandardMaterialDefines;
  39037. }(BABYLON.MaterialDefines));
  39038. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39039. var StandardMaterial = /** @class */ (function (_super) {
  39040. __extends(StandardMaterial, _super);
  39041. function StandardMaterial(name, scene) {
  39042. var _this = _super.call(this, name, scene) || this;
  39043. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39044. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39045. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39046. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39047. _this.specularPower = 64;
  39048. _this._useAlphaFromDiffuseTexture = false;
  39049. _this._useEmissiveAsIllumination = false;
  39050. _this._linkEmissiveWithDiffuse = false;
  39051. _this._useSpecularOverAlpha = false;
  39052. _this._useReflectionOverAlpha = false;
  39053. _this._disableLighting = false;
  39054. _this._useObjectSpaceNormalMap = false;
  39055. _this._useParallax = false;
  39056. _this._useParallaxOcclusion = false;
  39057. _this.parallaxScaleBias = 0.05;
  39058. _this._roughness = 0;
  39059. _this.indexOfRefraction = 0.98;
  39060. _this.invertRefractionY = true;
  39061. _this._useLightmapAsShadowmap = false;
  39062. _this._useReflectionFresnelFromSpecular = false;
  39063. _this._useGlossinessFromSpecularMapAlpha = false;
  39064. _this._maxSimultaneousLights = 4;
  39065. /**
  39066. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39067. */
  39068. _this._invertNormalMapX = false;
  39069. /**
  39070. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39071. */
  39072. _this._invertNormalMapY = false;
  39073. /**
  39074. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39075. */
  39076. _this._twoSidedLighting = false;
  39077. _this._renderTargets = new BABYLON.SmartArray(16);
  39078. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39079. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39080. // Setup the default processing configuration to the scene.
  39081. _this._attachImageProcessingConfiguration(null);
  39082. _this.getRenderTargetTextures = function () {
  39083. _this._renderTargets.reset();
  39084. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39085. _this._renderTargets.push(_this._reflectionTexture);
  39086. }
  39087. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39088. _this._renderTargets.push(_this._refractionTexture);
  39089. }
  39090. return _this._renderTargets;
  39091. };
  39092. return _this;
  39093. }
  39094. ;
  39095. ;
  39096. ;
  39097. ;
  39098. ;
  39099. ;
  39100. ;
  39101. ;
  39102. ;
  39103. ;
  39104. ;
  39105. ;
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39112. /**
  39113. * Gets the image processing configuration used either in this material.
  39114. */
  39115. get: function () {
  39116. return this._imageProcessingConfiguration;
  39117. },
  39118. /**
  39119. * Sets the Default image processing configuration used either in the this material.
  39120. *
  39121. * If sets to null, the scene one is in use.
  39122. */
  39123. set: function (value) {
  39124. this._attachImageProcessingConfiguration(value);
  39125. // Ensure the effect will be rebuilt.
  39126. this._markAllSubMeshesAsTexturesDirty();
  39127. },
  39128. enumerable: true,
  39129. configurable: true
  39130. });
  39131. /**
  39132. * Attaches a new image processing configuration to the Standard Material.
  39133. * @param configuration
  39134. */
  39135. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39136. var _this = this;
  39137. if (configuration === this._imageProcessingConfiguration) {
  39138. return;
  39139. }
  39140. // Detaches observer.
  39141. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39142. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39143. }
  39144. // Pick the scene configuration if needed.
  39145. if (!configuration) {
  39146. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39147. }
  39148. else {
  39149. this._imageProcessingConfiguration = configuration;
  39150. }
  39151. // Attaches observer.
  39152. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39153. _this._markAllSubMeshesAsImageProcessingDirty();
  39154. });
  39155. };
  39156. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39157. /**
  39158. * Gets wether the color curves effect is enabled.
  39159. */
  39160. get: function () {
  39161. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39162. },
  39163. /**
  39164. * Sets wether the color curves effect is enabled.
  39165. */
  39166. set: function (value) {
  39167. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39168. },
  39169. enumerable: true,
  39170. configurable: true
  39171. });
  39172. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39173. /**
  39174. * Gets wether the color grading effect is enabled.
  39175. */
  39176. get: function () {
  39177. return this.imageProcessingConfiguration.colorGradingEnabled;
  39178. },
  39179. /**
  39180. * Gets wether the color grading effect is enabled.
  39181. */
  39182. set: function (value) {
  39183. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39184. },
  39185. enumerable: true,
  39186. configurable: true
  39187. });
  39188. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39189. /**
  39190. * Gets wether tonemapping is enabled or not.
  39191. */
  39192. get: function () {
  39193. return this._imageProcessingConfiguration.toneMappingEnabled;
  39194. },
  39195. /**
  39196. * Sets wether tonemapping is enabled or not
  39197. */
  39198. set: function (value) {
  39199. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39200. },
  39201. enumerable: true,
  39202. configurable: true
  39203. });
  39204. ;
  39205. ;
  39206. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39207. /**
  39208. * The camera exposure used on this material.
  39209. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39210. * This corresponds to a photographic exposure.
  39211. */
  39212. get: function () {
  39213. return this._imageProcessingConfiguration.exposure;
  39214. },
  39215. /**
  39216. * The camera exposure used on this material.
  39217. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39218. * This corresponds to a photographic exposure.
  39219. */
  39220. set: function (value) {
  39221. this._imageProcessingConfiguration.exposure = value;
  39222. },
  39223. enumerable: true,
  39224. configurable: true
  39225. });
  39226. ;
  39227. ;
  39228. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39229. /**
  39230. * Gets The camera contrast used on this material.
  39231. */
  39232. get: function () {
  39233. return this._imageProcessingConfiguration.contrast;
  39234. },
  39235. /**
  39236. * Sets The camera contrast used on this material.
  39237. */
  39238. set: function (value) {
  39239. this._imageProcessingConfiguration.contrast = value;
  39240. },
  39241. enumerable: true,
  39242. configurable: true
  39243. });
  39244. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39245. /**
  39246. * Gets the Color Grading 2D Lookup Texture.
  39247. */
  39248. get: function () {
  39249. return this._imageProcessingConfiguration.colorGradingTexture;
  39250. },
  39251. /**
  39252. * Sets the Color Grading 2D Lookup Texture.
  39253. */
  39254. set: function (value) {
  39255. this._imageProcessingConfiguration.colorGradingTexture = value;
  39256. },
  39257. enumerable: true,
  39258. configurable: true
  39259. });
  39260. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39261. /**
  39262. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39263. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39264. * 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;
  39265. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39266. */
  39267. get: function () {
  39268. return this._imageProcessingConfiguration.colorCurves;
  39269. },
  39270. /**
  39271. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39272. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39273. * 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;
  39274. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39275. */
  39276. set: function (value) {
  39277. this._imageProcessingConfiguration.colorCurves = value;
  39278. },
  39279. enumerable: true,
  39280. configurable: true
  39281. });
  39282. StandardMaterial.prototype.getClassName = function () {
  39283. return "StandardMaterial";
  39284. };
  39285. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39286. get: function () {
  39287. return this._useLogarithmicDepth;
  39288. },
  39289. set: function (value) {
  39290. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39291. this._markAllSubMeshesAsMiscDirty();
  39292. },
  39293. enumerable: true,
  39294. configurable: true
  39295. });
  39296. StandardMaterial.prototype.needAlphaBlending = function () {
  39297. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39298. };
  39299. StandardMaterial.prototype.needAlphaTesting = function () {
  39300. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39301. };
  39302. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39303. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39304. };
  39305. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39306. return this._diffuseTexture;
  39307. };
  39308. /**
  39309. * Child classes can use it to update shaders
  39310. */
  39311. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39312. if (useInstances === void 0) { useInstances = false; }
  39313. if (subMesh.effect && this.isFrozen) {
  39314. if (this._wasPreviouslyReady && subMesh.effect) {
  39315. return true;
  39316. }
  39317. }
  39318. if (!subMesh._materialDefines) {
  39319. subMesh._materialDefines = new StandardMaterialDefines();
  39320. }
  39321. var scene = this.getScene();
  39322. var defines = subMesh._materialDefines;
  39323. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39324. if (defines._renderId === scene.getRenderId()) {
  39325. return true;
  39326. }
  39327. }
  39328. var engine = scene.getEngine();
  39329. // Lights
  39330. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39331. // Textures
  39332. if (defines._areTexturesDirty) {
  39333. defines._needUVs = false;
  39334. defines.MAINUV1 = false;
  39335. defines.MAINUV2 = false;
  39336. if (scene.texturesEnabled) {
  39337. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39338. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39339. return false;
  39340. }
  39341. else {
  39342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39343. }
  39344. }
  39345. else {
  39346. defines.DIFFUSE = false;
  39347. }
  39348. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39349. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39350. return false;
  39351. }
  39352. else {
  39353. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39354. }
  39355. }
  39356. else {
  39357. defines.AMBIENT = false;
  39358. }
  39359. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39360. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39361. return false;
  39362. }
  39363. else {
  39364. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39365. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39366. }
  39367. }
  39368. else {
  39369. defines.OPACITY = false;
  39370. }
  39371. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39372. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39373. return false;
  39374. }
  39375. else {
  39376. defines._needNormals = true;
  39377. defines.REFLECTION = true;
  39378. defines.ROUGHNESS = (this._roughness > 0);
  39379. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39380. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39381. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39382. switch (this._reflectionTexture.coordinatesMode) {
  39383. case BABYLON.Texture.CUBIC_MODE:
  39384. case BABYLON.Texture.INVCUBIC_MODE:
  39385. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39386. break;
  39387. case BABYLON.Texture.EXPLICIT_MODE:
  39388. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39389. break;
  39390. case BABYLON.Texture.PLANAR_MODE:
  39391. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39392. break;
  39393. case BABYLON.Texture.PROJECTION_MODE:
  39394. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39395. break;
  39396. case BABYLON.Texture.SKYBOX_MODE:
  39397. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39398. break;
  39399. case BABYLON.Texture.SPHERICAL_MODE:
  39400. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39401. break;
  39402. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39403. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39404. break;
  39405. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39406. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39407. break;
  39408. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39409. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39410. break;
  39411. }
  39412. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39413. }
  39414. }
  39415. else {
  39416. defines.REFLECTION = false;
  39417. }
  39418. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39419. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39420. return false;
  39421. }
  39422. else {
  39423. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39424. }
  39425. }
  39426. else {
  39427. defines.EMISSIVE = false;
  39428. }
  39429. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39430. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39431. return false;
  39432. }
  39433. else {
  39434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39435. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39436. }
  39437. }
  39438. else {
  39439. defines.LIGHTMAP = false;
  39440. }
  39441. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39442. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39443. return false;
  39444. }
  39445. else {
  39446. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39447. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39448. }
  39449. }
  39450. else {
  39451. defines.SPECULAR = false;
  39452. }
  39453. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39454. // Bump texure can not be not blocking.
  39455. if (!this._bumpTexture.isReady()) {
  39456. return false;
  39457. }
  39458. else {
  39459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39460. defines.PARALLAX = this._useParallax;
  39461. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39462. }
  39463. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39464. }
  39465. else {
  39466. defines.BUMP = false;
  39467. }
  39468. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39469. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39470. return false;
  39471. }
  39472. else {
  39473. defines._needUVs = true;
  39474. defines.REFRACTION = true;
  39475. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39476. }
  39477. }
  39478. else {
  39479. defines.REFRACTION = false;
  39480. }
  39481. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39482. }
  39483. else {
  39484. defines.DIFFUSE = false;
  39485. defines.AMBIENT = false;
  39486. defines.OPACITY = false;
  39487. defines.REFLECTION = false;
  39488. defines.EMISSIVE = false;
  39489. defines.LIGHTMAP = false;
  39490. defines.BUMP = false;
  39491. defines.REFRACTION = false;
  39492. }
  39493. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39494. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39495. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39496. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39497. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39498. }
  39499. if (defines._areImageProcessingDirty) {
  39500. if (!this._imageProcessingConfiguration.isReady()) {
  39501. return false;
  39502. }
  39503. this._imageProcessingConfiguration.prepareDefines(defines);
  39504. }
  39505. if (defines._areFresnelDirty) {
  39506. if (StandardMaterial.FresnelEnabled) {
  39507. // Fresnel
  39508. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39509. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39510. this._reflectionFresnelParameters) {
  39511. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39512. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39513. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39514. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39515. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39516. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39517. defines._needNormals = true;
  39518. defines.FRESNEL = true;
  39519. }
  39520. }
  39521. else {
  39522. defines.FRESNEL = false;
  39523. }
  39524. }
  39525. // Misc.
  39526. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39527. // Attribs
  39528. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39529. // Values that need to be evaluated on every frame
  39530. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39531. // Get correct effect
  39532. if (defines.isDirty) {
  39533. defines.markAsProcessed();
  39534. scene.resetCachedMaterial();
  39535. // Fallbacks
  39536. var fallbacks = new BABYLON.EffectFallbacks();
  39537. if (defines.REFLECTION) {
  39538. fallbacks.addFallback(0, "REFLECTION");
  39539. }
  39540. if (defines.SPECULAR) {
  39541. fallbacks.addFallback(0, "SPECULAR");
  39542. }
  39543. if (defines.BUMP) {
  39544. fallbacks.addFallback(0, "BUMP");
  39545. }
  39546. if (defines.PARALLAX) {
  39547. fallbacks.addFallback(1, "PARALLAX");
  39548. }
  39549. if (defines.PARALLAXOCCLUSION) {
  39550. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39551. }
  39552. if (defines.SPECULAROVERALPHA) {
  39553. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39554. }
  39555. if (defines.FOG) {
  39556. fallbacks.addFallback(1, "FOG");
  39557. }
  39558. if (defines.POINTSIZE) {
  39559. fallbacks.addFallback(0, "POINTSIZE");
  39560. }
  39561. if (defines.LOGARITHMICDEPTH) {
  39562. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39563. }
  39564. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39565. if (defines.SPECULARTERM) {
  39566. fallbacks.addFallback(0, "SPECULARTERM");
  39567. }
  39568. if (defines.DIFFUSEFRESNEL) {
  39569. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39570. }
  39571. if (defines.OPACITYFRESNEL) {
  39572. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39573. }
  39574. if (defines.REFLECTIONFRESNEL) {
  39575. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39576. }
  39577. if (defines.EMISSIVEFRESNEL) {
  39578. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39579. }
  39580. if (defines.FRESNEL) {
  39581. fallbacks.addFallback(4, "FRESNEL");
  39582. }
  39583. //Attributes
  39584. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39585. if (defines.NORMAL) {
  39586. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39587. }
  39588. if (defines.UV1) {
  39589. attribs.push(BABYLON.VertexBuffer.UVKind);
  39590. }
  39591. if (defines.UV2) {
  39592. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39593. }
  39594. if (defines.VERTEXCOLOR) {
  39595. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39596. }
  39597. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39598. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39599. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39600. var shaderName = "default";
  39601. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39602. "vFogInfos", "vFogColor", "pointSize",
  39603. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39604. "mBones",
  39605. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39606. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39607. "vReflectionPosition", "vReflectionSize",
  39608. "logarithmicDepthConstant", "vTangentSpaceParams"
  39609. ];
  39610. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39611. var uniformBuffers = ["Material", "Scene"];
  39612. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39613. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39614. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39615. uniformsNames: uniforms,
  39616. uniformBuffersNames: uniformBuffers,
  39617. samplers: samplers,
  39618. defines: defines,
  39619. maxSimultaneousLights: this._maxSimultaneousLights
  39620. });
  39621. if (this.customShaderNameResolve) {
  39622. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39623. }
  39624. var join = defines.toString();
  39625. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39626. attributes: attribs,
  39627. uniformsNames: uniforms,
  39628. uniformBuffersNames: uniformBuffers,
  39629. samplers: samplers,
  39630. defines: join,
  39631. fallbacks: fallbacks,
  39632. onCompiled: this.onCompiled,
  39633. onError: this.onError,
  39634. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39635. }, engine), defines);
  39636. this.buildUniformLayout();
  39637. }
  39638. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39639. return false;
  39640. }
  39641. defines._renderId = scene.getRenderId();
  39642. this._wasPreviouslyReady = true;
  39643. return true;
  39644. };
  39645. StandardMaterial.prototype.buildUniformLayout = function () {
  39646. // Order is important !
  39647. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39648. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39649. this._uniformBuffer.addUniform("opacityParts", 4);
  39650. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39651. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39652. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39653. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39654. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39655. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39656. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39657. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39658. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39659. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39660. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39661. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39662. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39663. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39664. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39665. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39666. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39667. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39668. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39669. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39670. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39671. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39672. this._uniformBuffer.addUniform("specularMatrix", 16);
  39673. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39674. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39675. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39676. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39677. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39678. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39679. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39680. this._uniformBuffer.addUniform("pointSize", 1);
  39681. this._uniformBuffer.create();
  39682. };
  39683. StandardMaterial.prototype.unbind = function () {
  39684. if (this._activeEffect) {
  39685. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39686. this._activeEffect.setTexture("reflection2DSampler", null);
  39687. }
  39688. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39689. this._activeEffect.setTexture("refraction2DSampler", null);
  39690. }
  39691. }
  39692. _super.prototype.unbind.call(this);
  39693. };
  39694. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39695. var scene = this.getScene();
  39696. var defines = subMesh._materialDefines;
  39697. if (!defines) {
  39698. return;
  39699. }
  39700. var effect = subMesh.effect;
  39701. if (!effect) {
  39702. return;
  39703. }
  39704. this._activeEffect = effect;
  39705. // Matrices
  39706. this.bindOnlyWorldMatrix(world);
  39707. // Normal Matrix
  39708. if (defines.OBJECTSPACE_NORMALMAP) {
  39709. world.toNormalMatrix(this._normalMatrix);
  39710. this.bindOnlyNormalMatrix(this._normalMatrix);
  39711. }
  39712. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39713. // Bones
  39714. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39715. if (mustRebind) {
  39716. this._uniformBuffer.bindToEffect(effect, "Material");
  39717. this.bindViewProjection(effect);
  39718. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39719. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39720. // Fresnel
  39721. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39722. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39723. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39724. }
  39725. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39726. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39727. }
  39728. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39729. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39730. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39731. }
  39732. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39733. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39734. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39735. }
  39736. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39737. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39738. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39739. }
  39740. }
  39741. // Textures
  39742. if (scene.texturesEnabled) {
  39743. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39744. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39745. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39746. }
  39747. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39748. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39749. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39750. }
  39751. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39752. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39753. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39754. }
  39755. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39756. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39757. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39758. if (this._reflectionTexture.boundingBoxSize) {
  39759. var cubeTexture = this._reflectionTexture;
  39760. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39761. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39762. }
  39763. }
  39764. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39765. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39766. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39767. }
  39768. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39769. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39770. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39771. }
  39772. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39773. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39774. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39775. }
  39776. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39777. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39778. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39779. if (scene._mirroredCameraPosition) {
  39780. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39781. }
  39782. else {
  39783. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39784. }
  39785. }
  39786. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39787. var depth = 1.0;
  39788. if (!this._refractionTexture.isCube) {
  39789. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39790. if (this._refractionTexture.depth) {
  39791. depth = this._refractionTexture.depth;
  39792. }
  39793. }
  39794. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39795. }
  39796. }
  39797. // Point size
  39798. if (this.pointsCloud) {
  39799. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39800. }
  39801. if (defines.SPECULARTERM) {
  39802. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39803. }
  39804. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39805. // Diffuse
  39806. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39807. }
  39808. // Textures
  39809. if (scene.texturesEnabled) {
  39810. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39811. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39812. }
  39813. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39814. effect.setTexture("ambientSampler", this._ambientTexture);
  39815. }
  39816. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39817. effect.setTexture("opacitySampler", this._opacityTexture);
  39818. }
  39819. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39820. if (this._reflectionTexture.isCube) {
  39821. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39822. }
  39823. else {
  39824. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39825. }
  39826. }
  39827. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39828. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39829. }
  39830. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39831. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39832. }
  39833. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39834. effect.setTexture("specularSampler", this._specularTexture);
  39835. }
  39836. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39837. effect.setTexture("bumpSampler", this._bumpTexture);
  39838. }
  39839. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39840. var depth = 1.0;
  39841. if (this._refractionTexture.isCube) {
  39842. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39843. }
  39844. else {
  39845. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39846. }
  39847. }
  39848. }
  39849. // Clip plane
  39850. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39851. // Colors
  39852. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39853. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39854. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39855. }
  39856. if (mustRebind || !this.isFrozen) {
  39857. // Lights
  39858. if (scene.lightsEnabled && !this._disableLighting) {
  39859. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39860. }
  39861. // View
  39862. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39863. this.bindView(effect);
  39864. }
  39865. // Fog
  39866. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39867. // Morph targets
  39868. if (defines.NUM_MORPH_INFLUENCERS) {
  39869. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39870. }
  39871. // Log. depth
  39872. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39873. // image processing
  39874. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39875. this._imageProcessingConfiguration.bind(this._activeEffect);
  39876. }
  39877. }
  39878. this._uniformBuffer.update();
  39879. this._afterBind(mesh, this._activeEffect);
  39880. };
  39881. StandardMaterial.prototype.getAnimatables = function () {
  39882. var results = [];
  39883. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39884. results.push(this._diffuseTexture);
  39885. }
  39886. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39887. results.push(this._ambientTexture);
  39888. }
  39889. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39890. results.push(this._opacityTexture);
  39891. }
  39892. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39893. results.push(this._reflectionTexture);
  39894. }
  39895. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39896. results.push(this._emissiveTexture);
  39897. }
  39898. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39899. results.push(this._specularTexture);
  39900. }
  39901. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39902. results.push(this._bumpTexture);
  39903. }
  39904. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39905. results.push(this._lightmapTexture);
  39906. }
  39907. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39908. results.push(this._refractionTexture);
  39909. }
  39910. return results;
  39911. };
  39912. StandardMaterial.prototype.getActiveTextures = function () {
  39913. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39914. if (this._diffuseTexture) {
  39915. activeTextures.push(this._diffuseTexture);
  39916. }
  39917. if (this._ambientTexture) {
  39918. activeTextures.push(this._ambientTexture);
  39919. }
  39920. if (this._opacityTexture) {
  39921. activeTextures.push(this._opacityTexture);
  39922. }
  39923. if (this._reflectionTexture) {
  39924. activeTextures.push(this._reflectionTexture);
  39925. }
  39926. if (this._emissiveTexture) {
  39927. activeTextures.push(this._emissiveTexture);
  39928. }
  39929. if (this._specularTexture) {
  39930. activeTextures.push(this._specularTexture);
  39931. }
  39932. if (this._bumpTexture) {
  39933. activeTextures.push(this._bumpTexture);
  39934. }
  39935. if (this._lightmapTexture) {
  39936. activeTextures.push(this._lightmapTexture);
  39937. }
  39938. if (this._refractionTexture) {
  39939. activeTextures.push(this._refractionTexture);
  39940. }
  39941. return activeTextures;
  39942. };
  39943. StandardMaterial.prototype.hasTexture = function (texture) {
  39944. if (_super.prototype.hasTexture.call(this, texture)) {
  39945. return true;
  39946. }
  39947. if (this._diffuseTexture === texture) {
  39948. return true;
  39949. }
  39950. if (this._ambientTexture === texture) {
  39951. return true;
  39952. }
  39953. if (this._opacityTexture === texture) {
  39954. return true;
  39955. }
  39956. if (this._reflectionTexture === texture) {
  39957. return true;
  39958. }
  39959. if (this._emissiveTexture === texture) {
  39960. return true;
  39961. }
  39962. if (this._specularTexture === texture) {
  39963. return true;
  39964. }
  39965. if (this._bumpTexture === texture) {
  39966. return true;
  39967. }
  39968. if (this._lightmapTexture === texture) {
  39969. return true;
  39970. }
  39971. if (this._refractionTexture === texture) {
  39972. return true;
  39973. }
  39974. return false;
  39975. };
  39976. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39977. if (forceDisposeTextures) {
  39978. if (this._diffuseTexture) {
  39979. this._diffuseTexture.dispose();
  39980. }
  39981. if (this._ambientTexture) {
  39982. this._ambientTexture.dispose();
  39983. }
  39984. if (this._opacityTexture) {
  39985. this._opacityTexture.dispose();
  39986. }
  39987. if (this._reflectionTexture) {
  39988. this._reflectionTexture.dispose();
  39989. }
  39990. if (this._emissiveTexture) {
  39991. this._emissiveTexture.dispose();
  39992. }
  39993. if (this._specularTexture) {
  39994. this._specularTexture.dispose();
  39995. }
  39996. if (this._bumpTexture) {
  39997. this._bumpTexture.dispose();
  39998. }
  39999. if (this._lightmapTexture) {
  40000. this._lightmapTexture.dispose();
  40001. }
  40002. if (this._refractionTexture) {
  40003. this._refractionTexture.dispose();
  40004. }
  40005. }
  40006. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40007. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40008. }
  40009. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40010. };
  40011. StandardMaterial.prototype.clone = function (name) {
  40012. var _this = this;
  40013. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40014. result.name = name;
  40015. result.id = name;
  40016. return result;
  40017. };
  40018. StandardMaterial.prototype.serialize = function () {
  40019. return BABYLON.SerializationHelper.Serialize(this);
  40020. };
  40021. // Statics
  40022. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40023. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40024. };
  40025. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40026. get: function () {
  40027. return StandardMaterial._DiffuseTextureEnabled;
  40028. },
  40029. set: function (value) {
  40030. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40031. return;
  40032. }
  40033. StandardMaterial._DiffuseTextureEnabled = value;
  40034. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40035. },
  40036. enumerable: true,
  40037. configurable: true
  40038. });
  40039. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40040. get: function () {
  40041. return StandardMaterial._AmbientTextureEnabled;
  40042. },
  40043. set: function (value) {
  40044. if (StandardMaterial._AmbientTextureEnabled === value) {
  40045. return;
  40046. }
  40047. StandardMaterial._AmbientTextureEnabled = value;
  40048. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40054. get: function () {
  40055. return StandardMaterial._OpacityTextureEnabled;
  40056. },
  40057. set: function (value) {
  40058. if (StandardMaterial._OpacityTextureEnabled === value) {
  40059. return;
  40060. }
  40061. StandardMaterial._OpacityTextureEnabled = value;
  40062. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40063. },
  40064. enumerable: true,
  40065. configurable: true
  40066. });
  40067. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40068. get: function () {
  40069. return StandardMaterial._ReflectionTextureEnabled;
  40070. },
  40071. set: function (value) {
  40072. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40073. return;
  40074. }
  40075. StandardMaterial._ReflectionTextureEnabled = value;
  40076. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40077. },
  40078. enumerable: true,
  40079. configurable: true
  40080. });
  40081. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40082. get: function () {
  40083. return StandardMaterial._EmissiveTextureEnabled;
  40084. },
  40085. set: function (value) {
  40086. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40087. return;
  40088. }
  40089. StandardMaterial._EmissiveTextureEnabled = value;
  40090. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40091. },
  40092. enumerable: true,
  40093. configurable: true
  40094. });
  40095. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40096. get: function () {
  40097. return StandardMaterial._SpecularTextureEnabled;
  40098. },
  40099. set: function (value) {
  40100. if (StandardMaterial._SpecularTextureEnabled === value) {
  40101. return;
  40102. }
  40103. StandardMaterial._SpecularTextureEnabled = value;
  40104. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40105. },
  40106. enumerable: true,
  40107. configurable: true
  40108. });
  40109. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40110. get: function () {
  40111. return StandardMaterial._BumpTextureEnabled;
  40112. },
  40113. set: function (value) {
  40114. if (StandardMaterial._BumpTextureEnabled === value) {
  40115. return;
  40116. }
  40117. StandardMaterial._BumpTextureEnabled = value;
  40118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40119. },
  40120. enumerable: true,
  40121. configurable: true
  40122. });
  40123. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40124. get: function () {
  40125. return StandardMaterial._LightmapTextureEnabled;
  40126. },
  40127. set: function (value) {
  40128. if (StandardMaterial._LightmapTextureEnabled === value) {
  40129. return;
  40130. }
  40131. StandardMaterial._LightmapTextureEnabled = value;
  40132. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40133. },
  40134. enumerable: true,
  40135. configurable: true
  40136. });
  40137. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40138. get: function () {
  40139. return StandardMaterial._RefractionTextureEnabled;
  40140. },
  40141. set: function (value) {
  40142. if (StandardMaterial._RefractionTextureEnabled === value) {
  40143. return;
  40144. }
  40145. StandardMaterial._RefractionTextureEnabled = value;
  40146. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40147. },
  40148. enumerable: true,
  40149. configurable: true
  40150. });
  40151. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40152. get: function () {
  40153. return StandardMaterial._ColorGradingTextureEnabled;
  40154. },
  40155. set: function (value) {
  40156. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40157. return;
  40158. }
  40159. StandardMaterial._ColorGradingTextureEnabled = value;
  40160. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40161. },
  40162. enumerable: true,
  40163. configurable: true
  40164. });
  40165. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40166. get: function () {
  40167. return StandardMaterial._FresnelEnabled;
  40168. },
  40169. set: function (value) {
  40170. if (StandardMaterial._FresnelEnabled === value) {
  40171. return;
  40172. }
  40173. StandardMaterial._FresnelEnabled = value;
  40174. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40175. },
  40176. enumerable: true,
  40177. configurable: true
  40178. });
  40179. // Flags used to enable or disable a type of texture for all Standard Materials
  40180. StandardMaterial._DiffuseTextureEnabled = true;
  40181. StandardMaterial._AmbientTextureEnabled = true;
  40182. StandardMaterial._OpacityTextureEnabled = true;
  40183. StandardMaterial._ReflectionTextureEnabled = true;
  40184. StandardMaterial._EmissiveTextureEnabled = true;
  40185. StandardMaterial._SpecularTextureEnabled = true;
  40186. StandardMaterial._BumpTextureEnabled = true;
  40187. StandardMaterial._LightmapTextureEnabled = true;
  40188. StandardMaterial._RefractionTextureEnabled = true;
  40189. StandardMaterial._ColorGradingTextureEnabled = true;
  40190. StandardMaterial._FresnelEnabled = true;
  40191. __decorate([
  40192. BABYLON.serializeAsTexture("diffuseTexture")
  40193. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40194. __decorate([
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40196. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40197. __decorate([
  40198. BABYLON.serializeAsTexture("ambientTexture")
  40199. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40200. __decorate([
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40202. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40203. __decorate([
  40204. BABYLON.serializeAsTexture("opacityTexture")
  40205. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40206. __decorate([
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40208. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40209. __decorate([
  40210. BABYLON.serializeAsTexture("reflectionTexture")
  40211. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40212. __decorate([
  40213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40214. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40215. __decorate([
  40216. BABYLON.serializeAsTexture("emissiveTexture")
  40217. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40218. __decorate([
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40220. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40221. __decorate([
  40222. BABYLON.serializeAsTexture("specularTexture")
  40223. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40224. __decorate([
  40225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40226. ], StandardMaterial.prototype, "specularTexture", void 0);
  40227. __decorate([
  40228. BABYLON.serializeAsTexture("bumpTexture")
  40229. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40230. __decorate([
  40231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40232. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40233. __decorate([
  40234. BABYLON.serializeAsTexture("lightmapTexture")
  40235. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40236. __decorate([
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40239. __decorate([
  40240. BABYLON.serializeAsTexture("refractionTexture")
  40241. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40242. __decorate([
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40245. __decorate([
  40246. BABYLON.serializeAsColor3("ambient")
  40247. ], StandardMaterial.prototype, "ambientColor", void 0);
  40248. __decorate([
  40249. BABYLON.serializeAsColor3("diffuse")
  40250. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40251. __decorate([
  40252. BABYLON.serializeAsColor3("specular")
  40253. ], StandardMaterial.prototype, "specularColor", void 0);
  40254. __decorate([
  40255. BABYLON.serializeAsColor3("emissive")
  40256. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40257. __decorate([
  40258. BABYLON.serialize()
  40259. ], StandardMaterial.prototype, "specularPower", void 0);
  40260. __decorate([
  40261. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40262. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40263. __decorate([
  40264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40265. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40266. __decorate([
  40267. BABYLON.serialize("useEmissiveAsIllumination")
  40268. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40269. __decorate([
  40270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40271. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40272. __decorate([
  40273. BABYLON.serialize("linkEmissiveWithDiffuse")
  40274. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40277. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40278. __decorate([
  40279. BABYLON.serialize("useSpecularOverAlpha")
  40280. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40284. __decorate([
  40285. BABYLON.serialize("useReflectionOverAlpha")
  40286. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40289. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40290. __decorate([
  40291. BABYLON.serialize("disableLighting")
  40292. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40293. __decorate([
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40295. ], StandardMaterial.prototype, "disableLighting", void 0);
  40296. __decorate([
  40297. BABYLON.serialize("useObjectSpaceNormalMap")
  40298. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40299. __decorate([
  40300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40301. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40302. __decorate([
  40303. BABYLON.serialize("useParallax")
  40304. ], StandardMaterial.prototype, "_useParallax", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40307. ], StandardMaterial.prototype, "useParallax", void 0);
  40308. __decorate([
  40309. BABYLON.serialize("useParallaxOcclusion")
  40310. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40311. __decorate([
  40312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40313. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40314. __decorate([
  40315. BABYLON.serialize()
  40316. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40317. __decorate([
  40318. BABYLON.serialize("roughness")
  40319. ], StandardMaterial.prototype, "_roughness", void 0);
  40320. __decorate([
  40321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40322. ], StandardMaterial.prototype, "roughness", void 0);
  40323. __decorate([
  40324. BABYLON.serialize()
  40325. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40326. __decorate([
  40327. BABYLON.serialize()
  40328. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40329. __decorate([
  40330. BABYLON.serialize("useLightmapAsShadowmap")
  40331. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40332. __decorate([
  40333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40334. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40335. __decorate([
  40336. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40337. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40338. __decorate([
  40339. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40340. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40341. __decorate([
  40342. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40343. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40344. __decorate([
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40346. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40347. __decorate([
  40348. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40349. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40350. __decorate([
  40351. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40352. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40353. __decorate([
  40354. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40355. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40356. __decorate([
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40358. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40359. __decorate([
  40360. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40361. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40362. __decorate([
  40363. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40364. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40365. __decorate([
  40366. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40367. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40368. __decorate([
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40370. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40371. __decorate([
  40372. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40373. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40374. __decorate([
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40376. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40377. __decorate([
  40378. BABYLON.serialize("maxSimultaneousLights")
  40379. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40380. __decorate([
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40382. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40383. __decorate([
  40384. BABYLON.serialize("invertNormalMapX")
  40385. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40386. __decorate([
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40389. __decorate([
  40390. BABYLON.serialize("invertNormalMapY")
  40391. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40392. __decorate([
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40395. __decorate([
  40396. BABYLON.serialize("twoSidedLighting")
  40397. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40398. __decorate([
  40399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40400. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40401. __decorate([
  40402. BABYLON.serialize()
  40403. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40404. return StandardMaterial;
  40405. }(BABYLON.PushMaterial));
  40406. BABYLON.StandardMaterial = StandardMaterial;
  40407. })(BABYLON || (BABYLON = {}));
  40408. //# sourceMappingURL=babylon.standardMaterial.js.map
  40409. var BABYLON;
  40410. (function (BABYLON) {
  40411. /**
  40412. * Manages the defines for the PBR Material.
  40413. */
  40414. var PBRMaterialDefines = /** @class */ (function (_super) {
  40415. __extends(PBRMaterialDefines, _super);
  40416. /**
  40417. * Initializes the PBR Material defines.
  40418. */
  40419. function PBRMaterialDefines() {
  40420. var _this = _super.call(this) || this;
  40421. _this.PBR = true;
  40422. _this.MAINUV1 = false;
  40423. _this.MAINUV2 = false;
  40424. _this.UV1 = false;
  40425. _this.UV2 = false;
  40426. _this.ALBEDO = false;
  40427. _this.ALBEDODIRECTUV = 0;
  40428. _this.VERTEXCOLOR = false;
  40429. _this.AMBIENT = false;
  40430. _this.AMBIENTDIRECTUV = 0;
  40431. _this.AMBIENTINGRAYSCALE = false;
  40432. _this.OPACITY = false;
  40433. _this.VERTEXALPHA = false;
  40434. _this.OPACITYDIRECTUV = 0;
  40435. _this.OPACITYRGB = false;
  40436. _this.ALPHATEST = false;
  40437. _this.DEPTHPREPASS = false;
  40438. _this.ALPHABLEND = false;
  40439. _this.ALPHAFROMALBEDO = false;
  40440. _this.ALPHATESTVALUE = 0.5;
  40441. _this.SPECULAROVERALPHA = false;
  40442. _this.RADIANCEOVERALPHA = false;
  40443. _this.ALPHAFRESNEL = false;
  40444. _this.LINEARALPHAFRESNEL = false;
  40445. _this.PREMULTIPLYALPHA = false;
  40446. _this.EMISSIVE = false;
  40447. _this.EMISSIVEDIRECTUV = 0;
  40448. _this.REFLECTIVITY = false;
  40449. _this.REFLECTIVITYDIRECTUV = 0;
  40450. _this.SPECULARTERM = false;
  40451. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40452. _this.MICROSURFACEAUTOMATIC = false;
  40453. _this.LODBASEDMICROSFURACE = false;
  40454. _this.MICROSURFACEMAP = false;
  40455. _this.MICROSURFACEMAPDIRECTUV = 0;
  40456. _this.METALLICWORKFLOW = false;
  40457. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40458. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40459. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40460. _this.AOSTOREINMETALMAPRED = false;
  40461. _this.ENVIRONMENTBRDF = false;
  40462. _this.NORMAL = false;
  40463. _this.TANGENT = false;
  40464. _this.BUMP = false;
  40465. _this.BUMPDIRECTUV = 0;
  40466. _this.OBJECTSPACE_NORMALMAP = false;
  40467. _this.PARALLAX = false;
  40468. _this.PARALLAXOCCLUSION = false;
  40469. _this.NORMALXYSCALE = true;
  40470. _this.LIGHTMAP = false;
  40471. _this.LIGHTMAPDIRECTUV = 0;
  40472. _this.USELIGHTMAPASSHADOWMAP = false;
  40473. _this.REFLECTION = false;
  40474. _this.REFLECTIONMAP_3D = false;
  40475. _this.REFLECTIONMAP_SPHERICAL = false;
  40476. _this.REFLECTIONMAP_PLANAR = false;
  40477. _this.REFLECTIONMAP_CUBIC = false;
  40478. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40479. _this.REFLECTIONMAP_PROJECTION = false;
  40480. _this.REFLECTIONMAP_SKYBOX = false;
  40481. _this.REFLECTIONMAP_EXPLICIT = false;
  40482. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40483. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40484. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40485. _this.INVERTCUBICMAP = false;
  40486. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40487. _this.USESPHERICALINVERTEX = false;
  40488. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40489. _this.LODINREFLECTIONALPHA = false;
  40490. _this.GAMMAREFLECTION = false;
  40491. _this.RADIANCEOCCLUSION = false;
  40492. _this.HORIZONOCCLUSION = false;
  40493. _this.REFRACTION = false;
  40494. _this.REFRACTIONMAP_3D = false;
  40495. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40496. _this.LODINREFRACTIONALPHA = false;
  40497. _this.GAMMAREFRACTION = false;
  40498. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40499. _this.INSTANCES = false;
  40500. _this.NUM_BONE_INFLUENCERS = 0;
  40501. _this.BonesPerMesh = 0;
  40502. _this.NONUNIFORMSCALING = false;
  40503. _this.MORPHTARGETS = false;
  40504. _this.MORPHTARGETS_NORMAL = false;
  40505. _this.MORPHTARGETS_TANGENT = false;
  40506. _this.NUM_MORPH_INFLUENCERS = 0;
  40507. _this.IMAGEPROCESSING = false;
  40508. _this.VIGNETTE = false;
  40509. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40510. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40511. _this.TONEMAPPING = false;
  40512. _this.CONTRAST = false;
  40513. _this.COLORCURVES = false;
  40514. _this.COLORGRADING = false;
  40515. _this.COLORGRADING3D = false;
  40516. _this.SAMPLER3DGREENDEPTH = false;
  40517. _this.SAMPLER3DBGRMAP = false;
  40518. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40519. _this.EXPOSURE = false;
  40520. _this.GRAIN = false;
  40521. _this.USEPHYSICALLIGHTFALLOFF = false;
  40522. _this.TWOSIDEDLIGHTING = false;
  40523. _this.SHADOWFLOAT = false;
  40524. _this.CLIPPLANE = false;
  40525. _this.POINTSIZE = false;
  40526. _this.FOG = false;
  40527. _this.LOGARITHMICDEPTH = false;
  40528. _this.FORCENORMALFORWARD = false;
  40529. _this.rebuild();
  40530. return _this;
  40531. }
  40532. /**
  40533. * Resets the PBR Material defines.
  40534. */
  40535. PBRMaterialDefines.prototype.reset = function () {
  40536. _super.prototype.reset.call(this);
  40537. this.ALPHATESTVALUE = 0.5;
  40538. this.PBR = true;
  40539. };
  40540. return PBRMaterialDefines;
  40541. }(BABYLON.MaterialDefines));
  40542. /**
  40543. * The Physically based material base class of BJS.
  40544. *
  40545. * This offers the main features of a standard PBR material.
  40546. * For more information, please refer to the documentation :
  40547. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40548. */
  40549. var PBRBaseMaterial = /** @class */ (function (_super) {
  40550. __extends(PBRBaseMaterial, _super);
  40551. /**
  40552. * Instantiates a new PBRMaterial instance.
  40553. *
  40554. * @param name The material name
  40555. * @param scene The scene the material will be use in.
  40556. */
  40557. function PBRBaseMaterial(name, scene) {
  40558. var _this = _super.call(this, name, scene) || this;
  40559. /**
  40560. * Intensity of the direct lights e.g. the four lights available in your scene.
  40561. * This impacts both the direct diffuse and specular highlights.
  40562. */
  40563. _this._directIntensity = 1.0;
  40564. /**
  40565. * Intensity of the emissive part of the material.
  40566. * This helps controlling the emissive effect without modifying the emissive color.
  40567. */
  40568. _this._emissiveIntensity = 1.0;
  40569. /**
  40570. * Intensity of the environment e.g. how much the environment will light the object
  40571. * either through harmonics for rough material or through the refelction for shiny ones.
  40572. */
  40573. _this._environmentIntensity = 1.0;
  40574. /**
  40575. * This is a special control allowing the reduction of the specular highlights coming from the
  40576. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40577. */
  40578. _this._specularIntensity = 1.0;
  40579. /**
  40580. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40581. */
  40582. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40583. /**
  40584. * Debug Control allowing disabling the bump map on this material.
  40585. */
  40586. _this._disableBumpMap = false;
  40587. /**
  40588. * AKA Occlusion Texture Intensity in other nomenclature.
  40589. */
  40590. _this._ambientTextureStrength = 1.0;
  40591. /**
  40592. * The color of a material in ambient lighting.
  40593. */
  40594. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40595. /**
  40596. * AKA Diffuse Color in other nomenclature.
  40597. */
  40598. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40599. /**
  40600. * AKA Specular Color in other nomenclature.
  40601. */
  40602. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40603. /**
  40604. * The color applied when light is reflected from a material.
  40605. */
  40606. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40607. /**
  40608. * The color applied when light is emitted from a material.
  40609. */
  40610. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40611. /**
  40612. * AKA Glossiness in other nomenclature.
  40613. */
  40614. _this._microSurface = 0.9;
  40615. /**
  40616. * source material index of refraction (IOR)' / 'destination material IOR.
  40617. */
  40618. _this._indexOfRefraction = 0.66;
  40619. /**
  40620. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40621. */
  40622. _this._invertRefractionY = false;
  40623. /**
  40624. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40625. * Materials half opaque for instance using refraction could benefit from this control.
  40626. */
  40627. _this._linkRefractionWithTransparency = false;
  40628. /**
  40629. * Specifies that the material will use the light map as a show map.
  40630. */
  40631. _this._useLightmapAsShadowmap = false;
  40632. /**
  40633. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40634. * makes the reflect vector face the model (under horizon).
  40635. */
  40636. _this._useHorizonOcclusion = true;
  40637. /**
  40638. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40639. * too much the area relying on ambient texture to define their ambient occlusion.
  40640. */
  40641. _this._useRadianceOcclusion = true;
  40642. /**
  40643. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40644. */
  40645. _this._useAlphaFromAlbedoTexture = false;
  40646. /**
  40647. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40648. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40649. */
  40650. _this._useSpecularOverAlpha = true;
  40651. /**
  40652. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40653. */
  40654. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40655. /**
  40656. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40657. */
  40658. _this._useRoughnessFromMetallicTextureAlpha = true;
  40659. /**
  40660. * Specifies if the metallic texture contains the roughness information in its green channel.
  40661. */
  40662. _this._useRoughnessFromMetallicTextureGreen = false;
  40663. /**
  40664. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40665. */
  40666. _this._useMetallnessFromMetallicTextureBlue = false;
  40667. /**
  40668. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40669. */
  40670. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40671. /**
  40672. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40673. */
  40674. _this._useAmbientInGrayScale = false;
  40675. /**
  40676. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40677. * The material will try to infer what glossiness each pixel should be.
  40678. */
  40679. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40680. /**
  40681. * BJS is using an harcoded light falloff based on a manually sets up range.
  40682. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40683. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40684. */
  40685. _this._usePhysicalLightFalloff = true;
  40686. /**
  40687. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40688. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40689. */
  40690. _this._useRadianceOverAlpha = true;
  40691. /**
  40692. * Allows using an object space normal map (instead of tangent space).
  40693. */
  40694. _this._useObjectSpaceNormalMap = false;
  40695. /**
  40696. * Allows using the bump map in parallax mode.
  40697. */
  40698. _this._useParallax = false;
  40699. /**
  40700. * Allows using the bump map in parallax occlusion mode.
  40701. */
  40702. _this._useParallaxOcclusion = false;
  40703. /**
  40704. * Controls the scale bias of the parallax mode.
  40705. */
  40706. _this._parallaxScaleBias = 0.05;
  40707. /**
  40708. * If sets to true, disables all the lights affecting the material.
  40709. */
  40710. _this._disableLighting = false;
  40711. /**
  40712. * Number of Simultaneous lights allowed on the material.
  40713. */
  40714. _this._maxSimultaneousLights = 4;
  40715. /**
  40716. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40717. */
  40718. _this._invertNormalMapX = false;
  40719. /**
  40720. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40721. */
  40722. _this._invertNormalMapY = false;
  40723. /**
  40724. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40725. */
  40726. _this._twoSidedLighting = false;
  40727. /**
  40728. * Defines the alpha limits in alpha test mode.
  40729. */
  40730. _this._alphaCutOff = 0.4;
  40731. /**
  40732. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40733. */
  40734. _this._forceAlphaTest = false;
  40735. /**
  40736. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40737. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40738. */
  40739. _this._useAlphaFresnel = false;
  40740. /**
  40741. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40742. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40743. */
  40744. _this._useLinearAlphaFresnel = false;
  40745. /**
  40746. * The transparency mode of the material.
  40747. */
  40748. _this._transparencyMode = null;
  40749. /**
  40750. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40751. * from cos thetav and roughness:
  40752. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40753. */
  40754. _this._environmentBRDFTexture = null;
  40755. /**
  40756. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40757. */
  40758. _this._forceIrradianceInFragment = false;
  40759. /**
  40760. * Force normal to face away from face.
  40761. */
  40762. _this._forceNormalForward = false;
  40763. /**
  40764. * Stores the available render targets.
  40765. */
  40766. _this._renderTargets = new BABYLON.SmartArray(16);
  40767. /**
  40768. * Sets the global ambient color for the material used in lighting calculations.
  40769. */
  40770. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40771. // Setup the default processing configuration to the scene.
  40772. _this._attachImageProcessingConfiguration(null);
  40773. _this.getRenderTargetTextures = function () {
  40774. _this._renderTargets.reset();
  40775. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40776. _this._renderTargets.push(_this._reflectionTexture);
  40777. }
  40778. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40779. _this._renderTargets.push(_this._refractionTexture);
  40780. }
  40781. return _this._renderTargets;
  40782. };
  40783. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40784. return _this;
  40785. }
  40786. /**
  40787. * Attaches a new image processing configuration to the PBR Material.
  40788. * @param configuration
  40789. */
  40790. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40791. var _this = this;
  40792. if (configuration === this._imageProcessingConfiguration) {
  40793. return;
  40794. }
  40795. // Detaches observer.
  40796. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40797. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40798. }
  40799. // Pick the scene configuration if needed.
  40800. if (!configuration) {
  40801. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40802. }
  40803. else {
  40804. this._imageProcessingConfiguration = configuration;
  40805. }
  40806. // Attaches observer.
  40807. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40808. _this._markAllSubMeshesAsImageProcessingDirty();
  40809. });
  40810. };
  40811. /**
  40812. * Gets the name of the material class.
  40813. */
  40814. PBRBaseMaterial.prototype.getClassName = function () {
  40815. return "PBRBaseMaterial";
  40816. };
  40817. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40818. /**
  40819. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40820. */
  40821. get: function () {
  40822. return this._useLogarithmicDepth;
  40823. },
  40824. /**
  40825. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40826. */
  40827. set: function (value) {
  40828. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40829. },
  40830. enumerable: true,
  40831. configurable: true
  40832. });
  40833. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40834. /**
  40835. * Gets the current transparency mode.
  40836. */
  40837. get: function () {
  40838. return this._transparencyMode;
  40839. },
  40840. /**
  40841. * Sets the transparency mode of the material.
  40842. */
  40843. set: function (value) {
  40844. if (this._transparencyMode === value) {
  40845. return;
  40846. }
  40847. this._transparencyMode = value;
  40848. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40849. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40850. },
  40851. enumerable: true,
  40852. configurable: true
  40853. });
  40854. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40855. /**
  40856. * Returns true if alpha blending should be disabled.
  40857. */
  40858. get: function () {
  40859. return (this._linkRefractionWithTransparency ||
  40860. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40861. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40862. },
  40863. enumerable: true,
  40864. configurable: true
  40865. });
  40866. /**
  40867. * Specifies whether or not this material should be rendered in alpha blend mode.
  40868. */
  40869. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40870. if (this._disableAlphaBlending) {
  40871. return false;
  40872. }
  40873. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40874. };
  40875. /**
  40876. * Specifies if the mesh will require alpha blending.
  40877. * @param mesh - BJS mesh.
  40878. */
  40879. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40880. if (this._disableAlphaBlending) {
  40881. return false;
  40882. }
  40883. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40884. };
  40885. /**
  40886. * Specifies whether or not this material should be rendered in alpha test mode.
  40887. */
  40888. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40889. if (this._forceAlphaTest) {
  40890. return true;
  40891. }
  40892. if (this._linkRefractionWithTransparency) {
  40893. return false;
  40894. }
  40895. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40896. };
  40897. /**
  40898. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40899. */
  40900. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40901. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40902. };
  40903. /**
  40904. * Gets the texture used for the alpha test.
  40905. */
  40906. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40907. return this._albedoTexture;
  40908. };
  40909. /**
  40910. * Specifies that the submesh is ready to be used.
  40911. * @param mesh - BJS mesh.
  40912. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40913. * @param useInstances - Specifies that instances should be used.
  40914. * @returns - boolean indicating that the submesh is ready or not.
  40915. */
  40916. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40917. if (subMesh.effect && this.isFrozen) {
  40918. if (this._wasPreviouslyReady) {
  40919. return true;
  40920. }
  40921. }
  40922. if (!subMesh._materialDefines) {
  40923. subMesh._materialDefines = new PBRMaterialDefines();
  40924. }
  40925. var defines = subMesh._materialDefines;
  40926. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40927. if (defines._renderId === this.getScene().getRenderId()) {
  40928. return true;
  40929. }
  40930. }
  40931. var scene = this.getScene();
  40932. var engine = scene.getEngine();
  40933. if (defines._areTexturesDirty) {
  40934. if (scene.texturesEnabled) {
  40935. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40936. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40937. return false;
  40938. }
  40939. }
  40940. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40941. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40942. return false;
  40943. }
  40944. }
  40945. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40946. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40947. return false;
  40948. }
  40949. }
  40950. var reflectionTexture = this._getReflectionTexture();
  40951. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40952. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40953. return false;
  40954. }
  40955. }
  40956. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40957. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40958. return false;
  40959. }
  40960. }
  40961. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40962. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40963. return false;
  40964. }
  40965. }
  40966. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40967. if (this._metallicTexture) {
  40968. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40969. return false;
  40970. }
  40971. }
  40972. else if (this._reflectivityTexture) {
  40973. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40974. return false;
  40975. }
  40976. }
  40977. if (this._microSurfaceTexture) {
  40978. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40979. return false;
  40980. }
  40981. }
  40982. }
  40983. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40984. // Bump texture cannot be not blocking.
  40985. if (!this._bumpTexture.isReady()) {
  40986. return false;
  40987. }
  40988. }
  40989. var refractionTexture = this._getRefractionTexture();
  40990. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40991. if (!refractionTexture.isReadyOrNotBlocking()) {
  40992. return false;
  40993. }
  40994. }
  40995. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40996. // This is blocking.
  40997. if (!this._environmentBRDFTexture.isReady()) {
  40998. return false;
  40999. }
  41000. }
  41001. }
  41002. }
  41003. if (defines._areImageProcessingDirty) {
  41004. if (!this._imageProcessingConfiguration.isReady()) {
  41005. return false;
  41006. }
  41007. }
  41008. if (!engine.getCaps().standardDerivatives) {
  41009. var bufferMesh = null;
  41010. if (mesh.getClassName() === "InstancedMesh") {
  41011. bufferMesh = mesh.sourceMesh;
  41012. }
  41013. else if (mesh.getClassName() === "Mesh") {
  41014. bufferMesh = mesh;
  41015. }
  41016. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41017. bufferMesh.createNormals(true);
  41018. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41019. }
  41020. }
  41021. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41022. if (effect) {
  41023. scene.resetCachedMaterial();
  41024. subMesh.setEffect(effect, defines);
  41025. this.buildUniformLayout();
  41026. }
  41027. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41028. return false;
  41029. }
  41030. defines._renderId = scene.getRenderId();
  41031. this._wasPreviouslyReady = true;
  41032. return true;
  41033. };
  41034. /**
  41035. * Specifies if the material uses metallic roughness workflow.
  41036. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41037. */
  41038. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41039. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41040. return true;
  41041. }
  41042. return false;
  41043. };
  41044. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41045. if (onCompiled === void 0) { onCompiled = null; }
  41046. if (onError === void 0) { onError = null; }
  41047. if (useInstances === void 0) { useInstances = null; }
  41048. if (useClipPlane === void 0) { useClipPlane = null; }
  41049. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41050. if (!defines.isDirty) {
  41051. return null;
  41052. }
  41053. defines.markAsProcessed();
  41054. var scene = this.getScene();
  41055. var engine = scene.getEngine();
  41056. // Fallbacks
  41057. var fallbacks = new BABYLON.EffectFallbacks();
  41058. var fallbackRank = 0;
  41059. if (defines.USESPHERICALINVERTEX) {
  41060. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41061. }
  41062. if (defines.FOG) {
  41063. fallbacks.addFallback(fallbackRank, "FOG");
  41064. }
  41065. if (defines.POINTSIZE) {
  41066. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41067. }
  41068. if (defines.LOGARITHMICDEPTH) {
  41069. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41070. }
  41071. if (defines.PARALLAX) {
  41072. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41073. }
  41074. if (defines.PARALLAXOCCLUSION) {
  41075. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41076. }
  41077. if (defines.ENVIRONMENTBRDF) {
  41078. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41079. }
  41080. if (defines.TANGENT) {
  41081. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41082. }
  41083. if (defines.BUMP) {
  41084. fallbacks.addFallback(fallbackRank++, "BUMP");
  41085. }
  41086. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41087. if (defines.SPECULARTERM) {
  41088. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41089. }
  41090. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41091. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41092. }
  41093. if (defines.LIGHTMAP) {
  41094. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41095. }
  41096. if (defines.NORMAL) {
  41097. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41098. }
  41099. if (defines.AMBIENT) {
  41100. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41101. }
  41102. if (defines.EMISSIVE) {
  41103. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41104. }
  41105. if (defines.VERTEXCOLOR) {
  41106. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41107. }
  41108. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41109. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41110. }
  41111. if (defines.MORPHTARGETS) {
  41112. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41113. }
  41114. //Attributes
  41115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41116. if (defines.NORMAL) {
  41117. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41118. }
  41119. if (defines.TANGENT) {
  41120. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41121. }
  41122. if (defines.UV1) {
  41123. attribs.push(BABYLON.VertexBuffer.UVKind);
  41124. }
  41125. if (defines.UV2) {
  41126. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41127. }
  41128. if (defines.VERTEXCOLOR) {
  41129. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41130. }
  41131. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41132. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41133. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41134. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41135. "vFogInfos", "vFogColor", "pointSize",
  41136. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41137. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41138. "mBones",
  41139. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41140. "vLightingIntensity",
  41141. "logarithmicDepthConstant",
  41142. "vSphericalX", "vSphericalY", "vSphericalZ",
  41143. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41144. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41145. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41146. "vTangentSpaceParams"
  41147. ];
  41148. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41149. "bumpSampler", "lightmapSampler", "opacitySampler",
  41150. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41151. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41152. "microSurfaceSampler", "environmentBrdfSampler"];
  41153. var uniformBuffers = ["Material", "Scene"];
  41154. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41155. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41156. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41157. uniformsNames: uniforms,
  41158. uniformBuffersNames: uniformBuffers,
  41159. samplers: samplers,
  41160. defines: defines,
  41161. maxSimultaneousLights: this._maxSimultaneousLights
  41162. });
  41163. var join = defines.toString();
  41164. return engine.createEffect("pbr", {
  41165. attributes: attribs,
  41166. uniformsNames: uniforms,
  41167. uniformBuffersNames: uniformBuffers,
  41168. samplers: samplers,
  41169. defines: join,
  41170. fallbacks: fallbacks,
  41171. onCompiled: onCompiled,
  41172. onError: onError,
  41173. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41174. }, engine);
  41175. };
  41176. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41177. if (useInstances === void 0) { useInstances = null; }
  41178. if (useClipPlane === void 0) { useClipPlane = null; }
  41179. var scene = this.getScene();
  41180. var engine = scene.getEngine();
  41181. // Lights
  41182. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41183. defines._needNormals = true;
  41184. // Textures
  41185. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41186. if (defines._areTexturesDirty) {
  41187. defines._needUVs = false;
  41188. if (scene.texturesEnabled) {
  41189. if (scene.getEngine().getCaps().textureLOD) {
  41190. defines.LODBASEDMICROSFURACE = true;
  41191. }
  41192. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41194. }
  41195. else {
  41196. defines.ALBEDO = false;
  41197. }
  41198. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41200. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41201. }
  41202. else {
  41203. defines.AMBIENT = false;
  41204. }
  41205. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41207. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41208. }
  41209. else {
  41210. defines.OPACITY = false;
  41211. }
  41212. var reflectionTexture = this._getReflectionTexture();
  41213. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41214. defines.REFLECTION = true;
  41215. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41216. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41217. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41218. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41219. defines.INVERTCUBICMAP = true;
  41220. }
  41221. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41222. switch (reflectionTexture.coordinatesMode) {
  41223. case BABYLON.Texture.CUBIC_MODE:
  41224. case BABYLON.Texture.INVCUBIC_MODE:
  41225. defines.REFLECTIONMAP_CUBIC = true;
  41226. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41227. break;
  41228. case BABYLON.Texture.EXPLICIT_MODE:
  41229. defines.REFLECTIONMAP_EXPLICIT = true;
  41230. break;
  41231. case BABYLON.Texture.PLANAR_MODE:
  41232. defines.REFLECTIONMAP_PLANAR = true;
  41233. break;
  41234. case BABYLON.Texture.PROJECTION_MODE:
  41235. defines.REFLECTIONMAP_PROJECTION = true;
  41236. break;
  41237. case BABYLON.Texture.SKYBOX_MODE:
  41238. defines.REFLECTIONMAP_SKYBOX = true;
  41239. break;
  41240. case BABYLON.Texture.SPHERICAL_MODE:
  41241. defines.REFLECTIONMAP_SPHERICAL = true;
  41242. break;
  41243. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41244. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41245. break;
  41246. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41247. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41248. break;
  41249. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41250. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41251. break;
  41252. }
  41253. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41254. if (reflectionTexture.sphericalPolynomial) {
  41255. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41256. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41257. defines.USESPHERICALINVERTEX = false;
  41258. }
  41259. else {
  41260. defines.USESPHERICALINVERTEX = true;
  41261. }
  41262. }
  41263. }
  41264. }
  41265. else {
  41266. defines.REFLECTION = false;
  41267. defines.REFLECTIONMAP_3D = false;
  41268. defines.REFLECTIONMAP_SPHERICAL = false;
  41269. defines.REFLECTIONMAP_PLANAR = false;
  41270. defines.REFLECTIONMAP_CUBIC = false;
  41271. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41272. defines.REFLECTIONMAP_PROJECTION = false;
  41273. defines.REFLECTIONMAP_SKYBOX = false;
  41274. defines.REFLECTIONMAP_EXPLICIT = false;
  41275. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41276. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41277. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41278. defines.INVERTCUBICMAP = false;
  41279. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41280. defines.USESPHERICALINVERTEX = false;
  41281. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41282. defines.LODINREFLECTIONALPHA = false;
  41283. defines.GAMMAREFLECTION = false;
  41284. }
  41285. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41286. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41287. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41288. }
  41289. else {
  41290. defines.LIGHTMAP = false;
  41291. }
  41292. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41294. }
  41295. else {
  41296. defines.EMISSIVE = false;
  41297. }
  41298. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41299. if (this._metallicTexture) {
  41300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41301. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41302. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41303. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41304. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41305. }
  41306. else if (this._reflectivityTexture) {
  41307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41308. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41309. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41310. }
  41311. else {
  41312. defines.REFLECTIVITY = false;
  41313. }
  41314. if (this._microSurfaceTexture) {
  41315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41316. }
  41317. else {
  41318. defines.MICROSURFACEMAP = false;
  41319. }
  41320. }
  41321. else {
  41322. defines.REFLECTIVITY = false;
  41323. defines.MICROSURFACEMAP = false;
  41324. }
  41325. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41326. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41327. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41328. defines.PARALLAX = true;
  41329. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41330. }
  41331. else {
  41332. defines.PARALLAX = false;
  41333. }
  41334. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41335. }
  41336. else {
  41337. defines.BUMP = false;
  41338. }
  41339. var refractionTexture = this._getRefractionTexture();
  41340. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41341. defines.REFRACTION = true;
  41342. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41343. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41344. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41345. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41346. if (this._linkRefractionWithTransparency) {
  41347. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41348. }
  41349. }
  41350. else {
  41351. defines.REFRACTION = false;
  41352. }
  41353. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41354. defines.ENVIRONMENTBRDF = true;
  41355. }
  41356. else {
  41357. defines.ENVIRONMENTBRDF = false;
  41358. }
  41359. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41360. defines.ALPHAFROMALBEDO = true;
  41361. }
  41362. else {
  41363. defines.ALPHAFROMALBEDO = false;
  41364. }
  41365. }
  41366. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41367. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41368. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41369. if (!this.backFaceCulling && this._twoSidedLighting) {
  41370. defines.TWOSIDEDLIGHTING = true;
  41371. }
  41372. else {
  41373. defines.TWOSIDEDLIGHTING = false;
  41374. }
  41375. defines.ALPHATESTVALUE = this._alphaCutOff;
  41376. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41377. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41378. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41379. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41380. }
  41381. if (defines._areImageProcessingDirty) {
  41382. this._imageProcessingConfiguration.prepareDefines(defines);
  41383. }
  41384. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41385. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41386. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41387. // Misc.
  41388. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41389. // Values that need to be evaluated on every frame
  41390. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41391. // Attribs
  41392. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41393. };
  41394. /**
  41395. * Force shader compilation
  41396. */
  41397. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41398. var _this = this;
  41399. var localOptions = __assign({ clipPlane: false }, options);
  41400. var defines = new PBRMaterialDefines();
  41401. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41402. if (effect.isReady()) {
  41403. if (onCompiled) {
  41404. onCompiled(this);
  41405. }
  41406. }
  41407. else {
  41408. effect.onCompileObservable.add(function () {
  41409. if (onCompiled) {
  41410. onCompiled(_this);
  41411. }
  41412. });
  41413. }
  41414. };
  41415. /**
  41416. * Initializes the uniform buffer layout for the shader.
  41417. */
  41418. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41419. // Order is important !
  41420. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41421. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41422. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41423. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41424. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41425. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41426. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41427. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41428. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41429. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41430. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41431. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41432. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41433. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41434. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41435. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41436. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41437. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41438. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41439. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41440. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41441. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41442. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41443. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41444. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41445. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41446. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41447. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41448. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41449. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41450. this._uniformBuffer.addUniform("pointSize", 1);
  41451. this._uniformBuffer.create();
  41452. };
  41453. /**
  41454. * Unbinds the textures.
  41455. */
  41456. PBRBaseMaterial.prototype.unbind = function () {
  41457. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41458. this._uniformBuffer.setTexture("reflectionSampler", null);
  41459. }
  41460. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41461. this._uniformBuffer.setTexture("refractionSampler", null);
  41462. }
  41463. _super.prototype.unbind.call(this);
  41464. };
  41465. /**
  41466. * Binds the submesh data.
  41467. * @param world - The world matrix.
  41468. * @param mesh - The BJS mesh.
  41469. * @param subMesh - A submesh of the BJS mesh.
  41470. */
  41471. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41472. var scene = this.getScene();
  41473. var defines = subMesh._materialDefines;
  41474. if (!defines) {
  41475. return;
  41476. }
  41477. var effect = subMesh.effect;
  41478. if (!effect) {
  41479. return;
  41480. }
  41481. this._activeEffect = effect;
  41482. // Matrices
  41483. this.bindOnlyWorldMatrix(world);
  41484. // Normal Matrix
  41485. if (defines.OBJECTSPACE_NORMALMAP) {
  41486. world.toNormalMatrix(this._normalMatrix);
  41487. this.bindOnlyNormalMatrix(this._normalMatrix);
  41488. }
  41489. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41490. // Bones
  41491. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41492. var reflectionTexture = null;
  41493. if (mustRebind) {
  41494. this._uniformBuffer.bindToEffect(effect, "Material");
  41495. this.bindViewProjection(effect);
  41496. reflectionTexture = this._getReflectionTexture();
  41497. var refractionTexture = this._getRefractionTexture();
  41498. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41499. // Texture uniforms
  41500. if (scene.texturesEnabled) {
  41501. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41502. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41503. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41504. }
  41505. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41506. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41507. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41508. }
  41509. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41510. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41511. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41512. }
  41513. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41514. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41515. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41516. if (reflectionTexture.boundingBoxSize) {
  41517. var cubeTexture = reflectionTexture;
  41518. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41519. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41520. }
  41521. var polynomials = reflectionTexture.sphericalPolynomial;
  41522. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41523. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41524. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41525. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41526. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41527. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41528. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41529. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41530. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41531. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41532. }
  41533. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41534. }
  41535. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41536. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41537. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41538. }
  41539. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41540. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41541. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41542. }
  41543. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41544. if (this._metallicTexture) {
  41545. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41546. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41547. }
  41548. else if (this._reflectivityTexture) {
  41549. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41550. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41551. }
  41552. if (this._microSurfaceTexture) {
  41553. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41554. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41555. }
  41556. }
  41557. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41558. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41559. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41560. if (scene._mirroredCameraPosition) {
  41561. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41562. }
  41563. else {
  41564. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41565. }
  41566. }
  41567. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41568. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41569. var depth = 1.0;
  41570. if (!refractionTexture.isCube) {
  41571. if (refractionTexture.depth) {
  41572. depth = refractionTexture.depth;
  41573. }
  41574. }
  41575. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41576. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41577. }
  41578. }
  41579. // Point size
  41580. if (this.pointsCloud) {
  41581. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41582. }
  41583. // Colors
  41584. if (defines.METALLICWORKFLOW) {
  41585. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41586. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41587. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41588. }
  41589. else {
  41590. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41591. }
  41592. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41593. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41594. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41595. // Misc
  41596. this._lightingInfos.x = this._directIntensity;
  41597. this._lightingInfos.y = this._emissiveIntensity;
  41598. this._lightingInfos.z = this._environmentIntensity;
  41599. this._lightingInfos.w = this._specularIntensity;
  41600. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41601. }
  41602. // Textures
  41603. if (scene.texturesEnabled) {
  41604. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41605. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41606. }
  41607. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41608. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41609. }
  41610. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41611. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41612. }
  41613. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41614. if (defines.LODBASEDMICROSFURACE) {
  41615. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41616. }
  41617. else {
  41618. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41619. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41620. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41621. }
  41622. }
  41623. if (defines.ENVIRONMENTBRDF) {
  41624. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41625. }
  41626. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41627. if (defines.LODBASEDMICROSFURACE) {
  41628. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41629. }
  41630. else {
  41631. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41632. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41633. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41634. }
  41635. }
  41636. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41637. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41638. }
  41639. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41640. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41641. }
  41642. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41643. if (this._metallicTexture) {
  41644. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41645. }
  41646. else if (this._reflectivityTexture) {
  41647. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41648. }
  41649. if (this._microSurfaceTexture) {
  41650. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41651. }
  41652. }
  41653. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41654. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41655. }
  41656. }
  41657. // Clip plane
  41658. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41659. // Colors
  41660. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41661. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41662. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41663. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41664. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41665. }
  41666. if (mustRebind || !this.isFrozen) {
  41667. // Lights
  41668. if (scene.lightsEnabled && !this._disableLighting) {
  41669. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41670. }
  41671. // View
  41672. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41673. this.bindView(effect);
  41674. }
  41675. // Fog
  41676. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41677. // Morph targets
  41678. if (defines.NUM_MORPH_INFLUENCERS) {
  41679. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41680. }
  41681. // image processing
  41682. this._imageProcessingConfiguration.bind(this._activeEffect);
  41683. // Log. depth
  41684. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41685. }
  41686. this._uniformBuffer.update();
  41687. this._afterBind(mesh);
  41688. };
  41689. /**
  41690. * Returns the animatable textures.
  41691. * @returns - Array of animatable textures.
  41692. */
  41693. PBRBaseMaterial.prototype.getAnimatables = function () {
  41694. var results = [];
  41695. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41696. results.push(this._albedoTexture);
  41697. }
  41698. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41699. results.push(this._ambientTexture);
  41700. }
  41701. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41702. results.push(this._opacityTexture);
  41703. }
  41704. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41705. results.push(this._reflectionTexture);
  41706. }
  41707. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41708. results.push(this._emissiveTexture);
  41709. }
  41710. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41711. results.push(this._metallicTexture);
  41712. }
  41713. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41714. results.push(this._reflectivityTexture);
  41715. }
  41716. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41717. results.push(this._bumpTexture);
  41718. }
  41719. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41720. results.push(this._lightmapTexture);
  41721. }
  41722. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41723. results.push(this._refractionTexture);
  41724. }
  41725. return results;
  41726. };
  41727. /**
  41728. * Returns the texture used for reflections.
  41729. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41730. */
  41731. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41732. if (this._reflectionTexture) {
  41733. return this._reflectionTexture;
  41734. }
  41735. return this.getScene().environmentTexture;
  41736. };
  41737. /**
  41738. * Returns the texture used for refraction or null if none is used.
  41739. * @returns - Refection texture if present. If no refraction texture and refraction
  41740. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41741. */
  41742. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41743. if (this._refractionTexture) {
  41744. return this._refractionTexture;
  41745. }
  41746. if (this._linkRefractionWithTransparency) {
  41747. return this.getScene().environmentTexture;
  41748. }
  41749. return null;
  41750. };
  41751. /**
  41752. * Disposes the resources of the material.
  41753. * @param forceDisposeEffect - Forces the disposal of effects.
  41754. * @param forceDisposeTextures - Forces the disposal of all textures.
  41755. */
  41756. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41757. if (forceDisposeTextures) {
  41758. if (this._albedoTexture) {
  41759. this._albedoTexture.dispose();
  41760. }
  41761. if (this._ambientTexture) {
  41762. this._ambientTexture.dispose();
  41763. }
  41764. if (this._opacityTexture) {
  41765. this._opacityTexture.dispose();
  41766. }
  41767. if (this._reflectionTexture) {
  41768. this._reflectionTexture.dispose();
  41769. }
  41770. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41771. this._environmentBRDFTexture.dispose();
  41772. }
  41773. if (this._emissiveTexture) {
  41774. this._emissiveTexture.dispose();
  41775. }
  41776. if (this._metallicTexture) {
  41777. this._metallicTexture.dispose();
  41778. }
  41779. if (this._reflectivityTexture) {
  41780. this._reflectivityTexture.dispose();
  41781. }
  41782. if (this._bumpTexture) {
  41783. this._bumpTexture.dispose();
  41784. }
  41785. if (this._lightmapTexture) {
  41786. this._lightmapTexture.dispose();
  41787. }
  41788. if (this._refractionTexture) {
  41789. this._refractionTexture.dispose();
  41790. }
  41791. }
  41792. this._renderTargets.dispose();
  41793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41795. }
  41796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41797. };
  41798. /**
  41799. * Stores the reflectivity values based on metallic roughness workflow.
  41800. */
  41801. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41802. __decorate([
  41803. BABYLON.serializeAsImageProcessingConfiguration()
  41804. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41805. __decorate([
  41806. BABYLON.serialize()
  41807. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41808. __decorate([
  41809. BABYLON.serialize()
  41810. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41811. return PBRBaseMaterial;
  41812. }(BABYLON.PushMaterial));
  41813. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41814. })(BABYLON || (BABYLON = {}));
  41815. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41816. var BABYLON;
  41817. (function (BABYLON) {
  41818. /**
  41819. * The Physically based simple base material of BJS.
  41820. *
  41821. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41822. * It is used as the base class for both the specGloss and metalRough conventions.
  41823. */
  41824. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41825. __extends(PBRBaseSimpleMaterial, _super);
  41826. /**
  41827. * Instantiates a new PBRMaterial instance.
  41828. *
  41829. * @param name The material name
  41830. * @param scene The scene the material will be use in.
  41831. */
  41832. function PBRBaseSimpleMaterial(name, scene) {
  41833. var _this = _super.call(this, name, scene) || this;
  41834. /**
  41835. * Number of Simultaneous lights allowed on the material.
  41836. */
  41837. _this.maxSimultaneousLights = 4;
  41838. /**
  41839. * If sets to true, disables all the lights affecting the material.
  41840. */
  41841. _this.disableLighting = false;
  41842. /**
  41843. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41844. */
  41845. _this.invertNormalMapX = false;
  41846. /**
  41847. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41848. */
  41849. _this.invertNormalMapY = false;
  41850. /**
  41851. * Emissivie color used to self-illuminate the model.
  41852. */
  41853. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41854. /**
  41855. * Occlusion Channel Strenght.
  41856. */
  41857. _this.occlusionStrength = 1.0;
  41858. _this.useLightmapAsShadowmap = false;
  41859. _this._useAlphaFromAlbedoTexture = true;
  41860. _this._useAmbientInGrayScale = true;
  41861. return _this;
  41862. }
  41863. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41864. /**
  41865. * Gets the current double sided mode.
  41866. */
  41867. get: function () {
  41868. return this._twoSidedLighting;
  41869. },
  41870. /**
  41871. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41872. */
  41873. set: function (value) {
  41874. if (this._twoSidedLighting === value) {
  41875. return;
  41876. }
  41877. this._twoSidedLighting = value;
  41878. this.backFaceCulling = !value;
  41879. this._markAllSubMeshesAsTexturesDirty();
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. /**
  41885. * Return the active textures of the material.
  41886. */
  41887. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41888. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41889. if (this.environmentTexture) {
  41890. activeTextures.push(this.environmentTexture);
  41891. }
  41892. if (this.normalTexture) {
  41893. activeTextures.push(this.normalTexture);
  41894. }
  41895. if (this.emissiveTexture) {
  41896. activeTextures.push(this.emissiveTexture);
  41897. }
  41898. if (this.occlusionTexture) {
  41899. activeTextures.push(this.occlusionTexture);
  41900. }
  41901. if (this.lightmapTexture) {
  41902. activeTextures.push(this.lightmapTexture);
  41903. }
  41904. return activeTextures;
  41905. };
  41906. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41907. if (_super.prototype.hasTexture.call(this, texture)) {
  41908. return true;
  41909. }
  41910. if (this.lightmapTexture === texture) {
  41911. return true;
  41912. }
  41913. return false;
  41914. };
  41915. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41916. return "PBRBaseSimpleMaterial";
  41917. };
  41918. __decorate([
  41919. BABYLON.serialize(),
  41920. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41921. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41922. __decorate([
  41923. BABYLON.serialize(),
  41924. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41925. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41926. __decorate([
  41927. BABYLON.serializeAsTexture(),
  41928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41929. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41930. __decorate([
  41931. BABYLON.serialize(),
  41932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41933. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41934. __decorate([
  41935. BABYLON.serialize(),
  41936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41937. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41938. __decorate([
  41939. BABYLON.serializeAsTexture(),
  41940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41941. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41942. __decorate([
  41943. BABYLON.serializeAsColor3("emissive"),
  41944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41945. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41946. __decorate([
  41947. BABYLON.serializeAsTexture(),
  41948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41949. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41950. __decorate([
  41951. BABYLON.serialize(),
  41952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41953. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41954. __decorate([
  41955. BABYLON.serializeAsTexture(),
  41956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41957. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41958. __decorate([
  41959. BABYLON.serialize(),
  41960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41961. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41962. __decorate([
  41963. BABYLON.serialize()
  41964. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41965. __decorate([
  41966. BABYLON.serializeAsTexture(),
  41967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41968. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41969. __decorate([
  41970. BABYLON.serialize(),
  41971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41972. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41973. return PBRBaseSimpleMaterial;
  41974. }(BABYLON.PBRBaseMaterial));
  41975. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41976. })(BABYLON || (BABYLON = {}));
  41977. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41978. var BABYLON;
  41979. (function (BABYLON) {
  41980. /**
  41981. * The Physically based material of BJS.
  41982. *
  41983. * This offers the main features of a standard PBR material.
  41984. * For more information, please refer to the documentation :
  41985. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41986. */
  41987. var PBRMaterial = /** @class */ (function (_super) {
  41988. __extends(PBRMaterial, _super);
  41989. /**
  41990. * Instantiates a new PBRMaterial instance.
  41991. *
  41992. * @param name The material name
  41993. * @param scene The scene the material will be use in.
  41994. */
  41995. function PBRMaterial(name, scene) {
  41996. var _this = _super.call(this, name, scene) || this;
  41997. /**
  41998. * Intensity of the direct lights e.g. the four lights available in your scene.
  41999. * This impacts both the direct diffuse and specular highlights.
  42000. */
  42001. _this.directIntensity = 1.0;
  42002. /**
  42003. * Intensity of the emissive part of the material.
  42004. * This helps controlling the emissive effect without modifying the emissive color.
  42005. */
  42006. _this.emissiveIntensity = 1.0;
  42007. /**
  42008. * Intensity of the environment e.g. how much the environment will light the object
  42009. * either through harmonics for rough material or through the refelction for shiny ones.
  42010. */
  42011. _this.environmentIntensity = 1.0;
  42012. /**
  42013. * This is a special control allowing the reduction of the specular highlights coming from the
  42014. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42015. */
  42016. _this.specularIntensity = 1.0;
  42017. /**
  42018. * Debug Control allowing disabling the bump map on this material.
  42019. */
  42020. _this.disableBumpMap = false;
  42021. /**
  42022. * AKA Occlusion Texture Intensity in other nomenclature.
  42023. */
  42024. _this.ambientTextureStrength = 1.0;
  42025. /**
  42026. * The color of a material in ambient lighting.
  42027. */
  42028. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42029. /**
  42030. * AKA Diffuse Color in other nomenclature.
  42031. */
  42032. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42033. /**
  42034. * AKA Specular Color in other nomenclature.
  42035. */
  42036. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42037. /**
  42038. * The color reflected from the material.
  42039. */
  42040. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42041. /**
  42042. * The color emitted from the material.
  42043. */
  42044. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42045. /**
  42046. * AKA Glossiness in other nomenclature.
  42047. */
  42048. _this.microSurface = 1.0;
  42049. /**
  42050. * source material index of refraction (IOR)' / 'destination material IOR.
  42051. */
  42052. _this.indexOfRefraction = 0.66;
  42053. /**
  42054. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42055. */
  42056. _this.invertRefractionY = false;
  42057. /**
  42058. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42059. * Materials half opaque for instance using refraction could benefit from this control.
  42060. */
  42061. _this.linkRefractionWithTransparency = false;
  42062. _this.useLightmapAsShadowmap = false;
  42063. /**
  42064. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42065. */
  42066. _this.useAlphaFromAlbedoTexture = false;
  42067. /**
  42068. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42069. */
  42070. _this.forceAlphaTest = false;
  42071. /**
  42072. * Defines the alpha limits in alpha test mode.
  42073. */
  42074. _this.alphaCutOff = 0.4;
  42075. /**
  42076. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42077. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42078. */
  42079. _this.useSpecularOverAlpha = true;
  42080. /**
  42081. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42082. */
  42083. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42084. /**
  42085. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42086. */
  42087. _this.useRoughnessFromMetallicTextureAlpha = true;
  42088. /**
  42089. * Specifies if the metallic texture contains the roughness information in its green channel.
  42090. */
  42091. _this.useRoughnessFromMetallicTextureGreen = false;
  42092. /**
  42093. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42094. */
  42095. _this.useMetallnessFromMetallicTextureBlue = false;
  42096. /**
  42097. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42098. */
  42099. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42100. /**
  42101. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42102. */
  42103. _this.useAmbientInGrayScale = false;
  42104. /**
  42105. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42106. * The material will try to infer what glossiness each pixel should be.
  42107. */
  42108. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42109. /**
  42110. * BJS is using an harcoded light falloff based on a manually sets up range.
  42111. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42112. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42113. */
  42114. _this.usePhysicalLightFalloff = true;
  42115. /**
  42116. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42117. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42118. */
  42119. _this.useRadianceOverAlpha = true;
  42120. /**
  42121. * Allows using an object space normal map (instead of tangent space).
  42122. */
  42123. _this.useObjectSpaceNormalMap = false;
  42124. /**
  42125. * Allows using the bump map in parallax mode.
  42126. */
  42127. _this.useParallax = false;
  42128. /**
  42129. * Allows using the bump map in parallax occlusion mode.
  42130. */
  42131. _this.useParallaxOcclusion = false;
  42132. /**
  42133. * Controls the scale bias of the parallax mode.
  42134. */
  42135. _this.parallaxScaleBias = 0.05;
  42136. /**
  42137. * If sets to true, disables all the lights affecting the material.
  42138. */
  42139. _this.disableLighting = false;
  42140. /**
  42141. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42142. */
  42143. _this.forceIrradianceInFragment = false;
  42144. /**
  42145. * Number of Simultaneous lights allowed on the material.
  42146. */
  42147. _this.maxSimultaneousLights = 4;
  42148. /**
  42149. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42150. */
  42151. _this.invertNormalMapX = false;
  42152. /**
  42153. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42154. */
  42155. _this.invertNormalMapY = false;
  42156. /**
  42157. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42158. */
  42159. _this.twoSidedLighting = false;
  42160. /**
  42161. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42162. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42163. */
  42164. _this.useAlphaFresnel = false;
  42165. /**
  42166. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42167. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42168. */
  42169. _this.useLinearAlphaFresnel = false;
  42170. /**
  42171. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42172. * And/Or occlude the blended part.
  42173. */
  42174. _this.environmentBRDFTexture = null;
  42175. /**
  42176. * Force normal to face away from face.
  42177. */
  42178. _this.forceNormalForward = false;
  42179. /**
  42180. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42181. * makes the reflect vector face the model (under horizon).
  42182. */
  42183. _this.useHorizonOcclusion = true;
  42184. /**
  42185. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42186. * too much the area relying on ambient texture to define their ambient occlusion.
  42187. */
  42188. _this.useRadianceOcclusion = true;
  42189. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42190. return _this;
  42191. }
  42192. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42193. /**
  42194. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42195. */
  42196. get: function () {
  42197. return this._PBRMATERIAL_OPAQUE;
  42198. },
  42199. enumerable: true,
  42200. configurable: true
  42201. });
  42202. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42203. /**
  42204. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42205. */
  42206. get: function () {
  42207. return this._PBRMATERIAL_ALPHATEST;
  42208. },
  42209. enumerable: true,
  42210. configurable: true
  42211. });
  42212. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42213. /**
  42214. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42215. */
  42216. get: function () {
  42217. return this._PBRMATERIAL_ALPHABLEND;
  42218. },
  42219. enumerable: true,
  42220. configurable: true
  42221. });
  42222. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42223. /**
  42224. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42225. * They are also discarded below the alpha cutoff threshold to improve performances.
  42226. */
  42227. get: function () {
  42228. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42229. },
  42230. enumerable: true,
  42231. configurable: true
  42232. });
  42233. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42234. /**
  42235. * Gets the image processing configuration used either in this material.
  42236. */
  42237. get: function () {
  42238. return this._imageProcessingConfiguration;
  42239. },
  42240. /**
  42241. * Sets the Default image processing configuration used either in the this material.
  42242. *
  42243. * If sets to null, the scene one is in use.
  42244. */
  42245. set: function (value) {
  42246. this._attachImageProcessingConfiguration(value);
  42247. // Ensure the effect will be rebuilt.
  42248. this._markAllSubMeshesAsTexturesDirty();
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42254. /**
  42255. * Gets wether the color curves effect is enabled.
  42256. */
  42257. get: function () {
  42258. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42259. },
  42260. /**
  42261. * Sets wether the color curves effect is enabled.
  42262. */
  42263. set: function (value) {
  42264. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42270. /**
  42271. * Gets wether the color grading effect is enabled.
  42272. */
  42273. get: function () {
  42274. return this.imageProcessingConfiguration.colorGradingEnabled;
  42275. },
  42276. /**
  42277. * Gets wether the color grading effect is enabled.
  42278. */
  42279. set: function (value) {
  42280. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42281. },
  42282. enumerable: true,
  42283. configurable: true
  42284. });
  42285. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42286. /**
  42287. * Gets wether tonemapping is enabled or not.
  42288. */
  42289. get: function () {
  42290. return this._imageProcessingConfiguration.toneMappingEnabled;
  42291. },
  42292. /**
  42293. * Sets wether tonemapping is enabled or not
  42294. */
  42295. set: function (value) {
  42296. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42297. },
  42298. enumerable: true,
  42299. configurable: true
  42300. });
  42301. ;
  42302. ;
  42303. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42304. /**
  42305. * The camera exposure used on this material.
  42306. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42307. * This corresponds to a photographic exposure.
  42308. */
  42309. get: function () {
  42310. return this._imageProcessingConfiguration.exposure;
  42311. },
  42312. /**
  42313. * The camera exposure used on this material.
  42314. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42315. * This corresponds to a photographic exposure.
  42316. */
  42317. set: function (value) {
  42318. this._imageProcessingConfiguration.exposure = value;
  42319. },
  42320. enumerable: true,
  42321. configurable: true
  42322. });
  42323. ;
  42324. ;
  42325. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42326. /**
  42327. * Gets The camera contrast used on this material.
  42328. */
  42329. get: function () {
  42330. return this._imageProcessingConfiguration.contrast;
  42331. },
  42332. /**
  42333. * Sets The camera contrast used on this material.
  42334. */
  42335. set: function (value) {
  42336. this._imageProcessingConfiguration.contrast = value;
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42342. /**
  42343. * Gets the Color Grading 2D Lookup Texture.
  42344. */
  42345. get: function () {
  42346. return this._imageProcessingConfiguration.colorGradingTexture;
  42347. },
  42348. /**
  42349. * Sets the Color Grading 2D Lookup Texture.
  42350. */
  42351. set: function (value) {
  42352. this._imageProcessingConfiguration.colorGradingTexture = value;
  42353. },
  42354. enumerable: true,
  42355. configurable: true
  42356. });
  42357. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42358. /**
  42359. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42360. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42361. * 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;
  42362. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42363. */
  42364. get: function () {
  42365. return this._imageProcessingConfiguration.colorCurves;
  42366. },
  42367. /**
  42368. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42369. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42370. * 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;
  42371. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42372. */
  42373. set: function (value) {
  42374. this._imageProcessingConfiguration.colorCurves = value;
  42375. },
  42376. enumerable: true,
  42377. configurable: true
  42378. });
  42379. /**
  42380. * Returns the name of this material class.
  42381. */
  42382. PBRMaterial.prototype.getClassName = function () {
  42383. return "PBRMaterial";
  42384. };
  42385. /**
  42386. * Returns an array of the actively used textures.
  42387. * @returns - Array of BaseTextures
  42388. */
  42389. PBRMaterial.prototype.getActiveTextures = function () {
  42390. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42391. if (this._albedoTexture) {
  42392. activeTextures.push(this._albedoTexture);
  42393. }
  42394. if (this._ambientTexture) {
  42395. activeTextures.push(this._ambientTexture);
  42396. }
  42397. if (this._opacityTexture) {
  42398. activeTextures.push(this._opacityTexture);
  42399. }
  42400. if (this._reflectionTexture) {
  42401. activeTextures.push(this._reflectionTexture);
  42402. }
  42403. if (this._emissiveTexture) {
  42404. activeTextures.push(this._emissiveTexture);
  42405. }
  42406. if (this._reflectivityTexture) {
  42407. activeTextures.push(this._reflectivityTexture);
  42408. }
  42409. if (this._metallicTexture) {
  42410. activeTextures.push(this._metallicTexture);
  42411. }
  42412. if (this._microSurfaceTexture) {
  42413. activeTextures.push(this._microSurfaceTexture);
  42414. }
  42415. if (this._bumpTexture) {
  42416. activeTextures.push(this._bumpTexture);
  42417. }
  42418. if (this._lightmapTexture) {
  42419. activeTextures.push(this._lightmapTexture);
  42420. }
  42421. if (this._refractionTexture) {
  42422. activeTextures.push(this._refractionTexture);
  42423. }
  42424. return activeTextures;
  42425. };
  42426. /**
  42427. * Checks to see if a texture is used in the material.
  42428. * @param texture - Base texture to use.
  42429. * @returns - Boolean specifying if a texture is used in the material.
  42430. */
  42431. PBRMaterial.prototype.hasTexture = function (texture) {
  42432. if (_super.prototype.hasTexture.call(this, texture)) {
  42433. return true;
  42434. }
  42435. if (this._albedoTexture === texture) {
  42436. return true;
  42437. }
  42438. if (this._ambientTexture === texture) {
  42439. return true;
  42440. }
  42441. if (this._opacityTexture === texture) {
  42442. return true;
  42443. }
  42444. if (this._reflectionTexture === texture) {
  42445. return true;
  42446. }
  42447. if (this._reflectivityTexture === texture) {
  42448. return true;
  42449. }
  42450. if (this._metallicTexture === texture) {
  42451. return true;
  42452. }
  42453. if (this._microSurfaceTexture === texture) {
  42454. return true;
  42455. }
  42456. if (this._bumpTexture === texture) {
  42457. return true;
  42458. }
  42459. if (this._lightmapTexture === texture) {
  42460. return true;
  42461. }
  42462. if (this._refractionTexture === texture) {
  42463. return true;
  42464. }
  42465. return false;
  42466. };
  42467. /**
  42468. * Makes a duplicate of the current material.
  42469. * @param name - name to use for the new material.
  42470. */
  42471. PBRMaterial.prototype.clone = function (name) {
  42472. var _this = this;
  42473. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42474. clone.id = name;
  42475. clone.name = name;
  42476. return clone;
  42477. };
  42478. /**
  42479. * Serializes this PBR Material.
  42480. * @returns - An object with the serialized material.
  42481. */
  42482. PBRMaterial.prototype.serialize = function () {
  42483. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42484. serializationObject.customType = "BABYLON.PBRMaterial";
  42485. return serializationObject;
  42486. };
  42487. // Statics
  42488. /**
  42489. * Parses a PBR Material from a serialized object.
  42490. * @param source - Serialized object.
  42491. * @param scene - BJS scene instance.
  42492. * @param rootUrl - url for the scene object
  42493. * @returns - PBRMaterial
  42494. */
  42495. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42496. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42497. };
  42498. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42499. /**
  42500. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42501. */
  42502. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42503. /**
  42504. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42505. */
  42506. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42507. /**
  42508. * 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.
  42509. * They are also discarded below the alpha cutoff threshold to improve performances.
  42510. */
  42511. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42512. __decorate([
  42513. BABYLON.serialize(),
  42514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42515. ], PBRMaterial.prototype, "directIntensity", void 0);
  42516. __decorate([
  42517. BABYLON.serialize(),
  42518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42519. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42520. __decorate([
  42521. BABYLON.serialize(),
  42522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42523. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42524. __decorate([
  42525. BABYLON.serialize(),
  42526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42527. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42528. __decorate([
  42529. BABYLON.serialize(),
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42532. __decorate([
  42533. BABYLON.serializeAsTexture(),
  42534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42535. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42536. __decorate([
  42537. BABYLON.serializeAsTexture(),
  42538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42539. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42540. __decorate([
  42541. BABYLON.serialize(),
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42544. __decorate([
  42545. BABYLON.serializeAsTexture(),
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42547. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42548. __decorate([
  42549. BABYLON.serializeAsTexture(),
  42550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42551. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42552. __decorate([
  42553. BABYLON.serializeAsTexture(),
  42554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42555. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42556. __decorate([
  42557. BABYLON.serializeAsTexture(),
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42559. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42560. __decorate([
  42561. BABYLON.serializeAsTexture(),
  42562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42563. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42564. __decorate([
  42565. BABYLON.serialize(),
  42566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42567. ], PBRMaterial.prototype, "metallic", void 0);
  42568. __decorate([
  42569. BABYLON.serialize(),
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42571. ], PBRMaterial.prototype, "roughness", void 0);
  42572. __decorate([
  42573. BABYLON.serializeAsTexture(),
  42574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42575. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42576. __decorate([
  42577. BABYLON.serializeAsTexture(),
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42579. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42580. __decorate([
  42581. BABYLON.serializeAsTexture(),
  42582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42583. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42584. __decorate([
  42585. BABYLON.serializeAsTexture(),
  42586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42587. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42588. __decorate([
  42589. BABYLON.serializeAsColor3("ambient"),
  42590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42591. ], PBRMaterial.prototype, "ambientColor", void 0);
  42592. __decorate([
  42593. BABYLON.serializeAsColor3("albedo"),
  42594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42595. ], PBRMaterial.prototype, "albedoColor", void 0);
  42596. __decorate([
  42597. BABYLON.serializeAsColor3("reflectivity"),
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42599. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42600. __decorate([
  42601. BABYLON.serializeAsColor3("reflection"),
  42602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42603. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42604. __decorate([
  42605. BABYLON.serializeAsColor3("emissive"),
  42606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42607. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42608. __decorate([
  42609. BABYLON.serialize(),
  42610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42611. ], PBRMaterial.prototype, "microSurface", void 0);
  42612. __decorate([
  42613. BABYLON.serialize(),
  42614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42615. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42616. __decorate([
  42617. BABYLON.serialize(),
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42619. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42620. __decorate([
  42621. BABYLON.serialize(),
  42622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42623. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42624. __decorate([
  42625. BABYLON.serialize(),
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42627. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42628. __decorate([
  42629. BABYLON.serialize(),
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42631. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42632. __decorate([
  42633. BABYLON.serialize(),
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42635. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42636. __decorate([
  42637. BABYLON.serialize(),
  42638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42639. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42640. __decorate([
  42641. BABYLON.serialize(),
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42643. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42644. __decorate([
  42645. BABYLON.serialize(),
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42647. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42648. __decorate([
  42649. BABYLON.serialize(),
  42650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42651. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42652. __decorate([
  42653. BABYLON.serialize(),
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42656. __decorate([
  42657. BABYLON.serialize(),
  42658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42659. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42660. __decorate([
  42661. BABYLON.serialize(),
  42662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42663. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42664. __decorate([
  42665. BABYLON.serialize(),
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42668. __decorate([
  42669. BABYLON.serialize(),
  42670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42671. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42672. __decorate([
  42673. BABYLON.serialize(),
  42674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42675. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42676. __decorate([
  42677. BABYLON.serialize(),
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42679. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42680. __decorate([
  42681. BABYLON.serialize(),
  42682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42683. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42684. __decorate([
  42685. BABYLON.serialize(),
  42686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42687. ], PBRMaterial.prototype, "useParallax", void 0);
  42688. __decorate([
  42689. BABYLON.serialize(),
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42692. __decorate([
  42693. BABYLON.serialize(),
  42694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42695. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42696. __decorate([
  42697. BABYLON.serialize(),
  42698. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42699. ], PBRMaterial.prototype, "disableLighting", void 0);
  42700. __decorate([
  42701. BABYLON.serialize(),
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42703. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42704. __decorate([
  42705. BABYLON.serialize(),
  42706. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42707. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42708. __decorate([
  42709. BABYLON.serialize(),
  42710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42711. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42712. __decorate([
  42713. BABYLON.serialize(),
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42716. __decorate([
  42717. BABYLON.serialize(),
  42718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42719. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42720. __decorate([
  42721. BABYLON.serialize(),
  42722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42723. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42724. __decorate([
  42725. BABYLON.serialize(),
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42727. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42728. __decorate([
  42729. BABYLON.serializeAsTexture(),
  42730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42731. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42732. __decorate([
  42733. BABYLON.serialize(),
  42734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42735. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42736. __decorate([
  42737. BABYLON.serialize(),
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42740. __decorate([
  42741. BABYLON.serialize(),
  42742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42743. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42744. return PBRMaterial;
  42745. }(BABYLON.PBRBaseMaterial));
  42746. BABYLON.PBRMaterial = PBRMaterial;
  42747. })(BABYLON || (BABYLON = {}));
  42748. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42749. var BABYLON;
  42750. (function (BABYLON) {
  42751. /**
  42752. * The PBR material of BJS following the metal roughness convention.
  42753. *
  42754. * This fits to the PBR convention in the GLTF definition:
  42755. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42756. */
  42757. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42758. __extends(PBRMetallicRoughnessMaterial, _super);
  42759. /**
  42760. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42761. *
  42762. * @param name The material name
  42763. * @param scene The scene the material will be use in.
  42764. */
  42765. function PBRMetallicRoughnessMaterial(name, scene) {
  42766. var _this = _super.call(this, name, scene) || this;
  42767. _this._useRoughnessFromMetallicTextureAlpha = false;
  42768. _this._useRoughnessFromMetallicTextureGreen = true;
  42769. _this._useMetallnessFromMetallicTextureBlue = true;
  42770. _this.metallic = 1.0;
  42771. _this.roughness = 1.0;
  42772. return _this;
  42773. }
  42774. /**
  42775. * Return the currrent class name of the material.
  42776. */
  42777. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42778. return "PBRMetallicRoughnessMaterial";
  42779. };
  42780. /**
  42781. * Return the active textures of the material.
  42782. */
  42783. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42784. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42785. if (this.baseTexture) {
  42786. activeTextures.push(this.baseTexture);
  42787. }
  42788. if (this.metallicRoughnessTexture) {
  42789. activeTextures.push(this.metallicRoughnessTexture);
  42790. }
  42791. return activeTextures;
  42792. };
  42793. /**
  42794. * Checks to see if a texture is used in the material.
  42795. * @param texture - Base texture to use.
  42796. * @returns - Boolean specifying if a texture is used in the material.
  42797. */
  42798. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42799. if (_super.prototype.hasTexture.call(this, texture)) {
  42800. return true;
  42801. }
  42802. if (this.baseTexture === texture) {
  42803. return true;
  42804. }
  42805. if (this.metallicRoughnessTexture === texture) {
  42806. return true;
  42807. }
  42808. return false;
  42809. };
  42810. /**
  42811. * Makes a duplicate of the current material.
  42812. * @param name - name to use for the new material.
  42813. */
  42814. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42815. var _this = this;
  42816. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42817. clone.id = name;
  42818. clone.name = name;
  42819. return clone;
  42820. };
  42821. /**
  42822. * Serialize the material to a parsable JSON object.
  42823. */
  42824. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42826. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42827. return serializationObject;
  42828. };
  42829. /**
  42830. * Parses a JSON object correponding to the serialize function.
  42831. */
  42832. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42833. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42834. };
  42835. __decorate([
  42836. BABYLON.serializeAsColor3(),
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42838. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsTexture(),
  42841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42842. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42843. __decorate([
  42844. BABYLON.serialize(),
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42846. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42847. __decorate([
  42848. BABYLON.serialize(),
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42851. __decorate([
  42852. BABYLON.serializeAsTexture(),
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42854. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42855. return PBRMetallicRoughnessMaterial;
  42856. }(BABYLON.PBRBaseSimpleMaterial));
  42857. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42858. })(BABYLON || (BABYLON = {}));
  42859. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42860. var BABYLON;
  42861. (function (BABYLON) {
  42862. /**
  42863. * The PBR material of BJS following the specular glossiness convention.
  42864. *
  42865. * This fits to the PBR convention in the GLTF definition:
  42866. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42867. */
  42868. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42869. __extends(PBRSpecularGlossinessMaterial, _super);
  42870. /**
  42871. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42872. *
  42873. * @param name The material name
  42874. * @param scene The scene the material will be use in.
  42875. */
  42876. function PBRSpecularGlossinessMaterial(name, scene) {
  42877. var _this = _super.call(this, name, scene) || this;
  42878. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42879. return _this;
  42880. }
  42881. /**
  42882. * Return the currrent class name of the material.
  42883. */
  42884. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42885. return "PBRSpecularGlossinessMaterial";
  42886. };
  42887. /**
  42888. * Return the active textures of the material.
  42889. */
  42890. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42891. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42892. if (this.diffuseTexture) {
  42893. activeTextures.push(this.diffuseTexture);
  42894. }
  42895. if (this.specularGlossinessTexture) {
  42896. activeTextures.push(this.specularGlossinessTexture);
  42897. }
  42898. return activeTextures;
  42899. };
  42900. /**
  42901. * Checks to see if a texture is used in the material.
  42902. * @param texture - Base texture to use.
  42903. * @returns - Boolean specifying if a texture is used in the material.
  42904. */
  42905. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42906. if (_super.prototype.hasTexture.call(this, texture)) {
  42907. return true;
  42908. }
  42909. if (this.diffuseTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this.specularGlossinessTexture === texture) {
  42913. return true;
  42914. }
  42915. return false;
  42916. };
  42917. /**
  42918. * Makes a duplicate of the current material.
  42919. * @param name - name to use for the new material.
  42920. */
  42921. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42922. var _this = this;
  42923. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42924. clone.id = name;
  42925. clone.name = name;
  42926. return clone;
  42927. };
  42928. /**
  42929. * Serialize the material to a parsable JSON object.
  42930. */
  42931. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42933. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42934. return serializationObject;
  42935. };
  42936. /**
  42937. * Parses a JSON object correponding to the serialize function.
  42938. */
  42939. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42940. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42941. };
  42942. __decorate([
  42943. BABYLON.serializeAsColor3("diffuse"),
  42944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42945. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42946. __decorate([
  42947. BABYLON.serializeAsTexture(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42949. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42950. __decorate([
  42951. BABYLON.serializeAsColor3("specular"),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42953. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42954. __decorate([
  42955. BABYLON.serialize(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42957. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42958. __decorate([
  42959. BABYLON.serializeAsTexture(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42961. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42962. return PBRSpecularGlossinessMaterial;
  42963. }(BABYLON.PBRBaseSimpleMaterial));
  42964. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42965. })(BABYLON || (BABYLON = {}));
  42966. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42967. var BABYLON;
  42968. (function (BABYLON) {
  42969. BABYLON.CameraInputTypes = {};
  42970. var CameraInputsManager = /** @class */ (function () {
  42971. function CameraInputsManager(camera) {
  42972. this.attached = {};
  42973. this.camera = camera;
  42974. this.checkInputs = function () { };
  42975. }
  42976. /**
  42977. * Add an input method to a camera.
  42978. * builtin inputs example: camera.inputs.addGamepad();
  42979. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42980. * @param input camera input method
  42981. */
  42982. CameraInputsManager.prototype.add = function (input) {
  42983. var type = input.getSimpleName();
  42984. if (this.attached[type]) {
  42985. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42986. return;
  42987. }
  42988. this.attached[type] = input;
  42989. input.camera = this.camera;
  42990. //for checkInputs, we are dynamically creating a function
  42991. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42992. if (input.checkInputs) {
  42993. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42994. }
  42995. if (this.attachedElement) {
  42996. input.attachControl(this.attachedElement);
  42997. }
  42998. };
  42999. /**
  43000. * Remove a specific input method from a camera
  43001. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43002. * @param inputToRemove camera input method
  43003. */
  43004. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43005. for (var cam in this.attached) {
  43006. var input = this.attached[cam];
  43007. if (input === inputToRemove) {
  43008. input.detachControl(this.attachedElement);
  43009. input.camera = null;
  43010. delete this.attached[cam];
  43011. this.rebuildInputCheck();
  43012. }
  43013. }
  43014. };
  43015. CameraInputsManager.prototype.removeByType = function (inputType) {
  43016. for (var cam in this.attached) {
  43017. var input = this.attached[cam];
  43018. if (input.getClassName() === inputType) {
  43019. input.detachControl(this.attachedElement);
  43020. input.camera = null;
  43021. delete this.attached[cam];
  43022. this.rebuildInputCheck();
  43023. }
  43024. }
  43025. };
  43026. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43027. var current = this.checkInputs;
  43028. return function () {
  43029. current();
  43030. fn();
  43031. };
  43032. };
  43033. CameraInputsManager.prototype.attachInput = function (input) {
  43034. if (this.attachedElement) {
  43035. input.attachControl(this.attachedElement, this.noPreventDefault);
  43036. }
  43037. };
  43038. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43039. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43040. if (this.attachedElement) {
  43041. return;
  43042. }
  43043. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43044. this.attachedElement = element;
  43045. this.noPreventDefault = noPreventDefault;
  43046. for (var cam in this.attached) {
  43047. this.attached[cam].attachControl(element, noPreventDefault);
  43048. }
  43049. };
  43050. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43051. if (disconnect === void 0) { disconnect = false; }
  43052. if (this.attachedElement !== element) {
  43053. return;
  43054. }
  43055. for (var cam in this.attached) {
  43056. this.attached[cam].detachControl(element);
  43057. if (disconnect) {
  43058. this.attached[cam].camera = null;
  43059. }
  43060. }
  43061. this.attachedElement = null;
  43062. };
  43063. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43064. this.checkInputs = function () { };
  43065. for (var cam in this.attached) {
  43066. var input = this.attached[cam];
  43067. if (input.checkInputs) {
  43068. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43069. }
  43070. }
  43071. };
  43072. /**
  43073. * Remove all attached input methods from a camera
  43074. */
  43075. CameraInputsManager.prototype.clear = function () {
  43076. if (this.attachedElement) {
  43077. this.detachElement(this.attachedElement, true);
  43078. }
  43079. this.attached = {};
  43080. this.attachedElement = null;
  43081. this.checkInputs = function () { };
  43082. };
  43083. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43084. var inputs = {};
  43085. for (var cam in this.attached) {
  43086. var input = this.attached[cam];
  43087. var res = BABYLON.SerializationHelper.Serialize(input);
  43088. inputs[input.getClassName()] = res;
  43089. }
  43090. serializedCamera.inputsmgr = inputs;
  43091. };
  43092. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43093. var parsedInputs = parsedCamera.inputsmgr;
  43094. if (parsedInputs) {
  43095. this.clear();
  43096. for (var n in parsedInputs) {
  43097. var construct = BABYLON.CameraInputTypes[n];
  43098. if (construct) {
  43099. var parsedinput = parsedInputs[n];
  43100. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43101. this.add(input);
  43102. }
  43103. }
  43104. }
  43105. else {
  43106. //2016-03-08 this part is for managing backward compatibility
  43107. for (var n in this.attached) {
  43108. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43109. if (construct) {
  43110. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43111. this.remove(this.attached[n]);
  43112. this.add(input);
  43113. }
  43114. }
  43115. }
  43116. };
  43117. return CameraInputsManager;
  43118. }());
  43119. BABYLON.CameraInputsManager = CameraInputsManager;
  43120. })(BABYLON || (BABYLON = {}));
  43121. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43122. var BABYLON;
  43123. (function (BABYLON) {
  43124. var TargetCamera = /** @class */ (function (_super) {
  43125. __extends(TargetCamera, _super);
  43126. function TargetCamera(name, position, scene) {
  43127. var _this = _super.call(this, name, position, scene) || this;
  43128. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43129. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43130. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43131. _this.speed = 2.0;
  43132. _this.noRotationConstraint = false;
  43133. _this.lockedTarget = null;
  43134. _this._currentTarget = BABYLON.Vector3.Zero();
  43135. _this._viewMatrix = BABYLON.Matrix.Zero();
  43136. _this._camMatrix = BABYLON.Matrix.Zero();
  43137. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43138. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43139. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43140. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43141. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43142. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43143. _this._tempMatrix = BABYLON.Matrix.Zero();
  43144. return _this;
  43145. }
  43146. TargetCamera.prototype.getFrontPosition = function (distance) {
  43147. this.getWorldMatrix();
  43148. var direction = this.getTarget().subtract(this.position);
  43149. direction.normalize();
  43150. direction.scaleInPlace(distance);
  43151. return this.globalPosition.add(direction);
  43152. };
  43153. TargetCamera.prototype._getLockedTargetPosition = function () {
  43154. if (!this.lockedTarget) {
  43155. return null;
  43156. }
  43157. if (this.lockedTarget.absolutePosition) {
  43158. this.lockedTarget.computeWorldMatrix();
  43159. }
  43160. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43161. };
  43162. TargetCamera.prototype.storeState = function () {
  43163. this._storedPosition = this.position.clone();
  43164. this._storedRotation = this.rotation.clone();
  43165. if (this.rotationQuaternion) {
  43166. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43167. }
  43168. return _super.prototype.storeState.call(this);
  43169. };
  43170. /**
  43171. * Restored camera state. You must call storeState() first
  43172. */
  43173. TargetCamera.prototype._restoreStateValues = function () {
  43174. if (!_super.prototype._restoreStateValues.call(this)) {
  43175. return false;
  43176. }
  43177. this.position = this._storedPosition.clone();
  43178. this.rotation = this._storedRotation.clone();
  43179. if (this.rotationQuaternion) {
  43180. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43181. }
  43182. this.cameraDirection.copyFromFloats(0, 0, 0);
  43183. this.cameraRotation.copyFromFloats(0, 0);
  43184. return true;
  43185. };
  43186. // Cache
  43187. TargetCamera.prototype._initCache = function () {
  43188. _super.prototype._initCache.call(this);
  43189. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43190. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43191. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43192. };
  43193. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43194. if (!ignoreParentClass) {
  43195. _super.prototype._updateCache.call(this);
  43196. }
  43197. var lockedTargetPosition = this._getLockedTargetPosition();
  43198. if (!lockedTargetPosition) {
  43199. this._cache.lockedTarget = null;
  43200. }
  43201. else {
  43202. if (!this._cache.lockedTarget) {
  43203. this._cache.lockedTarget = lockedTargetPosition.clone();
  43204. }
  43205. else {
  43206. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43207. }
  43208. }
  43209. this._cache.rotation.copyFrom(this.rotation);
  43210. if (this.rotationQuaternion)
  43211. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43212. };
  43213. // Synchronized
  43214. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43215. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43216. return false;
  43217. }
  43218. var lockedTargetPosition = this._getLockedTargetPosition();
  43219. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43220. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43221. };
  43222. // Methods
  43223. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43224. var engine = this.getEngine();
  43225. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43226. };
  43227. // Target
  43228. TargetCamera.prototype.setTarget = function (target) {
  43229. this.upVector.normalize();
  43230. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43231. this._camMatrix.invert();
  43232. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43233. var vDir = target.subtract(this.position);
  43234. if (vDir.x >= 0.0) {
  43235. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43236. }
  43237. else {
  43238. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43239. }
  43240. this.rotation.z = 0;
  43241. if (isNaN(this.rotation.x)) {
  43242. this.rotation.x = 0;
  43243. }
  43244. if (isNaN(this.rotation.y)) {
  43245. this.rotation.y = 0;
  43246. }
  43247. if (isNaN(this.rotation.z)) {
  43248. this.rotation.z = 0;
  43249. }
  43250. if (this.rotationQuaternion) {
  43251. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43252. }
  43253. };
  43254. /**
  43255. * Return the current target position of the camera. This value is expressed in local space.
  43256. */
  43257. TargetCamera.prototype.getTarget = function () {
  43258. return this._currentTarget;
  43259. };
  43260. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43261. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43262. };
  43263. TargetCamera.prototype._updatePosition = function () {
  43264. if (this.parent) {
  43265. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43266. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43267. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43268. return;
  43269. }
  43270. this.position.addInPlace(this.cameraDirection);
  43271. };
  43272. TargetCamera.prototype._checkInputs = function () {
  43273. var needToMove = this._decideIfNeedsToMove();
  43274. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43275. // Move
  43276. if (needToMove) {
  43277. this._updatePosition();
  43278. }
  43279. // Rotate
  43280. if (needToRotate) {
  43281. this.rotation.x += this.cameraRotation.x;
  43282. this.rotation.y += this.cameraRotation.y;
  43283. //rotate, if quaternion is set and rotation was used
  43284. if (this.rotationQuaternion) {
  43285. var len = this.rotation.lengthSquared();
  43286. if (len) {
  43287. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43288. }
  43289. }
  43290. if (!this.noRotationConstraint) {
  43291. var limit = (Math.PI / 2) * 0.95;
  43292. if (this.rotation.x > limit)
  43293. this.rotation.x = limit;
  43294. if (this.rotation.x < -limit)
  43295. this.rotation.x = -limit;
  43296. }
  43297. }
  43298. // Inertia
  43299. if (needToMove) {
  43300. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43301. this.cameraDirection.x = 0;
  43302. }
  43303. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43304. this.cameraDirection.y = 0;
  43305. }
  43306. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43307. this.cameraDirection.z = 0;
  43308. }
  43309. this.cameraDirection.scaleInPlace(this.inertia);
  43310. }
  43311. if (needToRotate) {
  43312. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43313. this.cameraRotation.x = 0;
  43314. }
  43315. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43316. this.cameraRotation.y = 0;
  43317. }
  43318. this.cameraRotation.scaleInPlace(this.inertia);
  43319. }
  43320. _super.prototype._checkInputs.call(this);
  43321. };
  43322. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43323. if (this.rotationQuaternion) {
  43324. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43325. }
  43326. else {
  43327. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43328. }
  43329. //update the up vector!
  43330. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43331. };
  43332. TargetCamera.prototype._getViewMatrix = function () {
  43333. if (this.lockedTarget) {
  43334. this.setTarget(this._getLockedTargetPosition());
  43335. }
  43336. // Compute
  43337. this._updateCameraRotationMatrix();
  43338. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43339. // Computing target and final matrix
  43340. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43341. if (this.getScene().useRightHandedSystem) {
  43342. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43343. }
  43344. else {
  43345. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43346. }
  43347. return this._viewMatrix;
  43348. };
  43349. /**
  43350. * @override
  43351. * Override Camera.createRigCamera
  43352. */
  43353. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43354. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43355. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43356. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43357. if (!this.rotationQuaternion) {
  43358. this.rotationQuaternion = new BABYLON.Quaternion();
  43359. }
  43360. rigCamera._cameraRigParams = {};
  43361. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43362. }
  43363. return rigCamera;
  43364. }
  43365. return null;
  43366. };
  43367. /**
  43368. * @override
  43369. * Override Camera._updateRigCameras
  43370. */
  43371. TargetCamera.prototype._updateRigCameras = function () {
  43372. var camLeft = this._rigCameras[0];
  43373. var camRight = this._rigCameras[1];
  43374. switch (this.cameraRigMode) {
  43375. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43376. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43379. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43380. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43381. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43382. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43383. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43384. camLeft.setTarget(this.getTarget());
  43385. camRight.setTarget(this.getTarget());
  43386. break;
  43387. case BABYLON.Camera.RIG_MODE_VR:
  43388. if (camLeft.rotationQuaternion) {
  43389. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43390. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43391. }
  43392. else {
  43393. camLeft.rotation.copyFrom(this.rotation);
  43394. camRight.rotation.copyFrom(this.rotation);
  43395. }
  43396. camLeft.position.copyFrom(this.position);
  43397. camRight.position.copyFrom(this.position);
  43398. break;
  43399. }
  43400. _super.prototype._updateRigCameras.call(this);
  43401. };
  43402. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43403. if (!this._rigCamTransformMatrix) {
  43404. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43405. }
  43406. var target = this.getTarget();
  43407. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43408. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43409. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43410. };
  43411. TargetCamera.prototype.getClassName = function () {
  43412. return "TargetCamera";
  43413. };
  43414. __decorate([
  43415. BABYLON.serializeAsVector3()
  43416. ], TargetCamera.prototype, "rotation", void 0);
  43417. __decorate([
  43418. BABYLON.serialize()
  43419. ], TargetCamera.prototype, "speed", void 0);
  43420. __decorate([
  43421. BABYLON.serializeAsMeshReference("lockedTargetId")
  43422. ], TargetCamera.prototype, "lockedTarget", void 0);
  43423. return TargetCamera;
  43424. }(BABYLON.Camera));
  43425. BABYLON.TargetCamera = TargetCamera;
  43426. })(BABYLON || (BABYLON = {}));
  43427. //# sourceMappingURL=babylon.targetCamera.js.map
  43428. var BABYLON;
  43429. (function (BABYLON) {
  43430. var FreeCameraMouseInput = /** @class */ (function () {
  43431. function FreeCameraMouseInput(touchEnabled) {
  43432. if (touchEnabled === void 0) { touchEnabled = true; }
  43433. this.touchEnabled = touchEnabled;
  43434. this.buttons = [0, 1, 2];
  43435. this.angularSensibility = 2000.0;
  43436. this.previousPosition = null;
  43437. }
  43438. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43439. var _this = this;
  43440. var engine = this.camera.getEngine();
  43441. if (!this._pointerInput) {
  43442. this._pointerInput = function (p, s) {
  43443. var evt = p.event;
  43444. if (engine.isInVRExclusivePointerMode) {
  43445. return;
  43446. }
  43447. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43448. return;
  43449. }
  43450. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43451. return;
  43452. }
  43453. var srcElement = (evt.srcElement || evt.target);
  43454. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43455. try {
  43456. srcElement.setPointerCapture(evt.pointerId);
  43457. }
  43458. catch (e) {
  43459. //Nothing to do with the error. Execution will continue.
  43460. }
  43461. _this.previousPosition = {
  43462. x: evt.clientX,
  43463. y: evt.clientY
  43464. };
  43465. if (!noPreventDefault) {
  43466. evt.preventDefault();
  43467. element.focus();
  43468. }
  43469. }
  43470. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43471. try {
  43472. srcElement.releasePointerCapture(evt.pointerId);
  43473. }
  43474. catch (e) {
  43475. //Nothing to do with the error.
  43476. }
  43477. _this.previousPosition = null;
  43478. if (!noPreventDefault) {
  43479. evt.preventDefault();
  43480. }
  43481. }
  43482. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43483. if (!_this.previousPosition || engine.isPointerLock) {
  43484. return;
  43485. }
  43486. var offsetX = evt.clientX - _this.previousPosition.x;
  43487. var offsetY = evt.clientY - _this.previousPosition.y;
  43488. if (_this.camera.getScene().useRightHandedSystem) {
  43489. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43490. }
  43491. else {
  43492. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43493. }
  43494. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43495. _this.previousPosition = {
  43496. x: evt.clientX,
  43497. y: evt.clientY
  43498. };
  43499. if (!noPreventDefault) {
  43500. evt.preventDefault();
  43501. }
  43502. }
  43503. };
  43504. }
  43505. this._onMouseMove = function (evt) {
  43506. if (!engine.isPointerLock) {
  43507. return;
  43508. }
  43509. if (engine.isInVRExclusivePointerMode) {
  43510. return;
  43511. }
  43512. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43513. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43514. if (_this.camera.getScene().useRightHandedSystem) {
  43515. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43516. }
  43517. else {
  43518. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43519. }
  43520. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43521. _this.previousPosition = null;
  43522. if (!noPreventDefault) {
  43523. evt.preventDefault();
  43524. }
  43525. };
  43526. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43527. element.addEventListener("mousemove", this._onMouseMove, false);
  43528. };
  43529. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43530. if (this._observer && element) {
  43531. this.camera.getScene().onPointerObservable.remove(this._observer);
  43532. if (this._onMouseMove) {
  43533. element.removeEventListener("mousemove", this._onMouseMove);
  43534. }
  43535. this._observer = null;
  43536. this._onMouseMove = null;
  43537. this.previousPosition = null;
  43538. }
  43539. };
  43540. FreeCameraMouseInput.prototype.getClassName = function () {
  43541. return "FreeCameraMouseInput";
  43542. };
  43543. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43544. return "mouse";
  43545. };
  43546. __decorate([
  43547. BABYLON.serialize()
  43548. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43549. __decorate([
  43550. BABYLON.serialize()
  43551. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43552. return FreeCameraMouseInput;
  43553. }());
  43554. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43555. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43556. })(BABYLON || (BABYLON = {}));
  43557. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43558. var BABYLON;
  43559. (function (BABYLON) {
  43560. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43561. function FreeCameraKeyboardMoveInput() {
  43562. this._keys = new Array();
  43563. this.keysUp = [38];
  43564. this.keysDown = [40];
  43565. this.keysLeft = [37];
  43566. this.keysRight = [39];
  43567. }
  43568. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43569. var _this = this;
  43570. if (this._onCanvasBlurObserver) {
  43571. return;
  43572. }
  43573. this._scene = this.camera.getScene();
  43574. this._engine = this._scene.getEngine();
  43575. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43576. _this._keys = [];
  43577. });
  43578. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43579. var evt = info.event;
  43580. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43581. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43582. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43583. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43584. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43585. var index = _this._keys.indexOf(evt.keyCode);
  43586. if (index === -1) {
  43587. _this._keys.push(evt.keyCode);
  43588. }
  43589. if (!noPreventDefault) {
  43590. evt.preventDefault();
  43591. }
  43592. }
  43593. }
  43594. else {
  43595. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43596. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43597. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43598. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43599. var index = _this._keys.indexOf(evt.keyCode);
  43600. if (index >= 0) {
  43601. _this._keys.splice(index, 1);
  43602. }
  43603. if (!noPreventDefault) {
  43604. evt.preventDefault();
  43605. }
  43606. }
  43607. }
  43608. });
  43609. };
  43610. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43611. if (this._scene) {
  43612. if (this._onKeyboardObserver) {
  43613. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43614. }
  43615. if (this._onCanvasBlurObserver) {
  43616. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43617. }
  43618. this._onKeyboardObserver = null;
  43619. this._onCanvasBlurObserver = null;
  43620. }
  43621. this._keys = [];
  43622. };
  43623. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43624. if (this._onKeyboardObserver) {
  43625. var camera = this.camera;
  43626. // Keyboard
  43627. for (var index = 0; index < this._keys.length; index++) {
  43628. var keyCode = this._keys[index];
  43629. var speed = camera._computeLocalCameraSpeed();
  43630. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43631. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43632. }
  43633. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43634. camera._localDirection.copyFromFloats(0, 0, speed);
  43635. }
  43636. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43637. camera._localDirection.copyFromFloats(speed, 0, 0);
  43638. }
  43639. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43640. camera._localDirection.copyFromFloats(0, 0, -speed);
  43641. }
  43642. if (camera.getScene().useRightHandedSystem) {
  43643. camera._localDirection.z *= -1;
  43644. }
  43645. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43646. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43647. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43648. }
  43649. }
  43650. };
  43651. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43652. return "FreeCameraKeyboardMoveInput";
  43653. };
  43654. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43655. this._keys = [];
  43656. };
  43657. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43658. return "keyboard";
  43659. };
  43660. __decorate([
  43661. BABYLON.serialize()
  43662. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43663. __decorate([
  43664. BABYLON.serialize()
  43665. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43666. __decorate([
  43667. BABYLON.serialize()
  43668. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43669. __decorate([
  43670. BABYLON.serialize()
  43671. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43672. return FreeCameraKeyboardMoveInput;
  43673. }());
  43674. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43675. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43676. })(BABYLON || (BABYLON = {}));
  43677. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43678. var BABYLON;
  43679. (function (BABYLON) {
  43680. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43681. __extends(FreeCameraInputsManager, _super);
  43682. function FreeCameraInputsManager(camera) {
  43683. return _super.call(this, camera) || this;
  43684. }
  43685. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43686. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43687. return this;
  43688. };
  43689. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43690. if (touchEnabled === void 0) { touchEnabled = true; }
  43691. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43692. return this;
  43693. };
  43694. FreeCameraInputsManager.prototype.addGamepad = function () {
  43695. this.add(new BABYLON.FreeCameraGamepadInput());
  43696. return this;
  43697. };
  43698. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43699. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43700. return this;
  43701. };
  43702. FreeCameraInputsManager.prototype.addTouch = function () {
  43703. this.add(new BABYLON.FreeCameraTouchInput());
  43704. return this;
  43705. };
  43706. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43707. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43708. return this;
  43709. };
  43710. return FreeCameraInputsManager;
  43711. }(BABYLON.CameraInputsManager));
  43712. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43713. })(BABYLON || (BABYLON = {}));
  43714. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43715. var BABYLON;
  43716. (function (BABYLON) {
  43717. var FreeCamera = /** @class */ (function (_super) {
  43718. __extends(FreeCamera, _super);
  43719. function FreeCamera(name, position, scene) {
  43720. var _this = _super.call(this, name, position, scene) || this;
  43721. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43722. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43723. _this.checkCollisions = false;
  43724. _this.applyGravity = false;
  43725. _this._needMoveForGravity = false;
  43726. _this._oldPosition = BABYLON.Vector3.Zero();
  43727. _this._diffPosition = BABYLON.Vector3.Zero();
  43728. _this._newPosition = BABYLON.Vector3.Zero();
  43729. // Collisions
  43730. _this._collisionMask = -1;
  43731. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43732. if (collidedMesh === void 0) { collidedMesh = null; }
  43733. //TODO move this to the collision coordinator!
  43734. if (_this.getScene().workerCollisions)
  43735. newPosition.multiplyInPlace(_this._collider._radius);
  43736. var updatePosition = function (newPos) {
  43737. _this._newPosition.copyFrom(newPos);
  43738. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43739. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43740. _this.position.addInPlace(_this._diffPosition);
  43741. if (_this.onCollide && collidedMesh) {
  43742. _this.onCollide(collidedMesh);
  43743. }
  43744. }
  43745. };
  43746. updatePosition(newPosition);
  43747. };
  43748. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43749. _this.inputs.addKeyboard().addMouse();
  43750. return _this;
  43751. }
  43752. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43753. //-- begin properties for backward compatibility for inputs
  43754. /**
  43755. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43756. * Higher values reduce sensitivity.
  43757. */
  43758. get: function () {
  43759. var mouse = this.inputs.attached["mouse"];
  43760. if (mouse)
  43761. return mouse.angularSensibility;
  43762. return 0;
  43763. },
  43764. /**
  43765. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43766. * Higher values reduce sensitivity.
  43767. */
  43768. set: function (value) {
  43769. var mouse = this.inputs.attached["mouse"];
  43770. if (mouse)
  43771. mouse.angularSensibility = value;
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43777. get: function () {
  43778. var keyboard = this.inputs.attached["keyboard"];
  43779. if (keyboard)
  43780. return keyboard.keysUp;
  43781. return [];
  43782. },
  43783. set: function (value) {
  43784. var keyboard = this.inputs.attached["keyboard"];
  43785. if (keyboard)
  43786. keyboard.keysUp = value;
  43787. },
  43788. enumerable: true,
  43789. configurable: true
  43790. });
  43791. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43792. get: function () {
  43793. var keyboard = this.inputs.attached["keyboard"];
  43794. if (keyboard)
  43795. return keyboard.keysDown;
  43796. return [];
  43797. },
  43798. set: function (value) {
  43799. var keyboard = this.inputs.attached["keyboard"];
  43800. if (keyboard)
  43801. keyboard.keysDown = value;
  43802. },
  43803. enumerable: true,
  43804. configurable: true
  43805. });
  43806. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43807. get: function () {
  43808. var keyboard = this.inputs.attached["keyboard"];
  43809. if (keyboard)
  43810. return keyboard.keysLeft;
  43811. return [];
  43812. },
  43813. set: function (value) {
  43814. var keyboard = this.inputs.attached["keyboard"];
  43815. if (keyboard)
  43816. keyboard.keysLeft = value;
  43817. },
  43818. enumerable: true,
  43819. configurable: true
  43820. });
  43821. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43822. get: function () {
  43823. var keyboard = this.inputs.attached["keyboard"];
  43824. if (keyboard)
  43825. return keyboard.keysRight;
  43826. return [];
  43827. },
  43828. set: function (value) {
  43829. var keyboard = this.inputs.attached["keyboard"];
  43830. if (keyboard)
  43831. keyboard.keysRight = value;
  43832. },
  43833. enumerable: true,
  43834. configurable: true
  43835. });
  43836. // Controls
  43837. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43838. this.inputs.attachElement(element, noPreventDefault);
  43839. };
  43840. FreeCamera.prototype.detachControl = function (element) {
  43841. this.inputs.detachElement(element);
  43842. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43843. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43844. };
  43845. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43846. get: function () {
  43847. return this._collisionMask;
  43848. },
  43849. set: function (mask) {
  43850. this._collisionMask = !isNaN(mask) ? mask : -1;
  43851. },
  43852. enumerable: true,
  43853. configurable: true
  43854. });
  43855. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43856. var globalPosition;
  43857. if (this.parent) {
  43858. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43859. }
  43860. else {
  43861. globalPosition = this.position;
  43862. }
  43863. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43864. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43865. if (!this._collider) {
  43866. this._collider = new BABYLON.Collider();
  43867. }
  43868. this._collider._radius = this.ellipsoid;
  43869. this._collider.collisionMask = this._collisionMask;
  43870. //no need for clone, as long as gravity is not on.
  43871. var actualDisplacement = displacement;
  43872. //add gravity to the direction to prevent the dual-collision checking
  43873. if (this.applyGravity) {
  43874. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43875. actualDisplacement = displacement.add(this.getScene().gravity);
  43876. }
  43877. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43878. };
  43879. FreeCamera.prototype._checkInputs = function () {
  43880. if (!this._localDirection) {
  43881. this._localDirection = BABYLON.Vector3.Zero();
  43882. this._transformedDirection = BABYLON.Vector3.Zero();
  43883. }
  43884. this.inputs.checkInputs();
  43885. _super.prototype._checkInputs.call(this);
  43886. };
  43887. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43888. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43889. };
  43890. FreeCamera.prototype._updatePosition = function () {
  43891. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43892. this._collideWithWorld(this.cameraDirection);
  43893. }
  43894. else {
  43895. _super.prototype._updatePosition.call(this);
  43896. }
  43897. };
  43898. FreeCamera.prototype.dispose = function () {
  43899. this.inputs.clear();
  43900. _super.prototype.dispose.call(this);
  43901. };
  43902. FreeCamera.prototype.getClassName = function () {
  43903. return "FreeCamera";
  43904. };
  43905. __decorate([
  43906. BABYLON.serializeAsVector3()
  43907. ], FreeCamera.prototype, "ellipsoid", void 0);
  43908. __decorate([
  43909. BABYLON.serializeAsVector3()
  43910. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43911. __decorate([
  43912. BABYLON.serialize()
  43913. ], FreeCamera.prototype, "checkCollisions", void 0);
  43914. __decorate([
  43915. BABYLON.serialize()
  43916. ], FreeCamera.prototype, "applyGravity", void 0);
  43917. return FreeCamera;
  43918. }(BABYLON.TargetCamera));
  43919. BABYLON.FreeCamera = FreeCamera;
  43920. })(BABYLON || (BABYLON = {}));
  43921. //# sourceMappingURL=babylon.freeCamera.js.map
  43922. var BABYLON;
  43923. (function (BABYLON) {
  43924. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43925. function ArcRotateCameraKeyboardMoveInput() {
  43926. this._keys = new Array();
  43927. this.keysUp = [38];
  43928. this.keysDown = [40];
  43929. this.keysLeft = [37];
  43930. this.keysRight = [39];
  43931. this.keysReset = [220];
  43932. this.panningSensibility = 50.0;
  43933. this.zoomingSensibility = 25.0;
  43934. this.useAltToZoom = true;
  43935. }
  43936. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43937. var _this = this;
  43938. if (this._onCanvasBlurObserver) {
  43939. return;
  43940. }
  43941. this._scene = this.camera.getScene();
  43942. this._engine = this._scene.getEngine();
  43943. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43944. _this._keys = [];
  43945. });
  43946. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43947. var evt = info.event;
  43948. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43949. _this._ctrlPressed = evt.ctrlKey;
  43950. _this._altPressed = evt.altKey;
  43951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43954. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43955. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43956. var index = _this._keys.indexOf(evt.keyCode);
  43957. if (index === -1) {
  43958. _this._keys.push(evt.keyCode);
  43959. }
  43960. if (evt.preventDefault) {
  43961. if (!noPreventDefault) {
  43962. evt.preventDefault();
  43963. }
  43964. }
  43965. }
  43966. }
  43967. else {
  43968. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43969. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43970. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43971. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43972. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43973. var index = _this._keys.indexOf(evt.keyCode);
  43974. if (index >= 0) {
  43975. _this._keys.splice(index, 1);
  43976. }
  43977. if (evt.preventDefault) {
  43978. if (!noPreventDefault) {
  43979. evt.preventDefault();
  43980. }
  43981. }
  43982. }
  43983. }
  43984. });
  43985. };
  43986. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43987. if (this._scene) {
  43988. if (this._onKeyboardObserver) {
  43989. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43990. }
  43991. if (this._onCanvasBlurObserver) {
  43992. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43993. }
  43994. this._onKeyboardObserver = null;
  43995. this._onCanvasBlurObserver = null;
  43996. }
  43997. this._keys = [];
  43998. };
  43999. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44000. if (this._onKeyboardObserver) {
  44001. var camera = this.camera;
  44002. for (var index = 0; index < this._keys.length; index++) {
  44003. var keyCode = this._keys[index];
  44004. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44005. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44006. camera.inertialPanningX -= 1 / this.panningSensibility;
  44007. }
  44008. else {
  44009. camera.inertialAlphaOffset -= 0.01;
  44010. }
  44011. }
  44012. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44013. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44014. camera.inertialPanningY += 1 / this.panningSensibility;
  44015. }
  44016. else if (this._altPressed && this.useAltToZoom) {
  44017. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44018. }
  44019. else {
  44020. camera.inertialBetaOffset -= 0.01;
  44021. }
  44022. }
  44023. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44024. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44025. camera.inertialPanningX += 1 / this.panningSensibility;
  44026. }
  44027. else {
  44028. camera.inertialAlphaOffset += 0.01;
  44029. }
  44030. }
  44031. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44032. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44033. camera.inertialPanningY -= 1 / this.panningSensibility;
  44034. }
  44035. else if (this._altPressed && this.useAltToZoom) {
  44036. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44037. }
  44038. else {
  44039. camera.inertialBetaOffset += 0.01;
  44040. }
  44041. }
  44042. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44043. camera.restoreState();
  44044. }
  44045. }
  44046. }
  44047. };
  44048. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44049. return "ArcRotateCameraKeyboardMoveInput";
  44050. };
  44051. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44052. return "keyboard";
  44053. };
  44054. __decorate([
  44055. BABYLON.serialize()
  44056. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44057. __decorate([
  44058. BABYLON.serialize()
  44059. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44063. __decorate([
  44064. BABYLON.serialize()
  44065. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44066. __decorate([
  44067. BABYLON.serialize()
  44068. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44069. __decorate([
  44070. BABYLON.serialize()
  44071. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44072. __decorate([
  44073. BABYLON.serialize()
  44074. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44078. return ArcRotateCameraKeyboardMoveInput;
  44079. }());
  44080. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44081. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44082. })(BABYLON || (BABYLON = {}));
  44083. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44084. var BABYLON;
  44085. (function (BABYLON) {
  44086. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44087. function ArcRotateCameraMouseWheelInput() {
  44088. this.wheelPrecision = 3.0;
  44089. /**
  44090. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44091. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44092. */
  44093. this.wheelDeltaPercentage = 0;
  44094. }
  44095. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44096. var _this = this;
  44097. this._wheel = function (p, s) {
  44098. //sanity check - this should be a PointerWheel event.
  44099. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44100. return;
  44101. var event = p.event;
  44102. var delta = 0;
  44103. if (event.wheelDelta) {
  44104. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44105. }
  44106. else if (event.detail) {
  44107. delta = -event.detail / _this.wheelPrecision;
  44108. }
  44109. if (delta)
  44110. _this.camera.inertialRadiusOffset += delta;
  44111. if (event.preventDefault) {
  44112. if (!noPreventDefault) {
  44113. event.preventDefault();
  44114. }
  44115. }
  44116. };
  44117. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44118. };
  44119. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44120. if (this._observer && element) {
  44121. this.camera.getScene().onPointerObservable.remove(this._observer);
  44122. this._observer = null;
  44123. this._wheel = null;
  44124. }
  44125. };
  44126. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44127. return "ArcRotateCameraMouseWheelInput";
  44128. };
  44129. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44130. return "mousewheel";
  44131. };
  44132. __decorate([
  44133. BABYLON.serialize()
  44134. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44135. __decorate([
  44136. BABYLON.serialize()
  44137. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44138. return ArcRotateCameraMouseWheelInput;
  44139. }());
  44140. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44141. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44142. })(BABYLON || (BABYLON = {}));
  44143. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44144. var BABYLON;
  44145. (function (BABYLON) {
  44146. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44147. function ArcRotateCameraPointersInput() {
  44148. this.buttons = [0, 1, 2];
  44149. this.angularSensibilityX = 1000.0;
  44150. this.angularSensibilityY = 1000.0;
  44151. this.pinchPrecision = 12.0;
  44152. /**
  44153. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44154. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44155. */
  44156. this.pinchDeltaPercentage = 0;
  44157. this.panningSensibility = 1000.0;
  44158. this.multiTouchPanning = true;
  44159. this.multiTouchPanAndZoom = true;
  44160. this._isPanClick = false;
  44161. this.pinchInwards = true;
  44162. }
  44163. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44164. var _this = this;
  44165. var engine = this.camera.getEngine();
  44166. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44167. var pointA = null;
  44168. var pointB = null;
  44169. var previousPinchSquaredDistance = 0;
  44170. var initialDistance = 0;
  44171. var twoFingerActivityCount = 0;
  44172. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44173. this._pointerInput = function (p, s) {
  44174. var evt = p.event;
  44175. var isTouch = p.event.pointerType === "touch";
  44176. if (engine.isInVRExclusivePointerMode) {
  44177. return;
  44178. }
  44179. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44180. return;
  44181. }
  44182. var srcElement = (evt.srcElement || evt.target);
  44183. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44184. try {
  44185. srcElement.setPointerCapture(evt.pointerId);
  44186. }
  44187. catch (e) {
  44188. //Nothing to do with the error. Execution will continue.
  44189. }
  44190. // Manage panning with pan button click
  44191. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44192. // manage pointers
  44193. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44194. if (pointA === null) {
  44195. pointA = cacheSoloPointer;
  44196. }
  44197. else if (pointB === null) {
  44198. pointB = cacheSoloPointer;
  44199. }
  44200. if (!noPreventDefault) {
  44201. evt.preventDefault();
  44202. element.focus();
  44203. }
  44204. }
  44205. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44206. _this.camera.restoreState();
  44207. }
  44208. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44209. try {
  44210. srcElement.releasePointerCapture(evt.pointerId);
  44211. }
  44212. catch (e) {
  44213. //Nothing to do with the error.
  44214. }
  44215. cacheSoloPointer = null;
  44216. previousPinchSquaredDistance = 0;
  44217. previousMultiTouchPanPosition.isPaning = false;
  44218. previousMultiTouchPanPosition.isPinching = false;
  44219. twoFingerActivityCount = 0;
  44220. initialDistance = 0;
  44221. if (!isTouch) {
  44222. pointB = null; // Mouse and pen are mono pointer
  44223. }
  44224. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44225. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44226. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44227. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44228. if (engine.badOS) {
  44229. pointA = pointB = null;
  44230. }
  44231. else {
  44232. //only remove the impacted pointer in case of multitouch allowing on most
  44233. //platforms switching from rotate to zoom and pan seamlessly.
  44234. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44235. pointA = pointB;
  44236. pointB = null;
  44237. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44238. }
  44239. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44240. pointB = null;
  44241. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44242. }
  44243. else {
  44244. pointA = pointB = null;
  44245. }
  44246. }
  44247. if (!noPreventDefault) {
  44248. evt.preventDefault();
  44249. }
  44250. }
  44251. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44252. if (!noPreventDefault) {
  44253. evt.preventDefault();
  44254. }
  44255. // One button down
  44256. if (pointA && pointB === null && cacheSoloPointer) {
  44257. if (_this.panningSensibility !== 0 &&
  44258. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44259. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44260. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44261. }
  44262. else {
  44263. var offsetX = evt.clientX - cacheSoloPointer.x;
  44264. var offsetY = evt.clientY - cacheSoloPointer.y;
  44265. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44266. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44267. }
  44268. cacheSoloPointer.x = evt.clientX;
  44269. cacheSoloPointer.y = evt.clientY;
  44270. }
  44271. else if (pointA && pointB) {
  44272. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44273. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44274. ed.x = evt.clientX;
  44275. ed.y = evt.clientY;
  44276. var direction = _this.pinchInwards ? 1 : -1;
  44277. var distX = pointA.x - pointB.x;
  44278. var distY = pointA.y - pointB.y;
  44279. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44280. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44281. if (previousPinchSquaredDistance === 0) {
  44282. initialDistance = pinchDistance;
  44283. previousPinchSquaredDistance = pinchSquaredDistance;
  44284. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44285. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44286. return;
  44287. }
  44288. if (_this.multiTouchPanAndZoom) {
  44289. if (_this.pinchDeltaPercentage) {
  44290. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44291. }
  44292. else {
  44293. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44294. (_this.pinchPrecision *
  44295. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44296. direction);
  44297. }
  44298. if (_this.panningSensibility !== 0) {
  44299. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44300. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44301. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44302. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44303. previousMultiTouchPanPosition.x = pointersCenterX;
  44304. previousMultiTouchPanPosition.y = pointersCenterY;
  44305. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44306. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44307. }
  44308. }
  44309. else {
  44310. twoFingerActivityCount++;
  44311. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44312. if (_this.pinchDeltaPercentage) {
  44313. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44314. }
  44315. else {
  44316. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44317. (_this.pinchPrecision *
  44318. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44319. direction);
  44320. }
  44321. previousMultiTouchPanPosition.isPaning = false;
  44322. previousMultiTouchPanPosition.isPinching = true;
  44323. }
  44324. else {
  44325. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44326. if (!previousMultiTouchPanPosition.isPaning) {
  44327. previousMultiTouchPanPosition.isPaning = true;
  44328. previousMultiTouchPanPosition.isPinching = false;
  44329. previousMultiTouchPanPosition.x = ed.x;
  44330. previousMultiTouchPanPosition.y = ed.y;
  44331. return;
  44332. }
  44333. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44334. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44335. }
  44336. }
  44337. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44338. previousMultiTouchPanPosition.x = ed.x;
  44339. previousMultiTouchPanPosition.y = ed.y;
  44340. }
  44341. }
  44342. previousPinchSquaredDistance = pinchSquaredDistance;
  44343. }
  44344. }
  44345. };
  44346. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44347. this._onContextMenu = function (evt) {
  44348. evt.preventDefault();
  44349. };
  44350. if (!this.camera._useCtrlForPanning) {
  44351. element.addEventListener("contextmenu", this._onContextMenu, false);
  44352. }
  44353. this._onLostFocus = function () {
  44354. //this._keys = [];
  44355. pointA = pointB = null;
  44356. previousPinchSquaredDistance = 0;
  44357. previousMultiTouchPanPosition.isPaning = false;
  44358. previousMultiTouchPanPosition.isPinching = false;
  44359. twoFingerActivityCount = 0;
  44360. cacheSoloPointer = null;
  44361. initialDistance = 0;
  44362. };
  44363. this._onMouseMove = function (evt) {
  44364. if (!engine.isPointerLock) {
  44365. return;
  44366. }
  44367. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44368. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44369. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44370. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44371. if (!noPreventDefault) {
  44372. evt.preventDefault();
  44373. }
  44374. };
  44375. this._onGestureStart = function (e) {
  44376. if (window.MSGesture === undefined) {
  44377. return;
  44378. }
  44379. if (!_this._MSGestureHandler) {
  44380. _this._MSGestureHandler = new MSGesture();
  44381. _this._MSGestureHandler.target = element;
  44382. }
  44383. _this._MSGestureHandler.addPointer(e.pointerId);
  44384. };
  44385. this._onGesture = function (e) {
  44386. _this.camera.radius *= e.scale;
  44387. if (e.preventDefault) {
  44388. if (!noPreventDefault) {
  44389. e.stopPropagation();
  44390. e.preventDefault();
  44391. }
  44392. }
  44393. };
  44394. element.addEventListener("mousemove", this._onMouseMove, false);
  44395. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44396. element.addEventListener("MSGestureChange", this._onGesture, false);
  44397. BABYLON.Tools.RegisterTopRootEvents([
  44398. { name: "blur", handler: this._onLostFocus }
  44399. ]);
  44400. };
  44401. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44402. if (this._onLostFocus) {
  44403. BABYLON.Tools.UnregisterTopRootEvents([
  44404. { name: "blur", handler: this._onLostFocus }
  44405. ]);
  44406. }
  44407. if (element && this._observer) {
  44408. this.camera.getScene().onPointerObservable.remove(this._observer);
  44409. this._observer = null;
  44410. if (this._onContextMenu) {
  44411. element.removeEventListener("contextmenu", this._onContextMenu);
  44412. }
  44413. if (this._onMouseMove) {
  44414. element.removeEventListener("mousemove", this._onMouseMove);
  44415. }
  44416. if (this._onGestureStart) {
  44417. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44418. }
  44419. if (this._onGesture) {
  44420. element.removeEventListener("MSGestureChange", this._onGesture);
  44421. }
  44422. this._isPanClick = false;
  44423. this.pinchInwards = true;
  44424. this._onMouseMove = null;
  44425. this._onGestureStart = null;
  44426. this._onGesture = null;
  44427. this._MSGestureHandler = null;
  44428. this._onLostFocus = null;
  44429. this._onContextMenu = null;
  44430. }
  44431. };
  44432. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44433. return "ArcRotateCameraPointersInput";
  44434. };
  44435. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44436. return "pointers";
  44437. };
  44438. __decorate([
  44439. BABYLON.serialize()
  44440. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44441. __decorate([
  44442. BABYLON.serialize()
  44443. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44444. __decorate([
  44445. BABYLON.serialize()
  44446. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44447. __decorate([
  44448. BABYLON.serialize()
  44449. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44450. __decorate([
  44451. BABYLON.serialize()
  44452. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44453. __decorate([
  44454. BABYLON.serialize()
  44455. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44456. __decorate([
  44457. BABYLON.serialize()
  44458. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44459. __decorate([
  44460. BABYLON.serialize()
  44461. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44462. return ArcRotateCameraPointersInput;
  44463. }());
  44464. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44465. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44466. })(BABYLON || (BABYLON = {}));
  44467. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44468. var BABYLON;
  44469. (function (BABYLON) {
  44470. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44471. __extends(ArcRotateCameraInputsManager, _super);
  44472. function ArcRotateCameraInputsManager(camera) {
  44473. return _super.call(this, camera) || this;
  44474. }
  44475. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44476. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44477. return this;
  44478. };
  44479. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44480. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44481. return this;
  44482. };
  44483. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44484. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44485. return this;
  44486. };
  44487. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44488. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44489. return this;
  44490. };
  44491. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44492. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44493. return this;
  44494. };
  44495. return ArcRotateCameraInputsManager;
  44496. }(BABYLON.CameraInputsManager));
  44497. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44498. })(BABYLON || (BABYLON = {}));
  44499. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44500. var BABYLON;
  44501. (function (BABYLON) {
  44502. var ArcRotateCamera = /** @class */ (function (_super) {
  44503. __extends(ArcRotateCamera, _super);
  44504. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44505. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44506. _this.inertialAlphaOffset = 0;
  44507. _this.inertialBetaOffset = 0;
  44508. _this.inertialRadiusOffset = 0;
  44509. _this.lowerAlphaLimit = null;
  44510. _this.upperAlphaLimit = null;
  44511. _this.lowerBetaLimit = 0.01;
  44512. _this.upperBetaLimit = Math.PI;
  44513. _this.lowerRadiusLimit = null;
  44514. _this.upperRadiusLimit = null;
  44515. _this.inertialPanningX = 0;
  44516. _this.inertialPanningY = 0;
  44517. _this.pinchToPanMaxDistance = 20;
  44518. _this.panningDistanceLimit = null;
  44519. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44520. _this.panningInertia = 0.9;
  44521. //-- end properties for backward compatibility for inputs
  44522. _this.zoomOnFactor = 1;
  44523. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44524. _this.allowUpsideDown = true;
  44525. _this._viewMatrix = new BABYLON.Matrix();
  44526. // Panning
  44527. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44528. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44529. _this.checkCollisions = false;
  44530. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44531. _this._previousPosition = BABYLON.Vector3.Zero();
  44532. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44533. _this._newPosition = BABYLON.Vector3.Zero();
  44534. _this._computationVector = BABYLON.Vector3.Zero();
  44535. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44536. if (collidedMesh === void 0) { collidedMesh = null; }
  44537. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44538. newPosition.multiplyInPlace(_this._collider._radius);
  44539. }
  44540. if (!collidedMesh) {
  44541. _this._previousPosition.copyFrom(_this.position);
  44542. }
  44543. else {
  44544. _this.setPosition(newPosition);
  44545. if (_this.onCollide) {
  44546. _this.onCollide(collidedMesh);
  44547. }
  44548. }
  44549. // Recompute because of constraints
  44550. var cosa = Math.cos(_this.alpha);
  44551. var sina = Math.sin(_this.alpha);
  44552. var cosb = Math.cos(_this.beta);
  44553. var sinb = Math.sin(_this.beta);
  44554. if (sinb === 0) {
  44555. sinb = 0.0001;
  44556. }
  44557. var target = _this._getTargetPosition();
  44558. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44559. target.addToRef(_this._computationVector, _this._newPosition);
  44560. _this.position.copyFrom(_this._newPosition);
  44561. var up = _this.upVector;
  44562. if (_this.allowUpsideDown && _this.beta < 0) {
  44563. up = up.clone();
  44564. up = up.negate();
  44565. }
  44566. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44567. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44568. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44569. _this._collisionTriggered = false;
  44570. };
  44571. _this._target = BABYLON.Vector3.Zero();
  44572. if (target) {
  44573. _this.setTarget(target);
  44574. }
  44575. _this.alpha = alpha;
  44576. _this.beta = beta;
  44577. _this.radius = radius;
  44578. _this.getViewMatrix();
  44579. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44580. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44581. return _this;
  44582. }
  44583. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44584. get: function () {
  44585. return this._target;
  44586. },
  44587. set: function (value) {
  44588. this.setTarget(value);
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44594. //-- begin properties for backward compatibility for inputs
  44595. get: function () {
  44596. var pointers = this.inputs.attached["pointers"];
  44597. if (pointers)
  44598. return pointers.angularSensibilityX;
  44599. return 0;
  44600. },
  44601. set: function (value) {
  44602. var pointers = this.inputs.attached["pointers"];
  44603. if (pointers) {
  44604. pointers.angularSensibilityX = value;
  44605. }
  44606. },
  44607. enumerable: true,
  44608. configurable: true
  44609. });
  44610. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44611. get: function () {
  44612. var pointers = this.inputs.attached["pointers"];
  44613. if (pointers)
  44614. return pointers.angularSensibilityY;
  44615. return 0;
  44616. },
  44617. set: function (value) {
  44618. var pointers = this.inputs.attached["pointers"];
  44619. if (pointers) {
  44620. pointers.angularSensibilityY = value;
  44621. }
  44622. },
  44623. enumerable: true,
  44624. configurable: true
  44625. });
  44626. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44627. get: function () {
  44628. var pointers = this.inputs.attached["pointers"];
  44629. if (pointers)
  44630. return pointers.pinchPrecision;
  44631. return 0;
  44632. },
  44633. set: function (value) {
  44634. var pointers = this.inputs.attached["pointers"];
  44635. if (pointers) {
  44636. pointers.pinchPrecision = value;
  44637. }
  44638. },
  44639. enumerable: true,
  44640. configurable: true
  44641. });
  44642. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44643. get: function () {
  44644. var pointers = this.inputs.attached["pointers"];
  44645. if (pointers)
  44646. return pointers.pinchDeltaPercentage;
  44647. return 0;
  44648. },
  44649. set: function (value) {
  44650. var pointers = this.inputs.attached["pointers"];
  44651. if (pointers) {
  44652. pointers.pinchDeltaPercentage = value;
  44653. }
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44659. get: function () {
  44660. var pointers = this.inputs.attached["pointers"];
  44661. if (pointers)
  44662. return pointers.panningSensibility;
  44663. return 0;
  44664. },
  44665. set: function (value) {
  44666. var pointers = this.inputs.attached["pointers"];
  44667. if (pointers) {
  44668. pointers.panningSensibility = value;
  44669. }
  44670. },
  44671. enumerable: true,
  44672. configurable: true
  44673. });
  44674. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44675. get: function () {
  44676. var keyboard = this.inputs.attached["keyboard"];
  44677. if (keyboard)
  44678. return keyboard.keysUp;
  44679. return [];
  44680. },
  44681. set: function (value) {
  44682. var keyboard = this.inputs.attached["keyboard"];
  44683. if (keyboard)
  44684. keyboard.keysUp = value;
  44685. },
  44686. enumerable: true,
  44687. configurable: true
  44688. });
  44689. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44690. get: function () {
  44691. var keyboard = this.inputs.attached["keyboard"];
  44692. if (keyboard)
  44693. return keyboard.keysDown;
  44694. return [];
  44695. },
  44696. set: function (value) {
  44697. var keyboard = this.inputs.attached["keyboard"];
  44698. if (keyboard)
  44699. keyboard.keysDown = value;
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44705. get: function () {
  44706. var keyboard = this.inputs.attached["keyboard"];
  44707. if (keyboard)
  44708. return keyboard.keysLeft;
  44709. return [];
  44710. },
  44711. set: function (value) {
  44712. var keyboard = this.inputs.attached["keyboard"];
  44713. if (keyboard)
  44714. keyboard.keysLeft = value;
  44715. },
  44716. enumerable: true,
  44717. configurable: true
  44718. });
  44719. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44720. get: function () {
  44721. var keyboard = this.inputs.attached["keyboard"];
  44722. if (keyboard)
  44723. return keyboard.keysRight;
  44724. return [];
  44725. },
  44726. set: function (value) {
  44727. var keyboard = this.inputs.attached["keyboard"];
  44728. if (keyboard)
  44729. keyboard.keysRight = value;
  44730. },
  44731. enumerable: true,
  44732. configurable: true
  44733. });
  44734. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44735. get: function () {
  44736. var mousewheel = this.inputs.attached["mousewheel"];
  44737. if (mousewheel)
  44738. return mousewheel.wheelPrecision;
  44739. return 0;
  44740. },
  44741. set: function (value) {
  44742. var mousewheel = this.inputs.attached["mousewheel"];
  44743. if (mousewheel)
  44744. mousewheel.wheelPrecision = value;
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44750. get: function () {
  44751. var mousewheel = this.inputs.attached["mousewheel"];
  44752. if (mousewheel)
  44753. return mousewheel.wheelDeltaPercentage;
  44754. return 0;
  44755. },
  44756. set: function (value) {
  44757. var mousewheel = this.inputs.attached["mousewheel"];
  44758. if (mousewheel)
  44759. mousewheel.wheelDeltaPercentage = value;
  44760. },
  44761. enumerable: true,
  44762. configurable: true
  44763. });
  44764. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44765. get: function () {
  44766. return this._bouncingBehavior;
  44767. },
  44768. enumerable: true,
  44769. configurable: true
  44770. });
  44771. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44772. get: function () {
  44773. return this._bouncingBehavior != null;
  44774. },
  44775. set: function (value) {
  44776. if (value === this.useBouncingBehavior) {
  44777. return;
  44778. }
  44779. if (value) {
  44780. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44781. this.addBehavior(this._bouncingBehavior);
  44782. }
  44783. else if (this._bouncingBehavior) {
  44784. this.removeBehavior(this._bouncingBehavior);
  44785. this._bouncingBehavior = null;
  44786. }
  44787. },
  44788. enumerable: true,
  44789. configurable: true
  44790. });
  44791. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44792. get: function () {
  44793. return this._framingBehavior;
  44794. },
  44795. enumerable: true,
  44796. configurable: true
  44797. });
  44798. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44799. get: function () {
  44800. return this._framingBehavior != null;
  44801. },
  44802. set: function (value) {
  44803. if (value === this.useFramingBehavior) {
  44804. return;
  44805. }
  44806. if (value) {
  44807. this._framingBehavior = new BABYLON.FramingBehavior();
  44808. this.addBehavior(this._framingBehavior);
  44809. }
  44810. else if (this._framingBehavior) {
  44811. this.removeBehavior(this._framingBehavior);
  44812. this._framingBehavior = null;
  44813. }
  44814. },
  44815. enumerable: true,
  44816. configurable: true
  44817. });
  44818. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44819. get: function () {
  44820. return this._autoRotationBehavior;
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44826. get: function () {
  44827. return this._autoRotationBehavior != null;
  44828. },
  44829. set: function (value) {
  44830. if (value === this.useAutoRotationBehavior) {
  44831. return;
  44832. }
  44833. if (value) {
  44834. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44835. this.addBehavior(this._autoRotationBehavior);
  44836. }
  44837. else if (this._autoRotationBehavior) {
  44838. this.removeBehavior(this._autoRotationBehavior);
  44839. this._autoRotationBehavior = null;
  44840. }
  44841. },
  44842. enumerable: true,
  44843. configurable: true
  44844. });
  44845. // Cache
  44846. ArcRotateCamera.prototype._initCache = function () {
  44847. _super.prototype._initCache.call(this);
  44848. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44849. this._cache.alpha = undefined;
  44850. this._cache.beta = undefined;
  44851. this._cache.radius = undefined;
  44852. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44853. };
  44854. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44855. if (!ignoreParentClass) {
  44856. _super.prototype._updateCache.call(this);
  44857. }
  44858. this._cache._target.copyFrom(this._getTargetPosition());
  44859. this._cache.alpha = this.alpha;
  44860. this._cache.beta = this.beta;
  44861. this._cache.radius = this.radius;
  44862. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44863. };
  44864. ArcRotateCamera.prototype._getTargetPosition = function () {
  44865. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44866. var pos = this._targetHost.getAbsolutePosition();
  44867. if (this._targetBoundingCenter) {
  44868. pos.addToRef(this._targetBoundingCenter, this._target);
  44869. }
  44870. else {
  44871. this._target.copyFrom(pos);
  44872. }
  44873. }
  44874. var lockedTargetPosition = this._getLockedTargetPosition();
  44875. if (lockedTargetPosition) {
  44876. return lockedTargetPosition;
  44877. }
  44878. return this._target;
  44879. };
  44880. ArcRotateCamera.prototype.storeState = function () {
  44881. this._storedAlpha = this.alpha;
  44882. this._storedBeta = this.beta;
  44883. this._storedRadius = this.radius;
  44884. this._storedTarget = this._getTargetPosition().clone();
  44885. return _super.prototype.storeState.call(this);
  44886. };
  44887. /**
  44888. * Restored camera state. You must call storeState() first
  44889. */
  44890. ArcRotateCamera.prototype._restoreStateValues = function () {
  44891. if (!_super.prototype._restoreStateValues.call(this)) {
  44892. return false;
  44893. }
  44894. this.alpha = this._storedAlpha;
  44895. this.beta = this._storedBeta;
  44896. this.radius = this._storedRadius;
  44897. this.setTarget(this._storedTarget.clone());
  44898. this.inertialAlphaOffset = 0;
  44899. this.inertialBetaOffset = 0;
  44900. this.inertialRadiusOffset = 0;
  44901. this.inertialPanningX = 0;
  44902. this.inertialPanningY = 0;
  44903. return true;
  44904. };
  44905. // Synchronized
  44906. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44907. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44908. return false;
  44909. return this._cache._target.equals(this._getTargetPosition())
  44910. && this._cache.alpha === this.alpha
  44911. && this._cache.beta === this.beta
  44912. && this._cache.radius === this.radius
  44913. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44914. };
  44915. // Methods
  44916. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44917. var _this = this;
  44918. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44919. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44920. this._useCtrlForPanning = useCtrlForPanning;
  44921. this._panningMouseButton = panningMouseButton;
  44922. this.inputs.attachElement(element, noPreventDefault);
  44923. this._reset = function () {
  44924. _this.inertialAlphaOffset = 0;
  44925. _this.inertialBetaOffset = 0;
  44926. _this.inertialRadiusOffset = 0;
  44927. _this.inertialPanningX = 0;
  44928. _this.inertialPanningY = 0;
  44929. };
  44930. };
  44931. ArcRotateCamera.prototype.detachControl = function (element) {
  44932. this.inputs.detachElement(element);
  44933. if (this._reset) {
  44934. this._reset();
  44935. }
  44936. };
  44937. ArcRotateCamera.prototype._checkInputs = function () {
  44938. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44939. if (this._collisionTriggered) {
  44940. return;
  44941. }
  44942. this.inputs.checkInputs();
  44943. // Inertia
  44944. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44945. if (this.getScene().useRightHandedSystem) {
  44946. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44947. }
  44948. else {
  44949. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44950. }
  44951. this.beta += this.inertialBetaOffset;
  44952. this.radius -= this.inertialRadiusOffset;
  44953. this.inertialAlphaOffset *= this.inertia;
  44954. this.inertialBetaOffset *= this.inertia;
  44955. this.inertialRadiusOffset *= this.inertia;
  44956. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44957. this.inertialAlphaOffset = 0;
  44958. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44959. this.inertialBetaOffset = 0;
  44960. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44961. this.inertialRadiusOffset = 0;
  44962. }
  44963. // Panning inertia
  44964. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44965. if (!this._localDirection) {
  44966. this._localDirection = BABYLON.Vector3.Zero();
  44967. this._transformedDirection = BABYLON.Vector3.Zero();
  44968. }
  44969. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44970. this._localDirection.multiplyInPlace(this.panningAxis);
  44971. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44972. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44973. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44974. if (!this.panningAxis.y) {
  44975. this._transformedDirection.y = 0;
  44976. }
  44977. if (!this._targetHost) {
  44978. if (this.panningDistanceLimit) {
  44979. this._transformedDirection.addInPlace(this._target);
  44980. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44981. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44982. this._target.copyFrom(this._transformedDirection);
  44983. }
  44984. }
  44985. else {
  44986. this._target.addInPlace(this._transformedDirection);
  44987. }
  44988. }
  44989. this.inertialPanningX *= this.panningInertia;
  44990. this.inertialPanningY *= this.panningInertia;
  44991. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44992. this.inertialPanningX = 0;
  44993. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44994. this.inertialPanningY = 0;
  44995. }
  44996. // Limits
  44997. this._checkLimits();
  44998. _super.prototype._checkInputs.call(this);
  44999. };
  45000. ArcRotateCamera.prototype._checkLimits = function () {
  45001. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45002. if (this.allowUpsideDown && this.beta > Math.PI) {
  45003. this.beta = this.beta - (2 * Math.PI);
  45004. }
  45005. }
  45006. else {
  45007. if (this.beta < this.lowerBetaLimit) {
  45008. this.beta = this.lowerBetaLimit;
  45009. }
  45010. }
  45011. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45012. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45013. this.beta = this.beta + (2 * Math.PI);
  45014. }
  45015. }
  45016. else {
  45017. if (this.beta > this.upperBetaLimit) {
  45018. this.beta = this.upperBetaLimit;
  45019. }
  45020. }
  45021. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45022. this.alpha = this.lowerAlphaLimit;
  45023. }
  45024. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45025. this.alpha = this.upperAlphaLimit;
  45026. }
  45027. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45028. this.radius = this.lowerRadiusLimit;
  45029. }
  45030. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45031. this.radius = this.upperRadiusLimit;
  45032. }
  45033. };
  45034. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45035. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45036. this.radius = this._computationVector.length();
  45037. if (this.radius === 0) {
  45038. this.radius = 0.0001; // Just to avoid division by zero
  45039. }
  45040. // Alpha
  45041. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45042. if (this._computationVector.z < 0) {
  45043. this.alpha = 2 * Math.PI - this.alpha;
  45044. }
  45045. // Beta
  45046. this.beta = Math.acos(this._computationVector.y / this.radius);
  45047. this._checkLimits();
  45048. };
  45049. ArcRotateCamera.prototype.setPosition = function (position) {
  45050. if (this.position.equals(position)) {
  45051. return;
  45052. }
  45053. this.position.copyFrom(position);
  45054. this.rebuildAnglesAndRadius();
  45055. };
  45056. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45057. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45058. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45059. if (target.getBoundingInfo) {
  45060. if (toBoundingCenter) {
  45061. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45062. }
  45063. else {
  45064. this._targetBoundingCenter = null;
  45065. }
  45066. this._targetHost = target;
  45067. this._target = this._getTargetPosition();
  45068. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45069. }
  45070. else {
  45071. var newTarget = target;
  45072. var currentTarget = this._getTargetPosition();
  45073. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45074. return;
  45075. }
  45076. this._targetHost = null;
  45077. this._target = newTarget;
  45078. this._targetBoundingCenter = null;
  45079. this.onMeshTargetChangedObservable.notifyObservers(null);
  45080. }
  45081. this.rebuildAnglesAndRadius();
  45082. };
  45083. ArcRotateCamera.prototype._getViewMatrix = function () {
  45084. // Compute
  45085. var cosa = Math.cos(this.alpha);
  45086. var sina = Math.sin(this.alpha);
  45087. var cosb = Math.cos(this.beta);
  45088. var sinb = Math.sin(this.beta);
  45089. if (sinb === 0) {
  45090. sinb = 0.0001;
  45091. }
  45092. var target = this._getTargetPosition();
  45093. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45094. target.addToRef(this._computationVector, this._newPosition);
  45095. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45096. if (!this._collider) {
  45097. this._collider = new BABYLON.Collider();
  45098. }
  45099. this._collider._radius = this.collisionRadius;
  45100. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45101. this._collisionTriggered = true;
  45102. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45103. }
  45104. else {
  45105. this.position.copyFrom(this._newPosition);
  45106. var up = this.upVector;
  45107. if (this.allowUpsideDown && sinb < 0) {
  45108. up = up.clone();
  45109. up = up.negate();
  45110. }
  45111. if (this.getScene().useRightHandedSystem) {
  45112. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45113. }
  45114. else {
  45115. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45116. }
  45117. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45118. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45119. }
  45120. this._currentTarget = target;
  45121. return this._viewMatrix;
  45122. };
  45123. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45124. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45125. meshes = meshes || this.getScene().meshes;
  45126. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45127. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45128. this.radius = distance * this.zoomOnFactor;
  45129. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45130. };
  45131. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45132. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45133. var meshesOrMinMaxVector;
  45134. var distance;
  45135. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45136. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45137. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45138. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45139. }
  45140. else {
  45141. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45142. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45143. distance = minMaxVectorAndDistance.distance;
  45144. }
  45145. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45146. if (!doNotUpdateMaxZ) {
  45147. this.maxZ = distance * 2;
  45148. }
  45149. };
  45150. /**
  45151. * @override
  45152. * Override Camera.createRigCamera
  45153. */
  45154. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45155. var alphaShift = 0;
  45156. switch (this.cameraRigMode) {
  45157. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45158. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45159. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45160. case BABYLON.Camera.RIG_MODE_VR:
  45161. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45162. break;
  45163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45164. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45165. break;
  45166. }
  45167. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45168. rigCam._cameraRigParams = {};
  45169. return rigCam;
  45170. };
  45171. /**
  45172. * @override
  45173. * Override Camera._updateRigCameras
  45174. */
  45175. ArcRotateCamera.prototype._updateRigCameras = function () {
  45176. var camLeft = this._rigCameras[0];
  45177. var camRight = this._rigCameras[1];
  45178. camLeft.beta = camRight.beta = this.beta;
  45179. camLeft.radius = camRight.radius = this.radius;
  45180. switch (this.cameraRigMode) {
  45181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45184. case BABYLON.Camera.RIG_MODE_VR:
  45185. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45186. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45187. break;
  45188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45189. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45190. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45191. break;
  45192. }
  45193. _super.prototype._updateRigCameras.call(this);
  45194. };
  45195. ArcRotateCamera.prototype.dispose = function () {
  45196. this.inputs.clear();
  45197. _super.prototype.dispose.call(this);
  45198. };
  45199. ArcRotateCamera.prototype.getClassName = function () {
  45200. return "ArcRotateCamera";
  45201. };
  45202. __decorate([
  45203. BABYLON.serialize()
  45204. ], ArcRotateCamera.prototype, "alpha", void 0);
  45205. __decorate([
  45206. BABYLON.serialize()
  45207. ], ArcRotateCamera.prototype, "beta", void 0);
  45208. __decorate([
  45209. BABYLON.serialize()
  45210. ], ArcRotateCamera.prototype, "radius", void 0);
  45211. __decorate([
  45212. BABYLON.serializeAsVector3("target")
  45213. ], ArcRotateCamera.prototype, "_target", void 0);
  45214. __decorate([
  45215. BABYLON.serialize()
  45216. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45217. __decorate([
  45218. BABYLON.serialize()
  45219. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45220. __decorate([
  45221. BABYLON.serialize()
  45222. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45223. __decorate([
  45224. BABYLON.serialize()
  45225. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45226. __decorate([
  45227. BABYLON.serialize()
  45228. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45229. __decorate([
  45230. BABYLON.serialize()
  45231. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45232. __decorate([
  45233. BABYLON.serialize()
  45234. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45235. __decorate([
  45236. BABYLON.serialize()
  45237. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45238. __decorate([
  45239. BABYLON.serialize()
  45240. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45241. __decorate([
  45242. BABYLON.serialize()
  45243. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45244. __decorate([
  45245. BABYLON.serialize()
  45246. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45247. __decorate([
  45248. BABYLON.serialize()
  45249. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45250. __decorate([
  45251. BABYLON.serialize()
  45252. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45253. __decorate([
  45254. BABYLON.serializeAsVector3()
  45255. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45256. __decorate([
  45257. BABYLON.serialize()
  45258. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45259. __decorate([
  45260. BABYLON.serialize()
  45261. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45262. __decorate([
  45263. BABYLON.serialize()
  45264. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45265. return ArcRotateCamera;
  45266. }(BABYLON.TargetCamera));
  45267. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45268. })(BABYLON || (BABYLON = {}));
  45269. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45270. var BABYLON;
  45271. (function (BABYLON) {
  45272. /**
  45273. * The HemisphericLight simulates the ambient environment light,
  45274. * so the passed direction is the light reflection direction, not the incoming direction.
  45275. */
  45276. var HemisphericLight = /** @class */ (function (_super) {
  45277. __extends(HemisphericLight, _super);
  45278. /**
  45279. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45280. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45281. * The HemisphericLight can't cast shadows.
  45282. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45283. * @param name The friendly name of the light
  45284. * @param direction The direction of the light reflection
  45285. * @param scene The scene the light belongs to
  45286. */
  45287. function HemisphericLight(name, direction, scene) {
  45288. var _this = _super.call(this, name, scene) || this;
  45289. /**
  45290. * The groundColor is the light in the opposite direction to the one specified during creation.
  45291. * 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.
  45292. */
  45293. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45294. _this.direction = direction || BABYLON.Vector3.Up();
  45295. return _this;
  45296. }
  45297. HemisphericLight.prototype._buildUniformLayout = function () {
  45298. this._uniformBuffer.addUniform("vLightData", 4);
  45299. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45300. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45301. this._uniformBuffer.addUniform("vLightGround", 3);
  45302. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45303. this._uniformBuffer.addUniform("depthValues", 2);
  45304. this._uniformBuffer.create();
  45305. };
  45306. /**
  45307. * Returns the string "HemisphericLight".
  45308. * @return The class name
  45309. */
  45310. HemisphericLight.prototype.getClassName = function () {
  45311. return "HemisphericLight";
  45312. };
  45313. /**
  45314. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45315. * Returns the updated direction.
  45316. * @param target The target the direction should point to
  45317. * @return The computed direction
  45318. */
  45319. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45320. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45321. return this.direction;
  45322. };
  45323. /**
  45324. * Returns the shadow generator associated to the light.
  45325. * @returns Always null for hemispheric lights because it does not support shadows.
  45326. */
  45327. HemisphericLight.prototype.getShadowGenerator = function () {
  45328. return null;
  45329. };
  45330. /**
  45331. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45332. * @param effect The effect to update
  45333. * @param lightIndex The index of the light in the effect to update
  45334. * @returns The hemispheric light
  45335. */
  45336. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45337. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45338. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45339. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45340. return this;
  45341. };
  45342. /**
  45343. * @ignore internal use only.
  45344. */
  45345. HemisphericLight.prototype._getWorldMatrix = function () {
  45346. if (!this._worldMatrix) {
  45347. this._worldMatrix = BABYLON.Matrix.Identity();
  45348. }
  45349. return this._worldMatrix;
  45350. };
  45351. /**
  45352. * Returns the integer 3.
  45353. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45354. */
  45355. HemisphericLight.prototype.getTypeID = function () {
  45356. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45357. };
  45358. __decorate([
  45359. BABYLON.serializeAsColor3()
  45360. ], HemisphericLight.prototype, "groundColor", void 0);
  45361. __decorate([
  45362. BABYLON.serializeAsVector3()
  45363. ], HemisphericLight.prototype, "direction", void 0);
  45364. return HemisphericLight;
  45365. }(BABYLON.Light));
  45366. BABYLON.HemisphericLight = HemisphericLight;
  45367. })(BABYLON || (BABYLON = {}));
  45368. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45369. var BABYLON;
  45370. (function (BABYLON) {
  45371. /**
  45372. * Base implementation of @see IShadowLight
  45373. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45374. */
  45375. var ShadowLight = /** @class */ (function (_super) {
  45376. __extends(ShadowLight, _super);
  45377. function ShadowLight() {
  45378. var _this = _super !== null && _super.apply(this, arguments) || this;
  45379. _this._needProjectionMatrixCompute = true;
  45380. return _this;
  45381. }
  45382. ShadowLight.prototype._setPosition = function (value) {
  45383. this._position = value;
  45384. };
  45385. Object.defineProperty(ShadowLight.prototype, "position", {
  45386. /**
  45387. * Sets the position the shadow will be casted from. Also use as the light position for both
  45388. * point and spot lights.
  45389. */
  45390. get: function () {
  45391. return this._position;
  45392. },
  45393. /**
  45394. * Sets the position the shadow will be casted from. Also use as the light position for both
  45395. * point and spot lights.
  45396. */
  45397. set: function (value) {
  45398. this._setPosition(value);
  45399. },
  45400. enumerable: true,
  45401. configurable: true
  45402. });
  45403. ShadowLight.prototype._setDirection = function (value) {
  45404. this._direction = value;
  45405. };
  45406. Object.defineProperty(ShadowLight.prototype, "direction", {
  45407. /**
  45408. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45409. * Also use as the light direction on spot and directional lights.
  45410. */
  45411. get: function () {
  45412. return this._direction;
  45413. },
  45414. /**
  45415. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45416. * Also use as the light direction on spot and directional lights.
  45417. */
  45418. set: function (value) {
  45419. this._setDirection(value);
  45420. },
  45421. enumerable: true,
  45422. configurable: true
  45423. });
  45424. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45425. /**
  45426. * Gets the shadow projection clipping minimum z value.
  45427. */
  45428. get: function () {
  45429. return this._shadowMinZ;
  45430. },
  45431. /**
  45432. * Sets the shadow projection clipping minimum z value.
  45433. */
  45434. set: function (value) {
  45435. this._shadowMinZ = value;
  45436. this.forceProjectionMatrixCompute();
  45437. },
  45438. enumerable: true,
  45439. configurable: true
  45440. });
  45441. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45442. /**
  45443. * Sets the shadow projection clipping maximum z value.
  45444. */
  45445. get: function () {
  45446. return this._shadowMaxZ;
  45447. },
  45448. /**
  45449. * Gets the shadow projection clipping maximum z value.
  45450. */
  45451. set: function (value) {
  45452. this._shadowMaxZ = value;
  45453. this.forceProjectionMatrixCompute();
  45454. },
  45455. enumerable: true,
  45456. configurable: true
  45457. });
  45458. /**
  45459. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45460. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45461. */
  45462. ShadowLight.prototype.computeTransformedInformation = function () {
  45463. if (this.parent && this.parent.getWorldMatrix) {
  45464. if (!this.transformedPosition) {
  45465. this.transformedPosition = BABYLON.Vector3.Zero();
  45466. }
  45467. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45468. // In case the direction is present.
  45469. if (this.direction) {
  45470. if (!this.transformedDirection) {
  45471. this.transformedDirection = BABYLON.Vector3.Zero();
  45472. }
  45473. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45474. }
  45475. return true;
  45476. }
  45477. return false;
  45478. };
  45479. /**
  45480. * Return the depth scale used for the shadow map.
  45481. * @returns the depth scale.
  45482. */
  45483. ShadowLight.prototype.getDepthScale = function () {
  45484. return 50.0;
  45485. };
  45486. /**
  45487. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45488. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45489. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45490. */
  45491. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45492. return this.transformedDirection ? this.transformedDirection : this.direction;
  45493. };
  45494. /**
  45495. * Returns the ShadowLight absolute position in the World.
  45496. * @returns the position vector in world space
  45497. */
  45498. ShadowLight.prototype.getAbsolutePosition = function () {
  45499. return this.transformedPosition ? this.transformedPosition : this.position;
  45500. };
  45501. /**
  45502. * Sets the ShadowLight direction toward the passed target.
  45503. * @param target The point tot target in local space
  45504. * @returns the updated ShadowLight direction
  45505. */
  45506. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45507. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45508. return this.direction;
  45509. };
  45510. /**
  45511. * Returns the light rotation in euler definition.
  45512. * @returns the x y z rotation in local space.
  45513. */
  45514. ShadowLight.prototype.getRotation = function () {
  45515. this.direction.normalize();
  45516. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45517. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45518. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45519. };
  45520. /**
  45521. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45522. * @returns true if a cube texture needs to be use
  45523. */
  45524. ShadowLight.prototype.needCube = function () {
  45525. return false;
  45526. };
  45527. /**
  45528. * Detects if the projection matrix requires to be recomputed this frame.
  45529. * @returns true if it requires to be recomputed otherwise, false.
  45530. */
  45531. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45532. return this._needProjectionMatrixCompute;
  45533. };
  45534. /**
  45535. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45536. */
  45537. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45538. this._needProjectionMatrixCompute = true;
  45539. };
  45540. /**
  45541. * Get the world matrix of the sahdow lights.
  45542. * @ignore Internal Use Only
  45543. */
  45544. ShadowLight.prototype._getWorldMatrix = function () {
  45545. if (!this._worldMatrix) {
  45546. this._worldMatrix = BABYLON.Matrix.Identity();
  45547. }
  45548. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45549. return this._worldMatrix;
  45550. };
  45551. /**
  45552. * Gets the minZ used for shadow according to both the scene and the light.
  45553. * @param activeCamera The camera we are returning the min for
  45554. * @returns the depth min z
  45555. */
  45556. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45557. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45558. };
  45559. /**
  45560. * Gets the maxZ used for shadow according to both the scene and the light.
  45561. * @param activeCamera The camera we are returning the max for
  45562. * @returns the depth max z
  45563. */
  45564. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45565. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45566. };
  45567. /**
  45568. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45569. * @param matrix The materix to updated with the projection information
  45570. * @param viewMatrix The transform matrix of the light
  45571. * @param renderList The list of mesh to render in the map
  45572. * @returns The current light
  45573. */
  45574. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45575. if (this.customProjectionMatrixBuilder) {
  45576. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45577. }
  45578. else {
  45579. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45580. }
  45581. return this;
  45582. };
  45583. __decorate([
  45584. BABYLON.serializeAsVector3()
  45585. ], ShadowLight.prototype, "position", null);
  45586. __decorate([
  45587. BABYLON.serializeAsVector3()
  45588. ], ShadowLight.prototype, "direction", null);
  45589. __decorate([
  45590. BABYLON.serialize()
  45591. ], ShadowLight.prototype, "shadowMinZ", null);
  45592. __decorate([
  45593. BABYLON.serialize()
  45594. ], ShadowLight.prototype, "shadowMaxZ", null);
  45595. return ShadowLight;
  45596. }(BABYLON.Light));
  45597. BABYLON.ShadowLight = ShadowLight;
  45598. })(BABYLON || (BABYLON = {}));
  45599. //# sourceMappingURL=babylon.shadowLight.js.map
  45600. var BABYLON;
  45601. (function (BABYLON) {
  45602. /**
  45603. * A point light is a light defined by an unique point in world space.
  45604. * The light is emitted in every direction from this point.
  45605. * A good example of a point light is a standard light bulb.
  45606. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45607. */
  45608. var PointLight = /** @class */ (function (_super) {
  45609. __extends(PointLight, _super);
  45610. /**
  45611. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45612. * A PointLight emits the light in every direction.
  45613. * It can cast shadows.
  45614. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45615. * ```javascript
  45616. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45617. * ```
  45618. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45619. * @param name The light friendly name
  45620. * @param position The position of the point light in the scene
  45621. * @param scene The scene the lights belongs to
  45622. */
  45623. function PointLight(name, position, scene) {
  45624. var _this = _super.call(this, name, scene) || this;
  45625. _this._shadowAngle = Math.PI / 2;
  45626. _this.position = position;
  45627. return _this;
  45628. }
  45629. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45630. /**
  45631. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45632. * This specifies what angle the shadow will use to be created.
  45633. *
  45634. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45635. */
  45636. get: function () {
  45637. return this._shadowAngle;
  45638. },
  45639. /**
  45640. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45641. * This specifies what angle the shadow will use to be created.
  45642. *
  45643. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45644. */
  45645. set: function (value) {
  45646. this._shadowAngle = value;
  45647. this.forceProjectionMatrixCompute();
  45648. },
  45649. enumerable: true,
  45650. configurable: true
  45651. });
  45652. Object.defineProperty(PointLight.prototype, "direction", {
  45653. /**
  45654. * Gets the direction if it has been set.
  45655. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45656. */
  45657. get: function () {
  45658. return this._direction;
  45659. },
  45660. /**
  45661. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45662. */
  45663. set: function (value) {
  45664. var previousNeedCube = this.needCube();
  45665. this._direction = value;
  45666. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45667. this._shadowGenerator.recreateShadowMap();
  45668. }
  45669. },
  45670. enumerable: true,
  45671. configurable: true
  45672. });
  45673. /**
  45674. * Returns the string "PointLight"
  45675. * @returns the class name
  45676. */
  45677. PointLight.prototype.getClassName = function () {
  45678. return "PointLight";
  45679. };
  45680. /**
  45681. * Returns the integer 0.
  45682. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45683. */
  45684. PointLight.prototype.getTypeID = function () {
  45685. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45686. };
  45687. /**
  45688. * Specifies wether or not the shadowmap should be a cube texture.
  45689. * @returns true if the shadowmap needs to be a cube texture.
  45690. */
  45691. PointLight.prototype.needCube = function () {
  45692. return !this.direction;
  45693. };
  45694. /**
  45695. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45696. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45697. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45698. */
  45699. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45700. if (this.direction) {
  45701. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45702. }
  45703. else {
  45704. switch (faceIndex) {
  45705. case 0:
  45706. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45707. case 1:
  45708. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45709. case 2:
  45710. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45711. case 3:
  45712. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45713. case 4:
  45714. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45715. case 5:
  45716. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45717. }
  45718. }
  45719. return BABYLON.Vector3.Zero();
  45720. };
  45721. /**
  45722. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45723. * - fov = PI / 2
  45724. * - aspect ratio : 1.0
  45725. * - z-near and far equal to the active camera minZ and maxZ.
  45726. * Returns the PointLight.
  45727. */
  45728. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45729. var activeCamera = this.getScene().activeCamera;
  45730. if (!activeCamera) {
  45731. return;
  45732. }
  45733. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45734. };
  45735. PointLight.prototype._buildUniformLayout = function () {
  45736. this._uniformBuffer.addUniform("vLightData", 4);
  45737. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45738. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45739. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45740. this._uniformBuffer.addUniform("depthValues", 2);
  45741. this._uniformBuffer.create();
  45742. };
  45743. /**
  45744. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45745. * @param effect The effect to update
  45746. * @param lightIndex The index of the light in the effect to update
  45747. * @returns The point light
  45748. */
  45749. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45750. if (this.computeTransformedInformation()) {
  45751. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45752. return this;
  45753. }
  45754. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45755. return this;
  45756. };
  45757. __decorate([
  45758. BABYLON.serialize()
  45759. ], PointLight.prototype, "shadowAngle", null);
  45760. return PointLight;
  45761. }(BABYLON.ShadowLight));
  45762. BABYLON.PointLight = PointLight;
  45763. })(BABYLON || (BABYLON = {}));
  45764. //# sourceMappingURL=babylon.pointLight.js.map
  45765. var BABYLON;
  45766. (function (BABYLON) {
  45767. /**
  45768. * A directional light is defined by a direction (what a surprise!).
  45769. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45770. * 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.
  45771. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45772. */
  45773. var DirectionalLight = /** @class */ (function (_super) {
  45774. __extends(DirectionalLight, _super);
  45775. /**
  45776. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45777. * The directional light is emitted from everywhere in the given direction.
  45778. * It can cast shawdows.
  45779. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45780. * @param name The friendly name of the light
  45781. * @param direction The direction of the light
  45782. * @param scene The scene the light belongs to
  45783. */
  45784. function DirectionalLight(name, direction, scene) {
  45785. var _this = _super.call(this, name, scene) || this;
  45786. _this._shadowFrustumSize = 0;
  45787. _this._shadowOrthoScale = 0.5;
  45788. /**
  45789. * Automatically compute the projection matrix to best fit (including all the casters)
  45790. * on each frame.
  45791. */
  45792. _this.autoUpdateExtends = true;
  45793. // Cache
  45794. _this._orthoLeft = Number.MAX_VALUE;
  45795. _this._orthoRight = Number.MIN_VALUE;
  45796. _this._orthoTop = Number.MIN_VALUE;
  45797. _this._orthoBottom = Number.MAX_VALUE;
  45798. _this.position = direction.scale(-1.0);
  45799. _this.direction = direction;
  45800. return _this;
  45801. }
  45802. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45803. /**
  45804. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45805. */
  45806. get: function () {
  45807. return this._shadowFrustumSize;
  45808. },
  45809. /**
  45810. * Specifies a fix frustum size for the shadow generation.
  45811. */
  45812. set: function (value) {
  45813. this._shadowFrustumSize = value;
  45814. this.forceProjectionMatrixCompute();
  45815. },
  45816. enumerable: true,
  45817. configurable: true
  45818. });
  45819. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45820. /**
  45821. * Gets the shadow projection scale against the optimal computed one.
  45822. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45823. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45824. */
  45825. get: function () {
  45826. return this._shadowOrthoScale;
  45827. },
  45828. /**
  45829. * Sets the shadow projection scale against the optimal computed one.
  45830. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45831. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45832. */
  45833. set: function (value) {
  45834. this._shadowOrthoScale = value;
  45835. this.forceProjectionMatrixCompute();
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. /**
  45841. * Returns the string "DirectionalLight".
  45842. * @return The class name
  45843. */
  45844. DirectionalLight.prototype.getClassName = function () {
  45845. return "DirectionalLight";
  45846. };
  45847. /**
  45848. * Returns the integer 1.
  45849. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45850. */
  45851. DirectionalLight.prototype.getTypeID = function () {
  45852. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45853. };
  45854. /**
  45855. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45856. * Returns the DirectionalLight Shadow projection matrix.
  45857. */
  45858. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45859. if (this.shadowFrustumSize > 0) {
  45860. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45861. }
  45862. else {
  45863. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45864. }
  45865. };
  45866. /**
  45867. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45868. * Returns the DirectionalLight Shadow projection matrix.
  45869. */
  45870. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45871. var activeCamera = this.getScene().activeCamera;
  45872. if (!activeCamera) {
  45873. return;
  45874. }
  45875. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45876. };
  45877. /**
  45878. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45879. * Returns the DirectionalLight Shadow projection matrix.
  45880. */
  45881. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45882. var activeCamera = this.getScene().activeCamera;
  45883. if (!activeCamera) {
  45884. return;
  45885. }
  45886. // Check extends
  45887. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45888. var tempVector3 = BABYLON.Vector3.Zero();
  45889. this._orthoLeft = Number.MAX_VALUE;
  45890. this._orthoRight = Number.MIN_VALUE;
  45891. this._orthoTop = Number.MIN_VALUE;
  45892. this._orthoBottom = Number.MAX_VALUE;
  45893. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45894. var mesh = renderList[meshIndex];
  45895. if (!mesh) {
  45896. continue;
  45897. }
  45898. var boundingInfo = mesh.getBoundingInfo();
  45899. var boundingBox = boundingInfo.boundingBox;
  45900. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45901. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45902. if (tempVector3.x < this._orthoLeft)
  45903. this._orthoLeft = tempVector3.x;
  45904. if (tempVector3.y < this._orthoBottom)
  45905. this._orthoBottom = tempVector3.y;
  45906. if (tempVector3.x > this._orthoRight)
  45907. this._orthoRight = tempVector3.x;
  45908. if (tempVector3.y > this._orthoTop)
  45909. this._orthoTop = tempVector3.y;
  45910. }
  45911. }
  45912. }
  45913. var xOffset = this._orthoRight - this._orthoLeft;
  45914. var yOffset = this._orthoTop - this._orthoBottom;
  45915. 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);
  45916. };
  45917. DirectionalLight.prototype._buildUniformLayout = function () {
  45918. this._uniformBuffer.addUniform("vLightData", 4);
  45919. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45920. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45921. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45922. this._uniformBuffer.addUniform("depthValues", 2);
  45923. this._uniformBuffer.create();
  45924. };
  45925. /**
  45926. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45927. * @param effect The effect to update
  45928. * @param lightIndex The index of the light in the effect to update
  45929. * @returns The directional light
  45930. */
  45931. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45932. if (this.computeTransformedInformation()) {
  45933. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45934. return this;
  45935. }
  45936. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45937. return this;
  45938. };
  45939. /**
  45940. * Gets the minZ used for shadow according to both the scene and the light.
  45941. *
  45942. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45943. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45944. * @param activeCamera The camera we are returning the min for
  45945. * @returns the depth min z
  45946. */
  45947. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45948. return 1;
  45949. };
  45950. /**
  45951. * Gets the maxZ used for shadow according to both the scene and the light.
  45952. *
  45953. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45954. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45955. * @param activeCamera The camera we are returning the max for
  45956. * @returns the depth max z
  45957. */
  45958. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45959. return 1;
  45960. };
  45961. __decorate([
  45962. BABYLON.serialize()
  45963. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45964. __decorate([
  45965. BABYLON.serialize()
  45966. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45967. __decorate([
  45968. BABYLON.serialize()
  45969. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45970. return DirectionalLight;
  45971. }(BABYLON.ShadowLight));
  45972. BABYLON.DirectionalLight = DirectionalLight;
  45973. })(BABYLON || (BABYLON = {}));
  45974. //# sourceMappingURL=babylon.directionalLight.js.map
  45975. var BABYLON;
  45976. (function (BABYLON) {
  45977. /**
  45978. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45979. * These values define a cone of light starting from the position, emitting toward the direction.
  45980. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45981. * and the exponent defines the speed of the decay of the light with distance (reach).
  45982. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45983. */
  45984. var SpotLight = /** @class */ (function (_super) {
  45985. __extends(SpotLight, _super);
  45986. /**
  45987. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45988. * It can cast shadows.
  45989. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45990. * @param name The light friendly name
  45991. * @param position The position of the spot light in the scene
  45992. * @param direction The direction of the light in the scene
  45993. * @param angle The cone angle of the light in Radians
  45994. * @param exponent The light decay speed with the distance from the emission spot
  45995. * @param scene The scene the lights belongs to
  45996. */
  45997. function SpotLight(name, position, direction, angle, exponent, scene) {
  45998. var _this = _super.call(this, name, scene) || this;
  45999. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46000. _this._projectionTextureLightNear = 1e-6;
  46001. _this._projectionTextureLightFar = 1000.0;
  46002. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46003. _this._projectionTextureViewLightDirty = true;
  46004. _this._projectionTextureProjectionLightDirty = true;
  46005. _this._projectionTextureDirty = true;
  46006. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46007. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46008. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46009. _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);
  46010. _this.position = position;
  46011. _this.direction = direction;
  46012. _this.angle = angle;
  46013. _this.exponent = exponent;
  46014. return _this;
  46015. }
  46016. Object.defineProperty(SpotLight.prototype, "angle", {
  46017. /**
  46018. * Gets the cone angle of the spot light in Radians.
  46019. */
  46020. get: function () {
  46021. return this._angle;
  46022. },
  46023. /**
  46024. * Sets the cone angle of the spot light in Radians.
  46025. */
  46026. set: function (value) {
  46027. this._angle = value;
  46028. this._projectionTextureProjectionLightDirty = true;
  46029. this.forceProjectionMatrixCompute();
  46030. },
  46031. enumerable: true,
  46032. configurable: true
  46033. });
  46034. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46035. /**
  46036. * Allows scaling the angle of the light for shadow generation only.
  46037. */
  46038. get: function () {
  46039. return this._shadowAngleScale;
  46040. },
  46041. /**
  46042. * Allows scaling the angle of the light for shadow generation only.
  46043. */
  46044. set: function (value) {
  46045. this._shadowAngleScale = value;
  46046. this.forceProjectionMatrixCompute();
  46047. },
  46048. enumerable: true,
  46049. configurable: true
  46050. });
  46051. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46052. /**
  46053. * Allows reading the projecton texture
  46054. */
  46055. get: function () {
  46056. return this._projectionTextureMatrix;
  46057. },
  46058. enumerable: true,
  46059. configurable: true
  46060. });
  46061. ;
  46062. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46063. /**
  46064. * Gets the near clip of the Spotlight for texture projection.
  46065. */
  46066. get: function () {
  46067. return this._projectionTextureLightNear;
  46068. },
  46069. /**
  46070. * Sets the near clip of the Spotlight for texture projection.
  46071. */
  46072. set: function (value) {
  46073. this._projectionTextureLightNear = value;
  46074. this._projectionTextureProjectionLightDirty = true;
  46075. },
  46076. enumerable: true,
  46077. configurable: true
  46078. });
  46079. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46080. /**
  46081. * Gets the far clip of the Spotlight for texture projection.
  46082. */
  46083. get: function () {
  46084. return this._projectionTextureLightFar;
  46085. },
  46086. /**
  46087. * Sets the far clip of the Spotlight for texture projection.
  46088. */
  46089. set: function (value) {
  46090. this._projectionTextureLightFar = value;
  46091. this._projectionTextureProjectionLightDirty = true;
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46097. /**
  46098. * Gets the Up vector of the Spotlight for texture projection.
  46099. */
  46100. get: function () {
  46101. return this._projectionTextureUpDirection;
  46102. },
  46103. /**
  46104. * Sets the Up vector of the Spotlight for texture projection.
  46105. */
  46106. set: function (value) {
  46107. this._projectionTextureUpDirection = value;
  46108. this._projectionTextureProjectionLightDirty = true;
  46109. },
  46110. enumerable: true,
  46111. configurable: true
  46112. });
  46113. ;
  46114. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46115. /**
  46116. * Gets the projection texture of the light.
  46117. */
  46118. get: function () {
  46119. return this._projectionTexture;
  46120. },
  46121. /**
  46122. * Sets the projection texture of the light.
  46123. */
  46124. set: function (value) {
  46125. this._projectionTexture = value;
  46126. this._projectionTextureDirty = true;
  46127. },
  46128. enumerable: true,
  46129. configurable: true
  46130. });
  46131. /**
  46132. * Returns the string "SpotLight".
  46133. * @returns the class name
  46134. */
  46135. SpotLight.prototype.getClassName = function () {
  46136. return "SpotLight";
  46137. };
  46138. /**
  46139. * Returns the integer 2.
  46140. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46141. */
  46142. SpotLight.prototype.getTypeID = function () {
  46143. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46144. };
  46145. /**
  46146. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46147. */
  46148. SpotLight.prototype._setDirection = function (value) {
  46149. _super.prototype._setDirection.call(this, value);
  46150. this._projectionTextureViewLightDirty = true;
  46151. };
  46152. /**
  46153. * Overrides the position setter to recompute the projection texture view light Matrix.
  46154. */
  46155. SpotLight.prototype._setPosition = function (value) {
  46156. _super.prototype._setPosition.call(this, value);
  46157. this._projectionTextureViewLightDirty = true;
  46158. };
  46159. /**
  46160. * 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.
  46161. * Returns the SpotLight.
  46162. */
  46163. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46164. var activeCamera = this.getScene().activeCamera;
  46165. if (!activeCamera) {
  46166. return;
  46167. }
  46168. this._shadowAngleScale = this._shadowAngleScale || 1;
  46169. var angle = this._shadowAngleScale * this._angle;
  46170. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46171. };
  46172. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46173. this._projectionTextureViewLightDirty = false;
  46174. this._projectionTextureDirty = true;
  46175. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46176. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46177. };
  46178. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46179. this._projectionTextureProjectionLightDirty = false;
  46180. this._projectionTextureDirty = true;
  46181. var light_far = this.projectionTextureLightFar;
  46182. var light_near = this.projectionTextureLightNear;
  46183. var P = light_far / (light_far - light_near);
  46184. var Q = -P * light_near;
  46185. var S = 1.0 / Math.tan(this._angle / 2.0);
  46186. var A = 1.0;
  46187. 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);
  46188. };
  46189. /**
  46190. * Main function for light texture projection matrix computing.
  46191. */
  46192. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46193. this._projectionTextureDirty = false;
  46194. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46195. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46196. };
  46197. SpotLight.prototype._buildUniformLayout = function () {
  46198. this._uniformBuffer.addUniform("vLightData", 4);
  46199. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46200. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46201. this._uniformBuffer.addUniform("vLightDirection", 3);
  46202. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46203. this._uniformBuffer.addUniform("depthValues", 2);
  46204. this._uniformBuffer.create();
  46205. };
  46206. /**
  46207. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46208. * @param effect The effect to update
  46209. * @param lightIndex The index of the light in the effect to update
  46210. * @returns The spot light
  46211. */
  46212. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46213. var normalizeDirection;
  46214. if (this.computeTransformedInformation()) {
  46215. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46216. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46217. }
  46218. else {
  46219. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46220. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46221. }
  46222. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46223. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46224. if (this._projectionTextureViewLightDirty) {
  46225. this._computeProjectionTextureViewLightMatrix();
  46226. }
  46227. if (this._projectionTextureProjectionLightDirty) {
  46228. this._computeProjectionTextureProjectionLightMatrix();
  46229. }
  46230. if (this._projectionTextureDirty) {
  46231. this._computeProjectionTextureMatrix();
  46232. }
  46233. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46234. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46235. }
  46236. return this;
  46237. };
  46238. /**
  46239. * Disposes the light and the associated resources.
  46240. */
  46241. SpotLight.prototype.dispose = function () {
  46242. _super.prototype.dispose.call(this);
  46243. if (this._projectionTexture) {
  46244. this._projectionTexture.dispose();
  46245. }
  46246. };
  46247. __decorate([
  46248. BABYLON.serialize()
  46249. ], SpotLight.prototype, "angle", null);
  46250. __decorate([
  46251. BABYLON.serialize()
  46252. ], SpotLight.prototype, "shadowAngleScale", null);
  46253. __decorate([
  46254. BABYLON.serialize()
  46255. ], SpotLight.prototype, "exponent", void 0);
  46256. __decorate([
  46257. BABYLON.serialize()
  46258. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46259. __decorate([
  46260. BABYLON.serialize()
  46261. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46262. __decorate([
  46263. BABYLON.serialize()
  46264. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46265. __decorate([
  46266. BABYLON.serializeAsTexture("projectedLightTexture")
  46267. ], SpotLight.prototype, "_projectionTexture", void 0);
  46268. return SpotLight;
  46269. }(BABYLON.ShadowLight));
  46270. BABYLON.SpotLight = SpotLight;
  46271. })(BABYLON || (BABYLON = {}));
  46272. //# sourceMappingURL=babylon.spotLight.js.map
  46273. var BABYLON;
  46274. (function (BABYLON) {
  46275. /**
  46276. * Class used to override all child animations of a given target
  46277. */
  46278. var AnimationPropertiesOverride = /** @class */ (function () {
  46279. function AnimationPropertiesOverride() {
  46280. /**
  46281. * Gets or sets a value indicating if animation blending must be used
  46282. */
  46283. this.enableBlending = false;
  46284. /**
  46285. * Gets or sets the blending speed to use when enableBlending is true
  46286. */
  46287. this.blendingSpeed = 0.01;
  46288. /**
  46289. * Gets or sets the default loop mode to use
  46290. */
  46291. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46292. }
  46293. return AnimationPropertiesOverride;
  46294. }());
  46295. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46296. })(BABYLON || (BABYLON = {}));
  46297. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46298. var BABYLON;
  46299. (function (BABYLON) {
  46300. var AnimationRange = /** @class */ (function () {
  46301. function AnimationRange(name, from, to) {
  46302. this.name = name;
  46303. this.from = from;
  46304. this.to = to;
  46305. }
  46306. AnimationRange.prototype.clone = function () {
  46307. return new AnimationRange(this.name, this.from, this.to);
  46308. };
  46309. return AnimationRange;
  46310. }());
  46311. BABYLON.AnimationRange = AnimationRange;
  46312. /**
  46313. * Composed of a frame, and an action function
  46314. */
  46315. var AnimationEvent = /** @class */ (function () {
  46316. function AnimationEvent(frame, action, onlyOnce) {
  46317. this.frame = frame;
  46318. this.action = action;
  46319. this.onlyOnce = onlyOnce;
  46320. this.isDone = false;
  46321. }
  46322. return AnimationEvent;
  46323. }());
  46324. BABYLON.AnimationEvent = AnimationEvent;
  46325. var PathCursor = /** @class */ (function () {
  46326. function PathCursor(path) {
  46327. this.path = path;
  46328. this._onchange = new Array();
  46329. this.value = 0;
  46330. this.animations = new Array();
  46331. }
  46332. PathCursor.prototype.getPoint = function () {
  46333. var point = this.path.getPointAtLengthPosition(this.value);
  46334. return new BABYLON.Vector3(point.x, 0, point.y);
  46335. };
  46336. PathCursor.prototype.moveAhead = function (step) {
  46337. if (step === void 0) { step = 0.002; }
  46338. this.move(step);
  46339. return this;
  46340. };
  46341. PathCursor.prototype.moveBack = function (step) {
  46342. if (step === void 0) { step = 0.002; }
  46343. this.move(-step);
  46344. return this;
  46345. };
  46346. PathCursor.prototype.move = function (step) {
  46347. if (Math.abs(step) > 1) {
  46348. throw "step size should be less than 1.";
  46349. }
  46350. this.value += step;
  46351. this.ensureLimits();
  46352. this.raiseOnChange();
  46353. return this;
  46354. };
  46355. PathCursor.prototype.ensureLimits = function () {
  46356. while (this.value > 1) {
  46357. this.value -= 1;
  46358. }
  46359. while (this.value < 0) {
  46360. this.value += 1;
  46361. }
  46362. return this;
  46363. };
  46364. // used by animation engine
  46365. PathCursor.prototype.raiseOnChange = function () {
  46366. var _this = this;
  46367. this._onchange.forEach(function (f) { return f(_this); });
  46368. return this;
  46369. };
  46370. PathCursor.prototype.onchange = function (f) {
  46371. this._onchange.push(f);
  46372. return this;
  46373. };
  46374. return PathCursor;
  46375. }());
  46376. BABYLON.PathCursor = PathCursor;
  46377. var AnimationKeyInterpolation;
  46378. (function (AnimationKeyInterpolation) {
  46379. /**
  46380. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46381. */
  46382. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46383. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46384. var Animation = /** @class */ (function () {
  46385. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46386. this.name = name;
  46387. this.targetProperty = targetProperty;
  46388. this.framePerSecond = framePerSecond;
  46389. this.dataType = dataType;
  46390. this.loopMode = loopMode;
  46391. this.enableBlending = enableBlending;
  46392. this._runtimeAnimations = new Array();
  46393. // The set of event that will be linked to this animation
  46394. this._events = new Array();
  46395. this.blendingSpeed = 0.01;
  46396. this._ranges = {};
  46397. this.targetPropertyPath = targetProperty.split(".");
  46398. this.dataType = dataType;
  46399. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46400. }
  46401. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46402. var dataType = undefined;
  46403. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46404. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46405. }
  46406. else if (from instanceof BABYLON.Quaternion) {
  46407. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46408. }
  46409. else if (from instanceof BABYLON.Vector3) {
  46410. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46411. }
  46412. else if (from instanceof BABYLON.Vector2) {
  46413. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46414. }
  46415. else if (from instanceof BABYLON.Color3) {
  46416. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46417. }
  46418. else if (from instanceof BABYLON.Size) {
  46419. dataType = Animation.ANIMATIONTYPE_SIZE;
  46420. }
  46421. if (dataType == undefined) {
  46422. return null;
  46423. }
  46424. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46425. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46426. animation.setKeys(keys);
  46427. if (easingFunction !== undefined) {
  46428. animation.setEasingFunction(easingFunction);
  46429. }
  46430. return animation;
  46431. };
  46432. /**
  46433. * Sets up an animation.
  46434. * @param property the property to animate
  46435. * @param animationType the animation type to apply
  46436. * @param easingFunction the easing function used in the animation
  46437. * @returns The created animation
  46438. */
  46439. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46440. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46441. animation.setEasingFunction(easingFunction);
  46442. return animation;
  46443. };
  46444. /**
  46445. * Create and start an animation on a node
  46446. * @param {string} name defines the name of the global animation that will be run on all nodes
  46447. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46448. * @param {string} targetProperty defines property to animate
  46449. * @param {number} framePerSecond defines the number of frame per second yo use
  46450. * @param {number} totalFrame defines the number of frames in total
  46451. * @param {any} from defines the initial value
  46452. * @param {any} to defines the final value
  46453. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46454. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46455. * @param onAnimationEnd defines the callback to call when animation end
  46456. * @returns the animatable created for this animation
  46457. */
  46458. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46459. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46460. if (!animation) {
  46461. return null;
  46462. }
  46463. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46464. };
  46465. /**
  46466. * Create and start an animation on a node and its descendants
  46467. * @param {string} name defines the name of the global animation that will be run on all nodes
  46468. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46469. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46470. * @param {string} targetProperty defines property to animate
  46471. * @param {number} framePerSecond defines the number of frame per second yo use
  46472. * @param {number} totalFrame defines the number of frames in total
  46473. * @param {any} from defines the initial value
  46474. * @param {any} to defines the final value
  46475. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46476. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46477. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46478. * @returns the list of animatables created for all nodes
  46479. * @example https://www.babylonjs-playground.com/#MH0VLI
  46480. */
  46481. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46482. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46483. if (!animation) {
  46484. return null;
  46485. }
  46486. var scene = node.getScene();
  46487. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46488. };
  46489. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46490. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46491. if (!animation) {
  46492. return null;
  46493. }
  46494. node.animations.push(animation);
  46495. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46496. };
  46497. /**
  46498. * Transition property of the Camera to the target Value.
  46499. * @param property The property to transition
  46500. * @param targetValue The target Value of the property
  46501. * @param host The object where the property to animate belongs
  46502. * @param scene Scene used to run the animation
  46503. * @param frameRate Framerate (in frame/s) to use
  46504. * @param transition The transition type we want to use
  46505. * @param duration The duration of the animation, in milliseconds
  46506. * @param onAnimationEnd Call back trigger at the end of the animation.
  46507. */
  46508. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46509. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46510. if (duration <= 0) {
  46511. host[property] = targetValue;
  46512. if (onAnimationEnd) {
  46513. onAnimationEnd();
  46514. }
  46515. return null;
  46516. }
  46517. var endFrame = frameRate * (duration / 1000);
  46518. transition.setKeys([{
  46519. frame: 0,
  46520. value: host[property].clone ? host[property].clone() : host[property]
  46521. },
  46522. {
  46523. frame: endFrame,
  46524. value: targetValue
  46525. }]);
  46526. if (!host.animations) {
  46527. host.animations = [];
  46528. }
  46529. host.animations.push(transition);
  46530. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46531. animation.onAnimationEnd = onAnimationEnd;
  46532. return animation;
  46533. };
  46534. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46535. /**
  46536. * Return the array of runtime animations currently using this animation
  46537. */
  46538. get: function () {
  46539. return this._runtimeAnimations;
  46540. },
  46541. enumerable: true,
  46542. configurable: true
  46543. });
  46544. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46545. get: function () {
  46546. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46547. var runtimeAnimation = _a[_i];
  46548. if (!runtimeAnimation.isStopped) {
  46549. return true;
  46550. }
  46551. }
  46552. return false;
  46553. },
  46554. enumerable: true,
  46555. configurable: true
  46556. });
  46557. // Methods
  46558. /**
  46559. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46560. */
  46561. Animation.prototype.toString = function (fullDetails) {
  46562. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46563. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46564. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46565. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46566. if (fullDetails) {
  46567. ret += ", Ranges: {";
  46568. var first = true;
  46569. for (var name in this._ranges) {
  46570. if (first) {
  46571. ret += ", ";
  46572. first = false;
  46573. }
  46574. ret += name;
  46575. }
  46576. ret += "}";
  46577. }
  46578. return ret;
  46579. };
  46580. /**
  46581. * Add an event to this animation.
  46582. */
  46583. Animation.prototype.addEvent = function (event) {
  46584. this._events.push(event);
  46585. };
  46586. /**
  46587. * Remove all events found at the given frame
  46588. * @param frame
  46589. */
  46590. Animation.prototype.removeEvents = function (frame) {
  46591. for (var index = 0; index < this._events.length; index++) {
  46592. if (this._events[index].frame === frame) {
  46593. this._events.splice(index, 1);
  46594. index--;
  46595. }
  46596. }
  46597. };
  46598. Animation.prototype.getEvents = function () {
  46599. return this._events;
  46600. };
  46601. Animation.prototype.createRange = function (name, from, to) {
  46602. // check name not already in use; could happen for bones after serialized
  46603. if (!this._ranges[name]) {
  46604. this._ranges[name] = new AnimationRange(name, from, to);
  46605. }
  46606. };
  46607. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46608. if (deleteFrames === void 0) { deleteFrames = true; }
  46609. var range = this._ranges[name];
  46610. if (!range) {
  46611. return;
  46612. }
  46613. if (deleteFrames) {
  46614. var from = range.from;
  46615. var to = range.to;
  46616. // this loop MUST go high to low for multiple splices to work
  46617. for (var key = this._keys.length - 1; key >= 0; key--) {
  46618. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46619. this._keys.splice(key, 1);
  46620. }
  46621. }
  46622. }
  46623. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46624. };
  46625. Animation.prototype.getRange = function (name) {
  46626. return this._ranges[name];
  46627. };
  46628. Animation.prototype.getKeys = function () {
  46629. return this._keys;
  46630. };
  46631. Animation.prototype.getHighestFrame = function () {
  46632. var ret = 0;
  46633. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46634. if (ret < this._keys[key].frame) {
  46635. ret = this._keys[key].frame;
  46636. }
  46637. }
  46638. return ret;
  46639. };
  46640. Animation.prototype.getEasingFunction = function () {
  46641. return this._easingFunction;
  46642. };
  46643. Animation.prototype.setEasingFunction = function (easingFunction) {
  46644. this._easingFunction = easingFunction;
  46645. };
  46646. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46647. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46648. };
  46649. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46650. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46651. };
  46652. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46653. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46654. };
  46655. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46656. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46657. };
  46658. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46659. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46660. };
  46661. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46662. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46663. };
  46664. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46665. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46666. };
  46667. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46668. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46669. };
  46670. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46671. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46672. };
  46673. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46674. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46675. };
  46676. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46677. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46678. };
  46679. Animation.prototype.clone = function () {
  46680. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46681. clone.enableBlending = this.enableBlending;
  46682. clone.blendingSpeed = this.blendingSpeed;
  46683. if (this._keys) {
  46684. clone.setKeys(this._keys);
  46685. }
  46686. if (this._ranges) {
  46687. clone._ranges = {};
  46688. for (var name in this._ranges) {
  46689. var range = this._ranges[name];
  46690. if (!range) {
  46691. continue;
  46692. }
  46693. clone._ranges[name] = range.clone();
  46694. }
  46695. }
  46696. return clone;
  46697. };
  46698. Animation.prototype.setKeys = function (values) {
  46699. this._keys = values.slice(0);
  46700. };
  46701. Animation.prototype.serialize = function () {
  46702. var serializationObject = {};
  46703. serializationObject.name = this.name;
  46704. serializationObject.property = this.targetProperty;
  46705. serializationObject.framePerSecond = this.framePerSecond;
  46706. serializationObject.dataType = this.dataType;
  46707. serializationObject.loopBehavior = this.loopMode;
  46708. serializationObject.enableBlending = this.enableBlending;
  46709. serializationObject.blendingSpeed = this.blendingSpeed;
  46710. var dataType = this.dataType;
  46711. serializationObject.keys = [];
  46712. var keys = this.getKeys();
  46713. for (var index = 0; index < keys.length; index++) {
  46714. var animationKey = keys[index];
  46715. var key = {};
  46716. key.frame = animationKey.frame;
  46717. switch (dataType) {
  46718. case Animation.ANIMATIONTYPE_FLOAT:
  46719. key.values = [animationKey.value];
  46720. break;
  46721. case Animation.ANIMATIONTYPE_QUATERNION:
  46722. case Animation.ANIMATIONTYPE_MATRIX:
  46723. case Animation.ANIMATIONTYPE_VECTOR3:
  46724. case Animation.ANIMATIONTYPE_COLOR3:
  46725. key.values = animationKey.value.asArray();
  46726. break;
  46727. }
  46728. serializationObject.keys.push(key);
  46729. }
  46730. serializationObject.ranges = [];
  46731. for (var name in this._ranges) {
  46732. var source = this._ranges[name];
  46733. if (!source) {
  46734. continue;
  46735. }
  46736. var range = {};
  46737. range.name = name;
  46738. range.from = source.from;
  46739. range.to = source.to;
  46740. serializationObject.ranges.push(range);
  46741. }
  46742. return serializationObject;
  46743. };
  46744. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46745. get: function () {
  46746. return Animation._ANIMATIONTYPE_FLOAT;
  46747. },
  46748. enumerable: true,
  46749. configurable: true
  46750. });
  46751. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46752. get: function () {
  46753. return Animation._ANIMATIONTYPE_VECTOR3;
  46754. },
  46755. enumerable: true,
  46756. configurable: true
  46757. });
  46758. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46759. get: function () {
  46760. return Animation._ANIMATIONTYPE_VECTOR2;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46766. get: function () {
  46767. return Animation._ANIMATIONTYPE_SIZE;
  46768. },
  46769. enumerable: true,
  46770. configurable: true
  46771. });
  46772. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46773. get: function () {
  46774. return Animation._ANIMATIONTYPE_QUATERNION;
  46775. },
  46776. enumerable: true,
  46777. configurable: true
  46778. });
  46779. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46780. get: function () {
  46781. return Animation._ANIMATIONTYPE_MATRIX;
  46782. },
  46783. enumerable: true,
  46784. configurable: true
  46785. });
  46786. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46787. get: function () {
  46788. return Animation._ANIMATIONTYPE_COLOR3;
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46794. get: function () {
  46795. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46801. get: function () {
  46802. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46803. },
  46804. enumerable: true,
  46805. configurable: true
  46806. });
  46807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46808. get: function () {
  46809. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46810. },
  46811. enumerable: true,
  46812. configurable: true
  46813. });
  46814. Animation.Parse = function (parsedAnimation) {
  46815. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46816. var dataType = parsedAnimation.dataType;
  46817. var keys = [];
  46818. var data;
  46819. var index;
  46820. if (parsedAnimation.enableBlending) {
  46821. animation.enableBlending = parsedAnimation.enableBlending;
  46822. }
  46823. if (parsedAnimation.blendingSpeed) {
  46824. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46825. }
  46826. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46827. var key = parsedAnimation.keys[index];
  46828. var inTangent;
  46829. var outTangent;
  46830. switch (dataType) {
  46831. case Animation.ANIMATIONTYPE_FLOAT:
  46832. data = key.values[0];
  46833. if (key.values.length >= 1) {
  46834. inTangent = key.values[1];
  46835. }
  46836. if (key.values.length >= 2) {
  46837. outTangent = key.values[2];
  46838. }
  46839. break;
  46840. case Animation.ANIMATIONTYPE_QUATERNION:
  46841. data = BABYLON.Quaternion.FromArray(key.values);
  46842. if (key.values.length >= 8) {
  46843. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46844. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46845. inTangent = _inTangent;
  46846. }
  46847. }
  46848. if (key.values.length >= 12) {
  46849. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46850. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46851. outTangent = _outTangent;
  46852. }
  46853. }
  46854. break;
  46855. case Animation.ANIMATIONTYPE_MATRIX:
  46856. data = BABYLON.Matrix.FromArray(key.values);
  46857. break;
  46858. case Animation.ANIMATIONTYPE_COLOR3:
  46859. data = BABYLON.Color3.FromArray(key.values);
  46860. break;
  46861. case Animation.ANIMATIONTYPE_VECTOR3:
  46862. default:
  46863. data = BABYLON.Vector3.FromArray(key.values);
  46864. break;
  46865. }
  46866. var keyData = {};
  46867. keyData.frame = key.frame;
  46868. keyData.value = data;
  46869. if (inTangent != undefined) {
  46870. keyData.inTangent = inTangent;
  46871. }
  46872. if (outTangent != undefined) {
  46873. keyData.outTangent = outTangent;
  46874. }
  46875. keys.push(keyData);
  46876. }
  46877. animation.setKeys(keys);
  46878. if (parsedAnimation.ranges) {
  46879. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46880. data = parsedAnimation.ranges[index];
  46881. animation.createRange(data.name, data.from, data.to);
  46882. }
  46883. }
  46884. return animation;
  46885. };
  46886. Animation.AppendSerializedAnimations = function (source, destination) {
  46887. if (source.animations) {
  46888. destination.animations = [];
  46889. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46890. var animation = source.animations[animationIndex];
  46891. destination.animations.push(animation.serialize());
  46892. }
  46893. }
  46894. };
  46895. Animation.AllowMatricesInterpolation = false;
  46896. // Statics
  46897. Animation._ANIMATIONTYPE_FLOAT = 0;
  46898. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46899. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46900. Animation._ANIMATIONTYPE_MATRIX = 3;
  46901. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46902. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46903. Animation._ANIMATIONTYPE_SIZE = 6;
  46904. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46905. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46906. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46907. return Animation;
  46908. }());
  46909. BABYLON.Animation = Animation;
  46910. })(BABYLON || (BABYLON = {}));
  46911. //# sourceMappingURL=babylon.animation.js.map
  46912. var BABYLON;
  46913. (function (BABYLON) {
  46914. /**
  46915. * This class defines the direct association between an animation and a target
  46916. */
  46917. var TargetedAnimation = /** @class */ (function () {
  46918. function TargetedAnimation() {
  46919. }
  46920. return TargetedAnimation;
  46921. }());
  46922. BABYLON.TargetedAnimation = TargetedAnimation;
  46923. /**
  46924. * Use this class to create coordinated animations on multiple targets
  46925. */
  46926. var AnimationGroup = /** @class */ (function () {
  46927. function AnimationGroup(name, scene) {
  46928. if (scene === void 0) { scene = null; }
  46929. this.name = name;
  46930. this._targetedAnimations = new Array();
  46931. this._animatables = new Array();
  46932. this._from = Number.MAX_VALUE;
  46933. this._to = -Number.MAX_VALUE;
  46934. this._speedRatio = 1;
  46935. this.onAnimationEndObservable = new BABYLON.Observable();
  46936. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46937. this._scene.animationGroups.push(this);
  46938. }
  46939. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46940. /**
  46941. * Define if the animations are started
  46942. */
  46943. get: function () {
  46944. return this._isStarted;
  46945. },
  46946. enumerable: true,
  46947. configurable: true
  46948. });
  46949. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46950. /**
  46951. * Gets or sets the speed ratio to use for all animations
  46952. */
  46953. get: function () {
  46954. return this._speedRatio;
  46955. },
  46956. /**
  46957. * Gets or sets the speed ratio to use for all animations
  46958. */
  46959. set: function (value) {
  46960. if (this._speedRatio === value) {
  46961. return;
  46962. }
  46963. this._speedRatio = value;
  46964. for (var index = 0; index < this._animatables.length; index++) {
  46965. var animatable = this._animatables[index];
  46966. animatable.speedRatio = this._speedRatio;
  46967. }
  46968. },
  46969. enumerable: true,
  46970. configurable: true
  46971. });
  46972. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46973. /**
  46974. * Gets the targeted animations for this animation group
  46975. */
  46976. get: function () {
  46977. return this._targetedAnimations;
  46978. },
  46979. enumerable: true,
  46980. configurable: true
  46981. });
  46982. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46983. /**
  46984. * returning the list of animatables controlled by this animation group.
  46985. */
  46986. get: function () {
  46987. return this._animatables;
  46988. },
  46989. enumerable: true,
  46990. configurable: true
  46991. });
  46992. /**
  46993. * Add an animation (with its target) in the group
  46994. * @param animation defines the animation we want to add
  46995. * @param target defines the target of the animation
  46996. * @returns the {BABYLON.TargetedAnimation} object
  46997. */
  46998. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46999. var targetedAnimation = {
  47000. animation: animation,
  47001. target: target
  47002. };
  47003. var keys = animation.getKeys();
  47004. if (this._from > keys[0].frame) {
  47005. this._from = keys[0].frame;
  47006. }
  47007. if (this._to < keys[keys.length - 1].frame) {
  47008. this._to = keys[keys.length - 1].frame;
  47009. }
  47010. this._targetedAnimations.push(targetedAnimation);
  47011. return targetedAnimation;
  47012. };
  47013. /**
  47014. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47015. * It can add constant keys at begin or end
  47016. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47017. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47018. */
  47019. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47020. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47021. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47022. beginFrame = Math.max(beginFrame, this._from);
  47023. endFrame = Math.min(endFrame, this._to);
  47024. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47025. var targetedAnimation = this._targetedAnimations[index];
  47026. var keys = targetedAnimation.animation.getKeys();
  47027. var startKey = keys[0];
  47028. var endKey = keys[keys.length - 1];
  47029. if (startKey.frame > beginFrame) {
  47030. var newKey = {
  47031. frame: beginFrame,
  47032. value: startKey.value,
  47033. inTangent: startKey.inTangent,
  47034. outTangent: startKey.outTangent,
  47035. interpolation: startKey.interpolation
  47036. };
  47037. keys.splice(0, 0, newKey);
  47038. }
  47039. if (endKey.frame < endFrame) {
  47040. var newKey = {
  47041. frame: endFrame,
  47042. value: endKey.value,
  47043. inTangent: endKey.outTangent,
  47044. outTangent: endKey.outTangent,
  47045. interpolation: endKey.interpolation
  47046. };
  47047. keys.push(newKey);
  47048. }
  47049. }
  47050. return this;
  47051. };
  47052. /**
  47053. * Start all animations on given targets
  47054. * @param loop defines if animations must loop
  47055. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47056. */
  47057. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47058. var _this = this;
  47059. if (loop === void 0) { loop = false; }
  47060. if (speedRatio === void 0) { speedRatio = 1; }
  47061. if (this._isStarted || this._targetedAnimations.length === 0) {
  47062. return this;
  47063. }
  47064. var _loop_1 = function () {
  47065. var targetedAnimation = this_1._targetedAnimations[index];
  47066. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47067. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47068. }));
  47069. };
  47070. var this_1 = this;
  47071. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47072. _loop_1();
  47073. }
  47074. this._speedRatio = speedRatio;
  47075. this._isStarted = true;
  47076. return this;
  47077. };
  47078. /**
  47079. * Pause all animations
  47080. */
  47081. AnimationGroup.prototype.pause = function () {
  47082. if (!this._isStarted) {
  47083. return this;
  47084. }
  47085. for (var index = 0; index < this._animatables.length; index++) {
  47086. var animatable = this._animatables[index];
  47087. animatable.pause();
  47088. }
  47089. return this;
  47090. };
  47091. /**
  47092. * Play all animations to initial state
  47093. * This function will start() the animations if they were not started or will restart() them if they were paused
  47094. * @param loop defines if animations must loop
  47095. */
  47096. AnimationGroup.prototype.play = function (loop) {
  47097. if (this.isStarted) {
  47098. if (loop !== undefined) {
  47099. for (var index = 0; index < this._animatables.length; index++) {
  47100. var animatable = this._animatables[index];
  47101. animatable.loopAnimation = loop;
  47102. }
  47103. }
  47104. this.restart();
  47105. }
  47106. else {
  47107. this.start(loop, this._speedRatio);
  47108. }
  47109. return this;
  47110. };
  47111. /**
  47112. * Reset all animations to initial state
  47113. */
  47114. AnimationGroup.prototype.reset = function () {
  47115. if (!this._isStarted) {
  47116. return this;
  47117. }
  47118. for (var index = 0; index < this._animatables.length; index++) {
  47119. var animatable = this._animatables[index];
  47120. animatable.reset();
  47121. }
  47122. return this;
  47123. };
  47124. /**
  47125. * Restart animations from key 0
  47126. */
  47127. AnimationGroup.prototype.restart = function () {
  47128. if (!this._isStarted) {
  47129. return this;
  47130. }
  47131. for (var index = 0; index < this._animatables.length; index++) {
  47132. var animatable = this._animatables[index];
  47133. animatable.restart();
  47134. }
  47135. return this;
  47136. };
  47137. /**
  47138. * Stop all animations
  47139. */
  47140. AnimationGroup.prototype.stop = function () {
  47141. if (!this._isStarted) {
  47142. return this;
  47143. }
  47144. for (var index = 0; index < this._animatables.length; index++) {
  47145. var animatable = this._animatables[index];
  47146. animatable.stop();
  47147. }
  47148. this._isStarted = false;
  47149. return this;
  47150. };
  47151. /**
  47152. * Goes to a specific frame in this animation group
  47153. *
  47154. * @param frame the frame number to go to
  47155. * @return the animationGroup
  47156. */
  47157. AnimationGroup.prototype.goToFrame = function (frame) {
  47158. if (!this._isStarted) {
  47159. return this;
  47160. }
  47161. for (var index = 0; index < this._animatables.length; index++) {
  47162. var animatable = this._animatables[index];
  47163. animatable.goToFrame(frame);
  47164. }
  47165. return this;
  47166. };
  47167. /**
  47168. * Dispose all associated resources
  47169. */
  47170. AnimationGroup.prototype.dispose = function () {
  47171. this._targetedAnimations = [];
  47172. this._animatables = [];
  47173. var index = this._scene.animationGroups.indexOf(this);
  47174. if (index > -1) {
  47175. this._scene.animationGroups.splice(index, 1);
  47176. }
  47177. };
  47178. return AnimationGroup;
  47179. }());
  47180. BABYLON.AnimationGroup = AnimationGroup;
  47181. })(BABYLON || (BABYLON = {}));
  47182. //# sourceMappingURL=babylon.animationGroup.js.map
  47183. var BABYLON;
  47184. (function (BABYLON) {
  47185. var RuntimeAnimation = /** @class */ (function () {
  47186. function RuntimeAnimation(target, animation) {
  47187. this._offsetsCache = {};
  47188. this._highLimitsCache = {};
  47189. this._stopped = false;
  47190. this._blendingFactor = 0;
  47191. this._ratioOffset = 0;
  47192. this._animation = animation;
  47193. this._target = target;
  47194. animation._runtimeAnimations.push(this);
  47195. }
  47196. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47197. get: function () {
  47198. return this._animation;
  47199. },
  47200. enumerable: true,
  47201. configurable: true
  47202. });
  47203. RuntimeAnimation.prototype.reset = function () {
  47204. this._offsetsCache = {};
  47205. this._highLimitsCache = {};
  47206. this.currentFrame = 0;
  47207. this._blendingFactor = 0;
  47208. this._originalBlendValue = null;
  47209. };
  47210. RuntimeAnimation.prototype.isStopped = function () {
  47211. return this._stopped;
  47212. };
  47213. RuntimeAnimation.prototype.dispose = function () {
  47214. var index = this._animation.runtimeAnimations.indexOf(this);
  47215. if (index > -1) {
  47216. this._animation.runtimeAnimations.splice(index, 1);
  47217. }
  47218. };
  47219. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47220. if (typeof value === "function") {
  47221. return value();
  47222. }
  47223. return value;
  47224. };
  47225. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47226. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47227. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47228. }
  47229. this.currentFrame = currentFrame;
  47230. var keys = this._animation.getKeys();
  47231. // Try to get a hash to find the right key
  47232. 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));
  47233. if (keys[startKeyIndex].frame >= currentFrame) {
  47234. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47235. startKeyIndex--;
  47236. }
  47237. }
  47238. for (var key = startKeyIndex; key < keys.length; key++) {
  47239. var endKey = keys[key + 1];
  47240. if (endKey.frame >= currentFrame) {
  47241. var startKey = keys[key];
  47242. var startValue = this._getKeyValue(startKey.value);
  47243. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47244. return startValue;
  47245. }
  47246. var endValue = this._getKeyValue(endKey.value);
  47247. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47248. var frameDelta = endKey.frame - startKey.frame;
  47249. // gradient : percent of currentFrame between the frame inf and the frame sup
  47250. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47251. // check for easingFunction and correction of gradient
  47252. var easingFunction = this._animation.getEasingFunction();
  47253. if (easingFunction != null) {
  47254. gradient = easingFunction.ease(gradient);
  47255. }
  47256. switch (this._animation.dataType) {
  47257. // Float
  47258. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47259. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47260. switch (loopMode) {
  47261. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47262. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47263. return floatValue;
  47264. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47265. return offsetValue * repeatCount + floatValue;
  47266. }
  47267. break;
  47268. // Quaternion
  47269. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47270. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47271. switch (loopMode) {
  47272. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47273. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47274. return quatValue;
  47275. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47276. return quatValue.add(offsetValue.scale(repeatCount));
  47277. }
  47278. return quatValue;
  47279. // Vector3
  47280. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47281. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47282. switch (loopMode) {
  47283. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47284. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47285. return vec3Value;
  47286. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47287. return vec3Value.add(offsetValue.scale(repeatCount));
  47288. }
  47289. // Vector2
  47290. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47291. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47292. switch (loopMode) {
  47293. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47294. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47295. return vec2Value;
  47296. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47297. return vec2Value.add(offsetValue.scale(repeatCount));
  47298. }
  47299. // Size
  47300. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47301. switch (loopMode) {
  47302. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47303. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47304. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47305. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47306. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47307. }
  47308. // Color3
  47309. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47310. switch (loopMode) {
  47311. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47312. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47313. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47314. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47315. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47316. }
  47317. // Matrix
  47318. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47319. switch (loopMode) {
  47320. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47321. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47322. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47323. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47324. }
  47325. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47326. return startValue;
  47327. }
  47328. default:
  47329. break;
  47330. }
  47331. break;
  47332. }
  47333. }
  47334. return this._getKeyValue(keys[keys.length - 1].value);
  47335. };
  47336. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47337. if (blend === void 0) { blend = false; }
  47338. // Set value
  47339. var path;
  47340. var destination;
  47341. var targetPropertyPath = this._animation.targetPropertyPath;
  47342. if (targetPropertyPath.length > 1) {
  47343. var property = this._target[targetPropertyPath[0]];
  47344. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47345. property = property[targetPropertyPath[index]];
  47346. }
  47347. path = targetPropertyPath[targetPropertyPath.length - 1];
  47348. destination = property;
  47349. }
  47350. else {
  47351. path = targetPropertyPath[0];
  47352. destination = this._target;
  47353. }
  47354. // Blending
  47355. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47356. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47357. if (enableBlending && this._blendingFactor <= 1.0) {
  47358. if (!this._originalBlendValue) {
  47359. if (destination[path].clone) {
  47360. this._originalBlendValue = destination[path].clone();
  47361. }
  47362. else {
  47363. this._originalBlendValue = destination[path];
  47364. }
  47365. }
  47366. if (this._originalBlendValue.prototype) {
  47367. if (this._originalBlendValue.prototype.Lerp) {
  47368. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47369. }
  47370. else {
  47371. destination[path] = currentValue;
  47372. }
  47373. }
  47374. else if (this._originalBlendValue.m) {
  47375. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47376. }
  47377. else {
  47378. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47379. }
  47380. this._blendingFactor += blendingSpeed;
  47381. }
  47382. else {
  47383. destination[path] = currentValue;
  47384. }
  47385. if (this._target.markAsDirty) {
  47386. this._target.markAsDirty(this._animation.targetProperty);
  47387. }
  47388. };
  47389. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47390. if (this._target && this._target.animationPropertiesOverride) {
  47391. return this._target.animationPropertiesOverride.loopMode;
  47392. }
  47393. return this._animation.loopMode;
  47394. };
  47395. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47396. var keys = this._animation.getKeys();
  47397. if (frame < keys[0].frame) {
  47398. frame = keys[0].frame;
  47399. }
  47400. else if (frame > keys[keys.length - 1].frame) {
  47401. frame = keys[keys.length - 1].frame;
  47402. }
  47403. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47404. this.setValue(currentValue);
  47405. };
  47406. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47407. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47408. this._ratioOffset = this._previousRatio - newRatio;
  47409. };
  47410. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47411. if (blend === void 0) { blend = false; }
  47412. var targetPropertyPath = this._animation.targetPropertyPath;
  47413. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47414. this._stopped = true;
  47415. return false;
  47416. }
  47417. var returnValue = true;
  47418. var keys = this._animation.getKeys();
  47419. // Adding a start key at frame 0 if missing
  47420. if (keys[0].frame !== 0) {
  47421. var newKey = { frame: 0, value: keys[0].value };
  47422. keys.splice(0, 0, newKey);
  47423. }
  47424. // Check limits
  47425. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47426. from = keys[0].frame;
  47427. }
  47428. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47429. to = keys[keys.length - 1].frame;
  47430. }
  47431. //to and from cannot be the same key
  47432. if (from === to) {
  47433. if (from > keys[0].frame) {
  47434. from--;
  47435. }
  47436. else if (to < keys[keys.length - 1].frame) {
  47437. to++;
  47438. }
  47439. }
  47440. // Compute ratio
  47441. var range = to - from;
  47442. var offsetValue;
  47443. // ratio represents the frame delta between from and to
  47444. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47445. var highLimitValue = 0;
  47446. this._previousDelay = delay;
  47447. this._previousRatio = ratio;
  47448. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47449. returnValue = false;
  47450. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47451. }
  47452. else {
  47453. // Get max value if required
  47454. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47455. var keyOffset = to.toString() + from.toString();
  47456. if (!this._offsetsCache[keyOffset]) {
  47457. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47458. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47459. switch (this._animation.dataType) {
  47460. // Float
  47461. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47462. this._offsetsCache[keyOffset] = toValue - fromValue;
  47463. break;
  47464. // Quaternion
  47465. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47466. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47467. break;
  47468. // Vector3
  47469. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47470. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47471. // Vector2
  47472. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47473. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47474. // Size
  47475. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47476. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47477. // Color3
  47478. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47479. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47480. default:
  47481. break;
  47482. }
  47483. this._highLimitsCache[keyOffset] = toValue;
  47484. }
  47485. highLimitValue = this._highLimitsCache[keyOffset];
  47486. offsetValue = this._offsetsCache[keyOffset];
  47487. }
  47488. }
  47489. if (offsetValue === undefined) {
  47490. switch (this._animation.dataType) {
  47491. // Float
  47492. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47493. offsetValue = 0;
  47494. break;
  47495. // Quaternion
  47496. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47497. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47498. break;
  47499. // Vector3
  47500. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47501. offsetValue = BABYLON.Vector3.Zero();
  47502. break;
  47503. // Vector2
  47504. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47505. offsetValue = BABYLON.Vector2.Zero();
  47506. break;
  47507. // Size
  47508. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47509. offsetValue = BABYLON.Size.Zero();
  47510. break;
  47511. // Color3
  47512. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47513. offsetValue = BABYLON.Color3.Black();
  47514. }
  47515. }
  47516. // Compute value
  47517. var repeatCount = (ratio / range) >> 0;
  47518. var currentFrame = returnValue ? from + ratio % range : to;
  47519. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47520. // Set value
  47521. this.setValue(currentValue);
  47522. // Check events
  47523. var events = this._animation.getEvents();
  47524. for (var index = 0; index < events.length; index++) {
  47525. // Make sure current frame has passed event frame and that event frame is within the current range
  47526. // Also, handle both forward and reverse animations
  47527. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47528. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47529. var event = events[index];
  47530. if (!event.isDone) {
  47531. // If event should be done only once, remove it.
  47532. if (event.onlyOnce) {
  47533. events.splice(index, 1);
  47534. index--;
  47535. }
  47536. event.isDone = true;
  47537. event.action();
  47538. } // Don't do anything if the event has already be done.
  47539. }
  47540. else if (events[index].isDone && !events[index].onlyOnce) {
  47541. // reset event, the animation is looping
  47542. events[index].isDone = false;
  47543. }
  47544. }
  47545. if (!returnValue) {
  47546. this._stopped = true;
  47547. }
  47548. return returnValue;
  47549. };
  47550. return RuntimeAnimation;
  47551. }());
  47552. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47553. })(BABYLON || (BABYLON = {}));
  47554. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47555. var BABYLON;
  47556. (function (BABYLON) {
  47557. var Animatable = /** @class */ (function () {
  47558. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47559. if (fromFrame === void 0) { fromFrame = 0; }
  47560. if (toFrame === void 0) { toFrame = 100; }
  47561. if (loopAnimation === void 0) { loopAnimation = false; }
  47562. if (speedRatio === void 0) { speedRatio = 1.0; }
  47563. this.target = target;
  47564. this.fromFrame = fromFrame;
  47565. this.toFrame = toFrame;
  47566. this.loopAnimation = loopAnimation;
  47567. this.onAnimationEnd = onAnimationEnd;
  47568. this._localDelayOffset = null;
  47569. this._pausedDelay = null;
  47570. this._runtimeAnimations = new Array();
  47571. this._paused = false;
  47572. this._speedRatio = 1;
  47573. this.animationStarted = false;
  47574. if (animations) {
  47575. this.appendAnimations(target, animations);
  47576. }
  47577. this._speedRatio = speedRatio;
  47578. this._scene = scene;
  47579. scene._activeAnimatables.push(this);
  47580. }
  47581. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47582. get: function () {
  47583. return this._speedRatio;
  47584. },
  47585. set: function (value) {
  47586. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47587. var animation = this._runtimeAnimations[index];
  47588. animation._prepareForSpeedRatioChange(value);
  47589. }
  47590. this._speedRatio = value;
  47591. },
  47592. enumerable: true,
  47593. configurable: true
  47594. });
  47595. // Methods
  47596. Animatable.prototype.getAnimations = function () {
  47597. return this._runtimeAnimations;
  47598. };
  47599. Animatable.prototype.appendAnimations = function (target, animations) {
  47600. for (var index = 0; index < animations.length; index++) {
  47601. var animation = animations[index];
  47602. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47603. }
  47604. };
  47605. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47606. var runtimeAnimations = this._runtimeAnimations;
  47607. for (var index = 0; index < runtimeAnimations.length; index++) {
  47608. if (runtimeAnimations[index].animation.targetProperty === property) {
  47609. return runtimeAnimations[index].animation;
  47610. }
  47611. }
  47612. return null;
  47613. };
  47614. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47615. var runtimeAnimations = this._runtimeAnimations;
  47616. for (var index = 0; index < runtimeAnimations.length; index++) {
  47617. if (runtimeAnimations[index].animation.targetProperty === property) {
  47618. return runtimeAnimations[index];
  47619. }
  47620. }
  47621. return null;
  47622. };
  47623. Animatable.prototype.reset = function () {
  47624. var runtimeAnimations = this._runtimeAnimations;
  47625. for (var index = 0; index < runtimeAnimations.length; index++) {
  47626. runtimeAnimations[index].reset();
  47627. }
  47628. // Reset to original value
  47629. for (index = 0; index < runtimeAnimations.length; index++) {
  47630. var animation = runtimeAnimations[index];
  47631. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47632. }
  47633. this._localDelayOffset = null;
  47634. this._pausedDelay = null;
  47635. };
  47636. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47637. var runtimeAnimations = this._runtimeAnimations;
  47638. for (var index = 0; index < runtimeAnimations.length; index++) {
  47639. runtimeAnimations[index].animation.enableBlending = true;
  47640. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47641. }
  47642. };
  47643. Animatable.prototype.disableBlending = function () {
  47644. var runtimeAnimations = this._runtimeAnimations;
  47645. for (var index = 0; index < runtimeAnimations.length; index++) {
  47646. runtimeAnimations[index].animation.enableBlending = false;
  47647. }
  47648. };
  47649. Animatable.prototype.goToFrame = function (frame) {
  47650. var runtimeAnimations = this._runtimeAnimations;
  47651. if (runtimeAnimations[0]) {
  47652. var fps = runtimeAnimations[0].animation.framePerSecond;
  47653. var currentFrame = runtimeAnimations[0].currentFrame;
  47654. var adjustTime = frame - currentFrame;
  47655. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47656. if (this._localDelayOffset === null) {
  47657. this._localDelayOffset = 0;
  47658. }
  47659. this._localDelayOffset -= delay;
  47660. }
  47661. for (var index = 0; index < runtimeAnimations.length; index++) {
  47662. runtimeAnimations[index].goToFrame(frame);
  47663. }
  47664. };
  47665. Animatable.prototype.pause = function () {
  47666. if (this._paused) {
  47667. return;
  47668. }
  47669. this._paused = true;
  47670. };
  47671. Animatable.prototype.restart = function () {
  47672. this._paused = false;
  47673. };
  47674. Animatable.prototype.stop = function (animationName) {
  47675. if (animationName) {
  47676. var idx = this._scene._activeAnimatables.indexOf(this);
  47677. if (idx > -1) {
  47678. var runtimeAnimations = this._runtimeAnimations;
  47679. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47680. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47681. continue;
  47682. }
  47683. runtimeAnimations[index].dispose();
  47684. runtimeAnimations.splice(index, 1);
  47685. }
  47686. if (runtimeAnimations.length == 0) {
  47687. this._scene._activeAnimatables.splice(idx, 1);
  47688. if (this.onAnimationEnd) {
  47689. this.onAnimationEnd();
  47690. }
  47691. }
  47692. }
  47693. }
  47694. else {
  47695. var index = this._scene._activeAnimatables.indexOf(this);
  47696. if (index > -1) {
  47697. this._scene._activeAnimatables.splice(index, 1);
  47698. var runtimeAnimations = this._runtimeAnimations;
  47699. for (var index = 0; index < runtimeAnimations.length; index++) {
  47700. runtimeAnimations[index].dispose();
  47701. }
  47702. if (this.onAnimationEnd) {
  47703. this.onAnimationEnd();
  47704. }
  47705. }
  47706. }
  47707. };
  47708. Animatable.prototype._animate = function (delay) {
  47709. if (this._paused) {
  47710. this.animationStarted = false;
  47711. if (this._pausedDelay === null) {
  47712. this._pausedDelay = delay;
  47713. }
  47714. return true;
  47715. }
  47716. if (this._localDelayOffset === null) {
  47717. this._localDelayOffset = delay;
  47718. this._pausedDelay = null;
  47719. }
  47720. else if (this._pausedDelay !== null) {
  47721. this._localDelayOffset += delay - this._pausedDelay;
  47722. this._pausedDelay = null;
  47723. }
  47724. // Animating
  47725. var running = false;
  47726. var runtimeAnimations = this._runtimeAnimations;
  47727. var index;
  47728. for (index = 0; index < runtimeAnimations.length; index++) {
  47729. var animation = runtimeAnimations[index];
  47730. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47731. running = running || isRunning;
  47732. }
  47733. this.animationStarted = running;
  47734. if (!running) {
  47735. // Remove from active animatables
  47736. index = this._scene._activeAnimatables.indexOf(this);
  47737. this._scene._activeAnimatables.splice(index, 1);
  47738. // Dispose all runtime animations
  47739. for (index = 0; index < runtimeAnimations.length; index++) {
  47740. runtimeAnimations[index].dispose();
  47741. }
  47742. }
  47743. if (!running && this.onAnimationEnd) {
  47744. this.onAnimationEnd();
  47745. this.onAnimationEnd = null;
  47746. }
  47747. return running;
  47748. };
  47749. return Animatable;
  47750. }());
  47751. BABYLON.Animatable = Animatable;
  47752. })(BABYLON || (BABYLON = {}));
  47753. //# sourceMappingURL=babylon.animatable.js.map
  47754. var BABYLON;
  47755. (function (BABYLON) {
  47756. var EasingFunction = /** @class */ (function () {
  47757. function EasingFunction() {
  47758. // Properties
  47759. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47760. }
  47761. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47762. get: function () {
  47763. return EasingFunction._EASINGMODE_EASEIN;
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47769. get: function () {
  47770. return EasingFunction._EASINGMODE_EASEOUT;
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47776. get: function () {
  47777. return EasingFunction._EASINGMODE_EASEINOUT;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47783. var n = Math.min(Math.max(easingMode, 0), 2);
  47784. this._easingMode = n;
  47785. };
  47786. EasingFunction.prototype.getEasingMode = function () {
  47787. return this._easingMode;
  47788. };
  47789. EasingFunction.prototype.easeInCore = function (gradient) {
  47790. throw new Error('You must implement this method');
  47791. };
  47792. EasingFunction.prototype.ease = function (gradient) {
  47793. switch (this._easingMode) {
  47794. case EasingFunction.EASINGMODE_EASEIN:
  47795. return this.easeInCore(gradient);
  47796. case EasingFunction.EASINGMODE_EASEOUT:
  47797. return (1 - this.easeInCore(1 - gradient));
  47798. }
  47799. if (gradient >= 0.5) {
  47800. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47801. }
  47802. return (this.easeInCore(gradient * 2) * 0.5);
  47803. };
  47804. //Statics
  47805. EasingFunction._EASINGMODE_EASEIN = 0;
  47806. EasingFunction._EASINGMODE_EASEOUT = 1;
  47807. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47808. return EasingFunction;
  47809. }());
  47810. BABYLON.EasingFunction = EasingFunction;
  47811. var CircleEase = /** @class */ (function (_super) {
  47812. __extends(CircleEase, _super);
  47813. function CircleEase() {
  47814. return _super !== null && _super.apply(this, arguments) || this;
  47815. }
  47816. CircleEase.prototype.easeInCore = function (gradient) {
  47817. gradient = Math.max(0, Math.min(1, gradient));
  47818. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47819. };
  47820. return CircleEase;
  47821. }(EasingFunction));
  47822. BABYLON.CircleEase = CircleEase;
  47823. var BackEase = /** @class */ (function (_super) {
  47824. __extends(BackEase, _super);
  47825. function BackEase(amplitude) {
  47826. if (amplitude === void 0) { amplitude = 1; }
  47827. var _this = _super.call(this) || this;
  47828. _this.amplitude = amplitude;
  47829. return _this;
  47830. }
  47831. BackEase.prototype.easeInCore = function (gradient) {
  47832. var num = Math.max(0, this.amplitude);
  47833. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47834. };
  47835. return BackEase;
  47836. }(EasingFunction));
  47837. BABYLON.BackEase = BackEase;
  47838. var BounceEase = /** @class */ (function (_super) {
  47839. __extends(BounceEase, _super);
  47840. function BounceEase(bounces, bounciness) {
  47841. if (bounces === void 0) { bounces = 3; }
  47842. if (bounciness === void 0) { bounciness = 2; }
  47843. var _this = _super.call(this) || this;
  47844. _this.bounces = bounces;
  47845. _this.bounciness = bounciness;
  47846. return _this;
  47847. }
  47848. BounceEase.prototype.easeInCore = function (gradient) {
  47849. var y = Math.max(0.0, this.bounces);
  47850. var bounciness = this.bounciness;
  47851. if (bounciness <= 1.0) {
  47852. bounciness = 1.001;
  47853. }
  47854. var num9 = Math.pow(bounciness, y);
  47855. var num5 = 1.0 - bounciness;
  47856. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47857. var num15 = gradient * num4;
  47858. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47859. var num3 = Math.floor(num65);
  47860. var num13 = num3 + 1.0;
  47861. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47862. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47863. var num7 = (num8 + num12) * 0.5;
  47864. var num6 = gradient - num7;
  47865. var num2 = num7 - num8;
  47866. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47867. };
  47868. return BounceEase;
  47869. }(EasingFunction));
  47870. BABYLON.BounceEase = BounceEase;
  47871. var CubicEase = /** @class */ (function (_super) {
  47872. __extends(CubicEase, _super);
  47873. function CubicEase() {
  47874. return _super !== null && _super.apply(this, arguments) || this;
  47875. }
  47876. CubicEase.prototype.easeInCore = function (gradient) {
  47877. return (gradient * gradient * gradient);
  47878. };
  47879. return CubicEase;
  47880. }(EasingFunction));
  47881. BABYLON.CubicEase = CubicEase;
  47882. var ElasticEase = /** @class */ (function (_super) {
  47883. __extends(ElasticEase, _super);
  47884. function ElasticEase(oscillations, springiness) {
  47885. if (oscillations === void 0) { oscillations = 3; }
  47886. if (springiness === void 0) { springiness = 3; }
  47887. var _this = _super.call(this) || this;
  47888. _this.oscillations = oscillations;
  47889. _this.springiness = springiness;
  47890. return _this;
  47891. }
  47892. ElasticEase.prototype.easeInCore = function (gradient) {
  47893. var num2;
  47894. var num3 = Math.max(0.0, this.oscillations);
  47895. var num = Math.max(0.0, this.springiness);
  47896. if (num == 0) {
  47897. num2 = gradient;
  47898. }
  47899. else {
  47900. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47901. }
  47902. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47903. };
  47904. return ElasticEase;
  47905. }(EasingFunction));
  47906. BABYLON.ElasticEase = ElasticEase;
  47907. var ExponentialEase = /** @class */ (function (_super) {
  47908. __extends(ExponentialEase, _super);
  47909. function ExponentialEase(exponent) {
  47910. if (exponent === void 0) { exponent = 2; }
  47911. var _this = _super.call(this) || this;
  47912. _this.exponent = exponent;
  47913. return _this;
  47914. }
  47915. ExponentialEase.prototype.easeInCore = function (gradient) {
  47916. if (this.exponent <= 0) {
  47917. return gradient;
  47918. }
  47919. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47920. };
  47921. return ExponentialEase;
  47922. }(EasingFunction));
  47923. BABYLON.ExponentialEase = ExponentialEase;
  47924. var PowerEase = /** @class */ (function (_super) {
  47925. __extends(PowerEase, _super);
  47926. function PowerEase(power) {
  47927. if (power === void 0) { power = 2; }
  47928. var _this = _super.call(this) || this;
  47929. _this.power = power;
  47930. return _this;
  47931. }
  47932. PowerEase.prototype.easeInCore = function (gradient) {
  47933. var y = Math.max(0.0, this.power);
  47934. return Math.pow(gradient, y);
  47935. };
  47936. return PowerEase;
  47937. }(EasingFunction));
  47938. BABYLON.PowerEase = PowerEase;
  47939. var QuadraticEase = /** @class */ (function (_super) {
  47940. __extends(QuadraticEase, _super);
  47941. function QuadraticEase() {
  47942. return _super !== null && _super.apply(this, arguments) || this;
  47943. }
  47944. QuadraticEase.prototype.easeInCore = function (gradient) {
  47945. return (gradient * gradient);
  47946. };
  47947. return QuadraticEase;
  47948. }(EasingFunction));
  47949. BABYLON.QuadraticEase = QuadraticEase;
  47950. var QuarticEase = /** @class */ (function (_super) {
  47951. __extends(QuarticEase, _super);
  47952. function QuarticEase() {
  47953. return _super !== null && _super.apply(this, arguments) || this;
  47954. }
  47955. QuarticEase.prototype.easeInCore = function (gradient) {
  47956. return (gradient * gradient * gradient * gradient);
  47957. };
  47958. return QuarticEase;
  47959. }(EasingFunction));
  47960. BABYLON.QuarticEase = QuarticEase;
  47961. var QuinticEase = /** @class */ (function (_super) {
  47962. __extends(QuinticEase, _super);
  47963. function QuinticEase() {
  47964. return _super !== null && _super.apply(this, arguments) || this;
  47965. }
  47966. QuinticEase.prototype.easeInCore = function (gradient) {
  47967. return (gradient * gradient * gradient * gradient * gradient);
  47968. };
  47969. return QuinticEase;
  47970. }(EasingFunction));
  47971. BABYLON.QuinticEase = QuinticEase;
  47972. var SineEase = /** @class */ (function (_super) {
  47973. __extends(SineEase, _super);
  47974. function SineEase() {
  47975. return _super !== null && _super.apply(this, arguments) || this;
  47976. }
  47977. SineEase.prototype.easeInCore = function (gradient) {
  47978. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47979. };
  47980. return SineEase;
  47981. }(EasingFunction));
  47982. BABYLON.SineEase = SineEase;
  47983. var BezierCurveEase = /** @class */ (function (_super) {
  47984. __extends(BezierCurveEase, _super);
  47985. function BezierCurveEase(x1, y1, x2, y2) {
  47986. if (x1 === void 0) { x1 = 0; }
  47987. if (y1 === void 0) { y1 = 0; }
  47988. if (x2 === void 0) { x2 = 1; }
  47989. if (y2 === void 0) { y2 = 1; }
  47990. var _this = _super.call(this) || this;
  47991. _this.x1 = x1;
  47992. _this.y1 = y1;
  47993. _this.x2 = x2;
  47994. _this.y2 = y2;
  47995. return _this;
  47996. }
  47997. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47998. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47999. };
  48000. return BezierCurveEase;
  48001. }(EasingFunction));
  48002. BABYLON.BezierCurveEase = BezierCurveEase;
  48003. })(BABYLON || (BABYLON = {}));
  48004. //# sourceMappingURL=babylon.easing.js.map
  48005. var BABYLON;
  48006. (function (BABYLON) {
  48007. var Condition = /** @class */ (function () {
  48008. function Condition(actionManager) {
  48009. this._actionManager = actionManager;
  48010. }
  48011. Condition.prototype.isValid = function () {
  48012. return true;
  48013. };
  48014. Condition.prototype._getProperty = function (propertyPath) {
  48015. return this._actionManager._getProperty(propertyPath);
  48016. };
  48017. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48018. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48019. };
  48020. Condition.prototype.serialize = function () {
  48021. };
  48022. Condition.prototype._serialize = function (serializedCondition) {
  48023. return {
  48024. type: 2,
  48025. children: [],
  48026. name: serializedCondition.name,
  48027. properties: serializedCondition.properties
  48028. };
  48029. };
  48030. return Condition;
  48031. }());
  48032. BABYLON.Condition = Condition;
  48033. var ValueCondition = /** @class */ (function (_super) {
  48034. __extends(ValueCondition, _super);
  48035. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48036. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48037. var _this = _super.call(this, actionManager) || this;
  48038. _this.propertyPath = propertyPath;
  48039. _this.value = value;
  48040. _this.operator = operator;
  48041. _this._target = target;
  48042. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48043. _this._property = _this._getProperty(_this.propertyPath);
  48044. return _this;
  48045. }
  48046. Object.defineProperty(ValueCondition, "IsEqual", {
  48047. get: function () {
  48048. return ValueCondition._IsEqual;
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(ValueCondition, "IsDifferent", {
  48054. get: function () {
  48055. return ValueCondition._IsDifferent;
  48056. },
  48057. enumerable: true,
  48058. configurable: true
  48059. });
  48060. Object.defineProperty(ValueCondition, "IsGreater", {
  48061. get: function () {
  48062. return ValueCondition._IsGreater;
  48063. },
  48064. enumerable: true,
  48065. configurable: true
  48066. });
  48067. Object.defineProperty(ValueCondition, "IsLesser", {
  48068. get: function () {
  48069. return ValueCondition._IsLesser;
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. // Methods
  48075. ValueCondition.prototype.isValid = function () {
  48076. switch (this.operator) {
  48077. case ValueCondition.IsGreater:
  48078. return this._effectiveTarget[this._property] > this.value;
  48079. case ValueCondition.IsLesser:
  48080. return this._effectiveTarget[this._property] < this.value;
  48081. case ValueCondition.IsEqual:
  48082. case ValueCondition.IsDifferent:
  48083. var check;
  48084. if (this.value.equals) {
  48085. check = this.value.equals(this._effectiveTarget[this._property]);
  48086. }
  48087. else {
  48088. check = this.value === this._effectiveTarget[this._property];
  48089. }
  48090. return this.operator === ValueCondition.IsEqual ? check : !check;
  48091. }
  48092. return false;
  48093. };
  48094. ValueCondition.prototype.serialize = function () {
  48095. return this._serialize({
  48096. name: "ValueCondition",
  48097. properties: [
  48098. BABYLON.Action._GetTargetProperty(this._target),
  48099. { name: "propertyPath", value: this.propertyPath },
  48100. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48101. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48102. ]
  48103. });
  48104. };
  48105. ValueCondition.GetOperatorName = function (operator) {
  48106. switch (operator) {
  48107. case ValueCondition._IsEqual: return "IsEqual";
  48108. case ValueCondition._IsDifferent: return "IsDifferent";
  48109. case ValueCondition._IsGreater: return "IsGreater";
  48110. case ValueCondition._IsLesser: return "IsLesser";
  48111. default: return "";
  48112. }
  48113. };
  48114. // Statics
  48115. ValueCondition._IsEqual = 0;
  48116. ValueCondition._IsDifferent = 1;
  48117. ValueCondition._IsGreater = 2;
  48118. ValueCondition._IsLesser = 3;
  48119. return ValueCondition;
  48120. }(Condition));
  48121. BABYLON.ValueCondition = ValueCondition;
  48122. var PredicateCondition = /** @class */ (function (_super) {
  48123. __extends(PredicateCondition, _super);
  48124. function PredicateCondition(actionManager, predicate) {
  48125. var _this = _super.call(this, actionManager) || this;
  48126. _this.predicate = predicate;
  48127. return _this;
  48128. }
  48129. PredicateCondition.prototype.isValid = function () {
  48130. return this.predicate();
  48131. };
  48132. return PredicateCondition;
  48133. }(Condition));
  48134. BABYLON.PredicateCondition = PredicateCondition;
  48135. var StateCondition = /** @class */ (function (_super) {
  48136. __extends(StateCondition, _super);
  48137. function StateCondition(actionManager, target, value) {
  48138. var _this = _super.call(this, actionManager) || this;
  48139. _this.value = value;
  48140. _this._target = target;
  48141. return _this;
  48142. }
  48143. // Methods
  48144. StateCondition.prototype.isValid = function () {
  48145. return this._target.state === this.value;
  48146. };
  48147. StateCondition.prototype.serialize = function () {
  48148. return this._serialize({
  48149. name: "StateCondition",
  48150. properties: [
  48151. BABYLON.Action._GetTargetProperty(this._target),
  48152. { name: "value", value: this.value }
  48153. ]
  48154. });
  48155. };
  48156. return StateCondition;
  48157. }(Condition));
  48158. BABYLON.StateCondition = StateCondition;
  48159. })(BABYLON || (BABYLON = {}));
  48160. //# sourceMappingURL=babylon.condition.js.map
  48161. var BABYLON;
  48162. (function (BABYLON) {
  48163. var Action = /** @class */ (function () {
  48164. function Action(triggerOptions, condition) {
  48165. this.triggerOptions = triggerOptions;
  48166. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48167. if (triggerOptions.parameter) {
  48168. this.trigger = triggerOptions.trigger;
  48169. this._triggerParameter = triggerOptions.parameter;
  48170. }
  48171. else {
  48172. this.trigger = triggerOptions;
  48173. }
  48174. this._nextActiveAction = this;
  48175. this._condition = condition;
  48176. }
  48177. // Methods
  48178. Action.prototype._prepare = function () {
  48179. };
  48180. Action.prototype.getTriggerParameter = function () {
  48181. return this._triggerParameter;
  48182. };
  48183. Action.prototype._executeCurrent = function (evt) {
  48184. if (this._nextActiveAction._condition) {
  48185. var condition = this._nextActiveAction._condition;
  48186. var currentRenderId = this._actionManager.getScene().getRenderId();
  48187. // We cache the current evaluation for the current frame
  48188. if (condition._evaluationId === currentRenderId) {
  48189. if (!condition._currentResult) {
  48190. return;
  48191. }
  48192. }
  48193. else {
  48194. condition._evaluationId = currentRenderId;
  48195. if (!condition.isValid()) {
  48196. condition._currentResult = false;
  48197. return;
  48198. }
  48199. condition._currentResult = true;
  48200. }
  48201. }
  48202. this.onBeforeExecuteObservable.notifyObservers(this);
  48203. this._nextActiveAction.execute(evt);
  48204. this.skipToNextActiveAction();
  48205. };
  48206. Action.prototype.execute = function (evt) {
  48207. };
  48208. Action.prototype.skipToNextActiveAction = function () {
  48209. if (this._nextActiveAction._child) {
  48210. if (!this._nextActiveAction._child._actionManager) {
  48211. this._nextActiveAction._child._actionManager = this._actionManager;
  48212. }
  48213. this._nextActiveAction = this._nextActiveAction._child;
  48214. }
  48215. else {
  48216. this._nextActiveAction = this;
  48217. }
  48218. };
  48219. Action.prototype.then = function (action) {
  48220. this._child = action;
  48221. action._actionManager = this._actionManager;
  48222. action._prepare();
  48223. return action;
  48224. };
  48225. Action.prototype._getProperty = function (propertyPath) {
  48226. return this._actionManager._getProperty(propertyPath);
  48227. };
  48228. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48229. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48230. };
  48231. Action.prototype.serialize = function (parent) {
  48232. };
  48233. // Called by BABYLON.Action objects in serialize(...). Internal use
  48234. Action.prototype._serialize = function (serializedAction, parent) {
  48235. var serializationObject = {
  48236. type: 1,
  48237. children: [],
  48238. name: serializedAction.name,
  48239. properties: serializedAction.properties || []
  48240. };
  48241. // Serialize child
  48242. if (this._child) {
  48243. this._child.serialize(serializationObject);
  48244. }
  48245. // Check if "this" has a condition
  48246. if (this._condition) {
  48247. var serializedCondition = this._condition.serialize();
  48248. serializedCondition.children.push(serializationObject);
  48249. if (parent) {
  48250. parent.children.push(serializedCondition);
  48251. }
  48252. return serializedCondition;
  48253. }
  48254. if (parent) {
  48255. parent.children.push(serializationObject);
  48256. }
  48257. return serializationObject;
  48258. };
  48259. Action._SerializeValueAsString = function (value) {
  48260. if (typeof value === "number") {
  48261. return value.toString();
  48262. }
  48263. if (typeof value === "boolean") {
  48264. return value ? "true" : "false";
  48265. }
  48266. if (value instanceof BABYLON.Vector2) {
  48267. return value.x + ", " + value.y;
  48268. }
  48269. if (value instanceof BABYLON.Vector3) {
  48270. return value.x + ", " + value.y + ", " + value.z;
  48271. }
  48272. if (value instanceof BABYLON.Color3) {
  48273. return value.r + ", " + value.g + ", " + value.b;
  48274. }
  48275. if (value instanceof BABYLON.Color4) {
  48276. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48277. }
  48278. return value; // string
  48279. };
  48280. Action._GetTargetProperty = function (target) {
  48281. return {
  48282. name: "target",
  48283. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48284. : target instanceof BABYLON.Light ? "LightProperties"
  48285. : target instanceof BABYLON.Camera ? "CameraProperties"
  48286. : "SceneProperties",
  48287. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48288. };
  48289. };
  48290. return Action;
  48291. }());
  48292. BABYLON.Action = Action;
  48293. })(BABYLON || (BABYLON = {}));
  48294. //# sourceMappingURL=babylon.action.js.map
  48295. var BABYLON;
  48296. (function (BABYLON) {
  48297. /**
  48298. * ActionEvent is the event beint sent when an action is triggered.
  48299. */
  48300. var ActionEvent = /** @class */ (function () {
  48301. /**
  48302. * @param source The mesh or sprite that triggered the action.
  48303. * @param pointerX The X mouse cursor position at the time of the event
  48304. * @param pointerY The Y mouse cursor position at the time of the event
  48305. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48306. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48307. */
  48308. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48309. this.source = source;
  48310. this.pointerX = pointerX;
  48311. this.pointerY = pointerY;
  48312. this.meshUnderPointer = meshUnderPointer;
  48313. this.sourceEvent = sourceEvent;
  48314. this.additionalData = additionalData;
  48315. }
  48316. /**
  48317. * Helper function to auto-create an ActionEvent from a source mesh.
  48318. * @param source The source mesh that triggered the event
  48319. * @param evt {Event} The original (browser) event
  48320. */
  48321. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48322. var scene = source.getScene();
  48323. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48324. };
  48325. /**
  48326. * Helper function to auto-create an ActionEvent from a source mesh.
  48327. * @param source The source sprite that triggered the event
  48328. * @param scene Scene associated with the sprite
  48329. * @param evt {Event} The original (browser) event
  48330. */
  48331. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48332. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48333. };
  48334. /**
  48335. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48336. * @param scene the scene where the event occurred
  48337. * @param evt {Event} The original (browser) event
  48338. */
  48339. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48340. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48341. };
  48342. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48343. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48344. };
  48345. return ActionEvent;
  48346. }());
  48347. BABYLON.ActionEvent = ActionEvent;
  48348. /**
  48349. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48350. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48351. */
  48352. var ActionManager = /** @class */ (function () {
  48353. function ActionManager(scene) {
  48354. // Members
  48355. this.actions = new Array();
  48356. this.hoverCursor = '';
  48357. this._scene = scene;
  48358. scene._actionManagers.push(this);
  48359. }
  48360. Object.defineProperty(ActionManager, "NothingTrigger", {
  48361. get: function () {
  48362. return ActionManager._NothingTrigger;
  48363. },
  48364. enumerable: true,
  48365. configurable: true
  48366. });
  48367. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48368. get: function () {
  48369. return ActionManager._OnPickTrigger;
  48370. },
  48371. enumerable: true,
  48372. configurable: true
  48373. });
  48374. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48375. get: function () {
  48376. return ActionManager._OnLeftPickTrigger;
  48377. },
  48378. enumerable: true,
  48379. configurable: true
  48380. });
  48381. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48382. get: function () {
  48383. return ActionManager._OnRightPickTrigger;
  48384. },
  48385. enumerable: true,
  48386. configurable: true
  48387. });
  48388. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48389. get: function () {
  48390. return ActionManager._OnCenterPickTrigger;
  48391. },
  48392. enumerable: true,
  48393. configurable: true
  48394. });
  48395. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48396. get: function () {
  48397. return ActionManager._OnPickDownTrigger;
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48403. get: function () {
  48404. return ActionManager._OnDoublePickTrigger;
  48405. },
  48406. enumerable: true,
  48407. configurable: true
  48408. });
  48409. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48410. get: function () {
  48411. return ActionManager._OnPickUpTrigger;
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48417. /// This trigger will only be raised if you also declared a OnPickDown
  48418. get: function () {
  48419. return ActionManager._OnPickOutTrigger;
  48420. },
  48421. enumerable: true,
  48422. configurable: true
  48423. });
  48424. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48425. get: function () {
  48426. return ActionManager._OnLongPressTrigger;
  48427. },
  48428. enumerable: true,
  48429. configurable: true
  48430. });
  48431. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48432. get: function () {
  48433. return ActionManager._OnPointerOverTrigger;
  48434. },
  48435. enumerable: true,
  48436. configurable: true
  48437. });
  48438. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48439. get: function () {
  48440. return ActionManager._OnPointerOutTrigger;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48446. get: function () {
  48447. return ActionManager._OnEveryFrameTrigger;
  48448. },
  48449. enumerable: true,
  48450. configurable: true
  48451. });
  48452. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48453. get: function () {
  48454. return ActionManager._OnIntersectionEnterTrigger;
  48455. },
  48456. enumerable: true,
  48457. configurable: true
  48458. });
  48459. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48460. get: function () {
  48461. return ActionManager._OnIntersectionExitTrigger;
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48467. get: function () {
  48468. return ActionManager._OnKeyDownTrigger;
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48474. get: function () {
  48475. return ActionManager._OnKeyUpTrigger;
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. // Methods
  48481. ActionManager.prototype.dispose = function () {
  48482. var index = this._scene._actionManagers.indexOf(this);
  48483. for (var i = 0; i < this.actions.length; i++) {
  48484. var action = this.actions[i];
  48485. ActionManager.Triggers[action.trigger]--;
  48486. if (ActionManager.Triggers[action.trigger] === 0) {
  48487. delete ActionManager.Triggers[action.trigger];
  48488. }
  48489. }
  48490. if (index > -1) {
  48491. this._scene._actionManagers.splice(index, 1);
  48492. }
  48493. };
  48494. ActionManager.prototype.getScene = function () {
  48495. return this._scene;
  48496. };
  48497. /**
  48498. * Does this action manager handles actions of any of the given triggers
  48499. * @param {number[]} triggers - the triggers to be tested
  48500. * @return {boolean} whether one (or more) of the triggers is handeled
  48501. */
  48502. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48503. for (var index = 0; index < this.actions.length; index++) {
  48504. var action = this.actions[index];
  48505. if (triggers.indexOf(action.trigger) > -1) {
  48506. return true;
  48507. }
  48508. }
  48509. return false;
  48510. };
  48511. /**
  48512. * Does this action manager handles actions of a given trigger
  48513. * @param {number} trigger - the trigger to be tested
  48514. * @return {boolean} whether the trigger is handeled
  48515. */
  48516. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48517. for (var index = 0; index < this.actions.length; index++) {
  48518. var action = this.actions[index];
  48519. if (action.trigger === trigger) {
  48520. return true;
  48521. }
  48522. }
  48523. return false;
  48524. };
  48525. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48526. /**
  48527. * Does this action manager has pointer triggers
  48528. * @return {boolean} whether or not it has pointer triggers
  48529. */
  48530. get: function () {
  48531. for (var index = 0; index < this.actions.length; index++) {
  48532. var action = this.actions[index];
  48533. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48534. return true;
  48535. }
  48536. }
  48537. return false;
  48538. },
  48539. enumerable: true,
  48540. configurable: true
  48541. });
  48542. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48543. /**
  48544. * Does this action manager has pick triggers
  48545. * @return {boolean} whether or not it has pick triggers
  48546. */
  48547. get: function () {
  48548. for (var index = 0; index < this.actions.length; index++) {
  48549. var action = this.actions[index];
  48550. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48551. return true;
  48552. }
  48553. }
  48554. return false;
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(ActionManager, "HasTriggers", {
  48560. /**
  48561. * Does exist one action manager with at least one trigger
  48562. * @return {boolean} whether or not it exists one action manager with one trigger
  48563. **/
  48564. get: function () {
  48565. for (var t in ActionManager.Triggers) {
  48566. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48567. return true;
  48568. }
  48569. }
  48570. return false;
  48571. },
  48572. enumerable: true,
  48573. configurable: true
  48574. });
  48575. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48576. /**
  48577. * Does exist one action manager with at least one pick trigger
  48578. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48579. **/
  48580. get: function () {
  48581. for (var t in ActionManager.Triggers) {
  48582. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48583. var t_int = parseInt(t);
  48584. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48585. return true;
  48586. }
  48587. }
  48588. }
  48589. return false;
  48590. },
  48591. enumerable: true,
  48592. configurable: true
  48593. });
  48594. /**
  48595. * Does exist one action manager that handles actions of a given trigger
  48596. * @param {number} trigger - the trigger to be tested
  48597. * @return {boolean} whether the trigger is handeled by at least one action manager
  48598. **/
  48599. ActionManager.HasSpecificTrigger = function (trigger) {
  48600. for (var t in ActionManager.Triggers) {
  48601. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48602. var t_int = parseInt(t);
  48603. if (t_int === trigger) {
  48604. return true;
  48605. }
  48606. }
  48607. }
  48608. return false;
  48609. };
  48610. /**
  48611. * Registers an action to this action manager
  48612. * @param {BABYLON.Action} action - the action to be registered
  48613. * @return {BABYLON.Action} the action amended (prepared) after registration
  48614. */
  48615. ActionManager.prototype.registerAction = function (action) {
  48616. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48617. if (this.getScene().actionManager !== this) {
  48618. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48619. return null;
  48620. }
  48621. }
  48622. this.actions.push(action);
  48623. if (ActionManager.Triggers[action.trigger]) {
  48624. ActionManager.Triggers[action.trigger]++;
  48625. }
  48626. else {
  48627. ActionManager.Triggers[action.trigger] = 1;
  48628. }
  48629. action._actionManager = this;
  48630. action._prepare();
  48631. return action;
  48632. };
  48633. /**
  48634. * Unregisters an action to this action manager
  48635. * @param action The action to be unregistered
  48636. * @return whether the action has been unregistered
  48637. */
  48638. ActionManager.prototype.unregisterAction = function (action) {
  48639. var index = this.actions.indexOf(action);
  48640. if (index !== -1) {
  48641. this.actions.splice(index, 1);
  48642. ActionManager.Triggers[action.trigger] -= 1;
  48643. if (ActionManager.Triggers[action.trigger] === 0) {
  48644. delete ActionManager.Triggers[action.trigger];
  48645. }
  48646. delete action._actionManager;
  48647. return true;
  48648. }
  48649. return false;
  48650. };
  48651. /**
  48652. * Process a specific trigger
  48653. * @param {number} trigger - the trigger to process
  48654. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48655. */
  48656. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48657. for (var index = 0; index < this.actions.length; index++) {
  48658. var action = this.actions[index];
  48659. if (action.trigger === trigger) {
  48660. if (evt) {
  48661. if (trigger === ActionManager.OnKeyUpTrigger
  48662. || trigger === ActionManager.OnKeyDownTrigger) {
  48663. var parameter = action.getTriggerParameter();
  48664. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48665. if (!parameter.toLowerCase) {
  48666. continue;
  48667. }
  48668. var lowerCase = parameter.toLowerCase();
  48669. if (lowerCase !== evt.sourceEvent.key) {
  48670. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48671. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48672. if (actualkey !== lowerCase) {
  48673. continue;
  48674. }
  48675. }
  48676. }
  48677. }
  48678. }
  48679. action._executeCurrent(evt);
  48680. }
  48681. }
  48682. };
  48683. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48684. var properties = propertyPath.split(".");
  48685. for (var index = 0; index < properties.length - 1; index++) {
  48686. target = target[properties[index]];
  48687. }
  48688. return target;
  48689. };
  48690. ActionManager.prototype._getProperty = function (propertyPath) {
  48691. var properties = propertyPath.split(".");
  48692. return properties[properties.length - 1];
  48693. };
  48694. ActionManager.prototype.serialize = function (name) {
  48695. var root = {
  48696. children: new Array(),
  48697. name: name,
  48698. type: 3,
  48699. properties: new Array() // Empty for root but required
  48700. };
  48701. for (var i = 0; i < this.actions.length; i++) {
  48702. var triggerObject = {
  48703. type: 0,
  48704. children: new Array(),
  48705. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48706. properties: new Array()
  48707. };
  48708. var triggerOptions = this.actions[i].triggerOptions;
  48709. if (triggerOptions && typeof triggerOptions !== "number") {
  48710. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48711. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48712. }
  48713. else {
  48714. var parameter = {};
  48715. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48716. if (triggerOptions.parameter.mesh) {
  48717. parameter._meshId = triggerOptions.parameter.mesh.id;
  48718. }
  48719. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48720. }
  48721. }
  48722. // Serialize child action, recursively
  48723. this.actions[i].serialize(triggerObject);
  48724. // Add serialized trigger
  48725. root.children.push(triggerObject);
  48726. }
  48727. return root;
  48728. };
  48729. ActionManager.Parse = function (parsedActions, object, scene) {
  48730. var actionManager = new ActionManager(scene);
  48731. if (object === null)
  48732. scene.actionManager = actionManager;
  48733. else
  48734. object.actionManager = actionManager;
  48735. // instanciate a new object
  48736. var instanciate = function (name, params) {
  48737. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48738. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48739. newInstance.constructor.apply(newInstance, params);
  48740. return newInstance;
  48741. };
  48742. var parseParameter = function (name, value, target, propertyPath) {
  48743. if (propertyPath === null) {
  48744. // String, boolean or float
  48745. var floatValue = parseFloat(value);
  48746. if (value === "true" || value === "false")
  48747. return value === "true";
  48748. else
  48749. return isNaN(floatValue) ? value : floatValue;
  48750. }
  48751. var effectiveTarget = propertyPath.split(".");
  48752. var values = value.split(",");
  48753. // Get effective Target
  48754. for (var i = 0; i < effectiveTarget.length; i++) {
  48755. target = target[effectiveTarget[i]];
  48756. }
  48757. // Return appropriate value with its type
  48758. if (typeof (target) === "boolean")
  48759. return values[0] === "true";
  48760. if (typeof (target) === "string")
  48761. return values[0];
  48762. // Parameters with multiple values such as Vector3 etc.
  48763. var split = new Array();
  48764. for (var i = 0; i < values.length; i++)
  48765. split.push(parseFloat(values[i]));
  48766. if (target instanceof BABYLON.Vector3)
  48767. return BABYLON.Vector3.FromArray(split);
  48768. if (target instanceof BABYLON.Vector4)
  48769. return BABYLON.Vector4.FromArray(split);
  48770. if (target instanceof BABYLON.Color3)
  48771. return BABYLON.Color3.FromArray(split);
  48772. if (target instanceof BABYLON.Color4)
  48773. return BABYLON.Color4.FromArray(split);
  48774. return parseFloat(values[0]);
  48775. };
  48776. // traverse graph per trigger
  48777. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48778. if (combineArray === void 0) { combineArray = null; }
  48779. if (parsedAction.detached)
  48780. return;
  48781. var parameters = new Array();
  48782. var target = null;
  48783. var propertyPath = null;
  48784. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48785. // Parameters
  48786. if (parsedAction.type === 2)
  48787. parameters.push(actionManager);
  48788. else
  48789. parameters.push(trigger);
  48790. if (combine) {
  48791. var actions = new Array();
  48792. for (var j = 0; j < parsedAction.combine.length; j++) {
  48793. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48794. }
  48795. parameters.push(actions);
  48796. }
  48797. else {
  48798. for (var i = 0; i < parsedAction.properties.length; i++) {
  48799. var value = parsedAction.properties[i].value;
  48800. var name = parsedAction.properties[i].name;
  48801. var targetType = parsedAction.properties[i].targetType;
  48802. if (name === "target")
  48803. if (targetType !== null && targetType === "SceneProperties")
  48804. value = target = scene;
  48805. else
  48806. value = target = scene.getNodeByName(value);
  48807. else if (name === "parent")
  48808. value = scene.getNodeByName(value);
  48809. else if (name === "sound")
  48810. value = scene.getSoundByName(value);
  48811. else if (name !== "propertyPath") {
  48812. if (parsedAction.type === 2 && name === "operator")
  48813. value = BABYLON.ValueCondition[value];
  48814. else
  48815. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48816. }
  48817. else {
  48818. propertyPath = value;
  48819. }
  48820. parameters.push(value);
  48821. }
  48822. }
  48823. if (combineArray === null) {
  48824. parameters.push(condition);
  48825. }
  48826. else {
  48827. parameters.push(null);
  48828. }
  48829. // If interpolate value action
  48830. if (parsedAction.name === "InterpolateValueAction") {
  48831. var param = parameters[parameters.length - 2];
  48832. parameters[parameters.length - 1] = param;
  48833. parameters[parameters.length - 2] = condition;
  48834. }
  48835. // Action or condition(s) and not CombineAction
  48836. var newAction = instanciate(parsedAction.name, parameters);
  48837. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48838. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48839. if (action)
  48840. action.then(nothing);
  48841. else
  48842. actionManager.registerAction(nothing);
  48843. action = nothing;
  48844. }
  48845. if (combineArray === null) {
  48846. if (newAction instanceof BABYLON.Condition) {
  48847. condition = newAction;
  48848. newAction = action;
  48849. }
  48850. else {
  48851. condition = null;
  48852. if (action)
  48853. action.then(newAction);
  48854. else
  48855. actionManager.registerAction(newAction);
  48856. }
  48857. }
  48858. else {
  48859. combineArray.push(newAction);
  48860. }
  48861. for (var i = 0; i < parsedAction.children.length; i++)
  48862. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48863. };
  48864. // triggers
  48865. for (var i = 0; i < parsedActions.children.length; i++) {
  48866. var triggerParams;
  48867. var trigger = parsedActions.children[i];
  48868. if (trigger.properties.length > 0) {
  48869. var param = trigger.properties[0].value;
  48870. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48871. if (value._meshId) {
  48872. value.mesh = scene.getMeshByID(value._meshId);
  48873. }
  48874. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48875. }
  48876. else
  48877. triggerParams = ActionManager[trigger.name];
  48878. for (var j = 0; j < trigger.children.length; j++) {
  48879. if (!trigger.detached)
  48880. traverse(trigger.children[j], triggerParams, null, null);
  48881. }
  48882. }
  48883. };
  48884. ActionManager.GetTriggerName = function (trigger) {
  48885. switch (trigger) {
  48886. case 0: return "NothingTrigger";
  48887. case 1: return "OnPickTrigger";
  48888. case 2: return "OnLeftPickTrigger";
  48889. case 3: return "OnRightPickTrigger";
  48890. case 4: return "OnCenterPickTrigger";
  48891. case 5: return "OnPickDownTrigger";
  48892. case 6: return "OnPickUpTrigger";
  48893. case 7: return "OnLongPressTrigger";
  48894. case 8: return "OnPointerOverTrigger";
  48895. case 9: return "OnPointerOutTrigger";
  48896. case 10: return "OnEveryFrameTrigger";
  48897. case 11: return "OnIntersectionEnterTrigger";
  48898. case 12: return "OnIntersectionExitTrigger";
  48899. case 13: return "OnKeyDownTrigger";
  48900. case 14: return "OnKeyUpTrigger";
  48901. case 15: return "OnPickOutTrigger";
  48902. default: return "";
  48903. }
  48904. };
  48905. // Statics
  48906. ActionManager._NothingTrigger = 0;
  48907. ActionManager._OnPickTrigger = 1;
  48908. ActionManager._OnLeftPickTrigger = 2;
  48909. ActionManager._OnRightPickTrigger = 3;
  48910. ActionManager._OnCenterPickTrigger = 4;
  48911. ActionManager._OnPickDownTrigger = 5;
  48912. ActionManager._OnDoublePickTrigger = 6;
  48913. ActionManager._OnPickUpTrigger = 7;
  48914. ActionManager._OnLongPressTrigger = 8;
  48915. ActionManager._OnPointerOverTrigger = 9;
  48916. ActionManager._OnPointerOutTrigger = 10;
  48917. ActionManager._OnEveryFrameTrigger = 11;
  48918. ActionManager._OnIntersectionEnterTrigger = 12;
  48919. ActionManager._OnIntersectionExitTrigger = 13;
  48920. ActionManager._OnKeyDownTrigger = 14;
  48921. ActionManager._OnKeyUpTrigger = 15;
  48922. ActionManager._OnPickOutTrigger = 16;
  48923. ActionManager.Triggers = {};
  48924. return ActionManager;
  48925. }());
  48926. BABYLON.ActionManager = ActionManager;
  48927. })(BABYLON || (BABYLON = {}));
  48928. //# sourceMappingURL=babylon.actionManager.js.map
  48929. var BABYLON;
  48930. (function (BABYLON) {
  48931. var InterpolateValueAction = /** @class */ (function (_super) {
  48932. __extends(InterpolateValueAction, _super);
  48933. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48934. if (duration === void 0) { duration = 1000; }
  48935. var _this = _super.call(this, triggerOptions, condition) || this;
  48936. _this.propertyPath = propertyPath;
  48937. _this.value = value;
  48938. _this.duration = duration;
  48939. _this.stopOtherAnimations = stopOtherAnimations;
  48940. _this.onInterpolationDone = onInterpolationDone;
  48941. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48942. _this._target = _this._effectiveTarget = target;
  48943. return _this;
  48944. }
  48945. InterpolateValueAction.prototype._prepare = function () {
  48946. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48947. this._property = this._getProperty(this.propertyPath);
  48948. };
  48949. InterpolateValueAction.prototype.execute = function () {
  48950. var _this = this;
  48951. var scene = this._actionManager.getScene();
  48952. var keys = [
  48953. {
  48954. frame: 0,
  48955. value: this._effectiveTarget[this._property]
  48956. }, {
  48957. frame: 100,
  48958. value: this.value
  48959. }
  48960. ];
  48961. var dataType;
  48962. if (typeof this.value === "number") {
  48963. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48964. }
  48965. else if (this.value instanceof BABYLON.Color3) {
  48966. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48967. }
  48968. else if (this.value instanceof BABYLON.Vector3) {
  48969. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48970. }
  48971. else if (this.value instanceof BABYLON.Matrix) {
  48972. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48973. }
  48974. else if (this.value instanceof BABYLON.Quaternion) {
  48975. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48976. }
  48977. else {
  48978. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48979. return;
  48980. }
  48981. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48982. animation.setKeys(keys);
  48983. if (this.stopOtherAnimations) {
  48984. scene.stopAnimation(this._effectiveTarget);
  48985. }
  48986. var wrapper = function () {
  48987. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48988. if (_this.onInterpolationDone) {
  48989. _this.onInterpolationDone();
  48990. }
  48991. };
  48992. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48993. };
  48994. InterpolateValueAction.prototype.serialize = function (parent) {
  48995. return _super.prototype._serialize.call(this, {
  48996. name: "InterpolateValueAction",
  48997. properties: [
  48998. BABYLON.Action._GetTargetProperty(this._target),
  48999. { name: "propertyPath", value: this.propertyPath },
  49000. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49001. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49002. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49003. ]
  49004. }, parent);
  49005. };
  49006. return InterpolateValueAction;
  49007. }(BABYLON.Action));
  49008. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49009. })(BABYLON || (BABYLON = {}));
  49010. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49011. var BABYLON;
  49012. (function (BABYLON) {
  49013. var SwitchBooleanAction = /** @class */ (function (_super) {
  49014. __extends(SwitchBooleanAction, _super);
  49015. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49016. var _this = _super.call(this, triggerOptions, condition) || this;
  49017. _this.propertyPath = propertyPath;
  49018. _this._target = _this._effectiveTarget = target;
  49019. return _this;
  49020. }
  49021. SwitchBooleanAction.prototype._prepare = function () {
  49022. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49023. this._property = this._getProperty(this.propertyPath);
  49024. };
  49025. SwitchBooleanAction.prototype.execute = function () {
  49026. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49027. };
  49028. SwitchBooleanAction.prototype.serialize = function (parent) {
  49029. return _super.prototype._serialize.call(this, {
  49030. name: "SwitchBooleanAction",
  49031. properties: [
  49032. BABYLON.Action._GetTargetProperty(this._target),
  49033. { name: "propertyPath", value: this.propertyPath }
  49034. ]
  49035. }, parent);
  49036. };
  49037. return SwitchBooleanAction;
  49038. }(BABYLON.Action));
  49039. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49040. var SetStateAction = /** @class */ (function (_super) {
  49041. __extends(SetStateAction, _super);
  49042. function SetStateAction(triggerOptions, target, value, condition) {
  49043. var _this = _super.call(this, triggerOptions, condition) || this;
  49044. _this.value = value;
  49045. _this._target = target;
  49046. return _this;
  49047. }
  49048. SetStateAction.prototype.execute = function () {
  49049. this._target.state = this.value;
  49050. };
  49051. SetStateAction.prototype.serialize = function (parent) {
  49052. return _super.prototype._serialize.call(this, {
  49053. name: "SetStateAction",
  49054. properties: [
  49055. BABYLON.Action._GetTargetProperty(this._target),
  49056. { name: "value", value: this.value }
  49057. ]
  49058. }, parent);
  49059. };
  49060. return SetStateAction;
  49061. }(BABYLON.Action));
  49062. BABYLON.SetStateAction = SetStateAction;
  49063. var SetValueAction = /** @class */ (function (_super) {
  49064. __extends(SetValueAction, _super);
  49065. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49066. var _this = _super.call(this, triggerOptions, condition) || this;
  49067. _this.propertyPath = propertyPath;
  49068. _this.value = value;
  49069. _this._target = _this._effectiveTarget = target;
  49070. return _this;
  49071. }
  49072. SetValueAction.prototype._prepare = function () {
  49073. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49074. this._property = this._getProperty(this.propertyPath);
  49075. };
  49076. SetValueAction.prototype.execute = function () {
  49077. this._effectiveTarget[this._property] = this.value;
  49078. if (this._target.markAsDirty) {
  49079. this._target.markAsDirty(this._property);
  49080. }
  49081. };
  49082. SetValueAction.prototype.serialize = function (parent) {
  49083. return _super.prototype._serialize.call(this, {
  49084. name: "SetValueAction",
  49085. properties: [
  49086. BABYLON.Action._GetTargetProperty(this._target),
  49087. { name: "propertyPath", value: this.propertyPath },
  49088. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49089. ]
  49090. }, parent);
  49091. };
  49092. return SetValueAction;
  49093. }(BABYLON.Action));
  49094. BABYLON.SetValueAction = SetValueAction;
  49095. var IncrementValueAction = /** @class */ (function (_super) {
  49096. __extends(IncrementValueAction, _super);
  49097. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49098. var _this = _super.call(this, triggerOptions, condition) || this;
  49099. _this.propertyPath = propertyPath;
  49100. _this.value = value;
  49101. _this._target = _this._effectiveTarget = target;
  49102. return _this;
  49103. }
  49104. IncrementValueAction.prototype._prepare = function () {
  49105. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49106. this._property = this._getProperty(this.propertyPath);
  49107. if (typeof this._effectiveTarget[this._property] !== "number") {
  49108. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49109. }
  49110. };
  49111. IncrementValueAction.prototype.execute = function () {
  49112. this._effectiveTarget[this._property] += this.value;
  49113. if (this._target.markAsDirty) {
  49114. this._target.markAsDirty(this._property);
  49115. }
  49116. };
  49117. IncrementValueAction.prototype.serialize = function (parent) {
  49118. return _super.prototype._serialize.call(this, {
  49119. name: "IncrementValueAction",
  49120. properties: [
  49121. BABYLON.Action._GetTargetProperty(this._target),
  49122. { name: "propertyPath", value: this.propertyPath },
  49123. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49124. ]
  49125. }, parent);
  49126. };
  49127. return IncrementValueAction;
  49128. }(BABYLON.Action));
  49129. BABYLON.IncrementValueAction = IncrementValueAction;
  49130. var PlayAnimationAction = /** @class */ (function (_super) {
  49131. __extends(PlayAnimationAction, _super);
  49132. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49133. var _this = _super.call(this, triggerOptions, condition) || this;
  49134. _this.from = from;
  49135. _this.to = to;
  49136. _this.loop = loop;
  49137. _this._target = target;
  49138. return _this;
  49139. }
  49140. PlayAnimationAction.prototype._prepare = function () {
  49141. };
  49142. PlayAnimationAction.prototype.execute = function () {
  49143. var scene = this._actionManager.getScene();
  49144. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49145. };
  49146. PlayAnimationAction.prototype.serialize = function (parent) {
  49147. return _super.prototype._serialize.call(this, {
  49148. name: "PlayAnimationAction",
  49149. properties: [
  49150. BABYLON.Action._GetTargetProperty(this._target),
  49151. { name: "from", value: String(this.from) },
  49152. { name: "to", value: String(this.to) },
  49153. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49154. ]
  49155. }, parent);
  49156. };
  49157. return PlayAnimationAction;
  49158. }(BABYLON.Action));
  49159. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49160. var StopAnimationAction = /** @class */ (function (_super) {
  49161. __extends(StopAnimationAction, _super);
  49162. function StopAnimationAction(triggerOptions, target, condition) {
  49163. var _this = _super.call(this, triggerOptions, condition) || this;
  49164. _this._target = target;
  49165. return _this;
  49166. }
  49167. StopAnimationAction.prototype._prepare = function () {
  49168. };
  49169. StopAnimationAction.prototype.execute = function () {
  49170. var scene = this._actionManager.getScene();
  49171. scene.stopAnimation(this._target);
  49172. };
  49173. StopAnimationAction.prototype.serialize = function (parent) {
  49174. return _super.prototype._serialize.call(this, {
  49175. name: "StopAnimationAction",
  49176. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49177. }, parent);
  49178. };
  49179. return StopAnimationAction;
  49180. }(BABYLON.Action));
  49181. BABYLON.StopAnimationAction = StopAnimationAction;
  49182. var DoNothingAction = /** @class */ (function (_super) {
  49183. __extends(DoNothingAction, _super);
  49184. function DoNothingAction(triggerOptions, condition) {
  49185. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49186. return _super.call(this, triggerOptions, condition) || this;
  49187. }
  49188. DoNothingAction.prototype.execute = function () {
  49189. };
  49190. DoNothingAction.prototype.serialize = function (parent) {
  49191. return _super.prototype._serialize.call(this, {
  49192. name: "DoNothingAction",
  49193. properties: []
  49194. }, parent);
  49195. };
  49196. return DoNothingAction;
  49197. }(BABYLON.Action));
  49198. BABYLON.DoNothingAction = DoNothingAction;
  49199. var CombineAction = /** @class */ (function (_super) {
  49200. __extends(CombineAction, _super);
  49201. function CombineAction(triggerOptions, children, condition) {
  49202. var _this = _super.call(this, triggerOptions, condition) || this;
  49203. _this.children = children;
  49204. return _this;
  49205. }
  49206. CombineAction.prototype._prepare = function () {
  49207. for (var index = 0; index < this.children.length; index++) {
  49208. this.children[index]._actionManager = this._actionManager;
  49209. this.children[index]._prepare();
  49210. }
  49211. };
  49212. CombineAction.prototype.execute = function (evt) {
  49213. for (var index = 0; index < this.children.length; index++) {
  49214. this.children[index].execute(evt);
  49215. }
  49216. };
  49217. CombineAction.prototype.serialize = function (parent) {
  49218. var serializationObject = _super.prototype._serialize.call(this, {
  49219. name: "CombineAction",
  49220. properties: [],
  49221. combine: []
  49222. }, parent);
  49223. for (var i = 0; i < this.children.length; i++) {
  49224. serializationObject.combine.push(this.children[i].serialize(null));
  49225. }
  49226. return serializationObject;
  49227. };
  49228. return CombineAction;
  49229. }(BABYLON.Action));
  49230. BABYLON.CombineAction = CombineAction;
  49231. var ExecuteCodeAction = /** @class */ (function (_super) {
  49232. __extends(ExecuteCodeAction, _super);
  49233. function ExecuteCodeAction(triggerOptions, func, condition) {
  49234. var _this = _super.call(this, triggerOptions, condition) || this;
  49235. _this.func = func;
  49236. return _this;
  49237. }
  49238. ExecuteCodeAction.prototype.execute = function (evt) {
  49239. this.func(evt);
  49240. };
  49241. return ExecuteCodeAction;
  49242. }(BABYLON.Action));
  49243. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49244. var SetParentAction = /** @class */ (function (_super) {
  49245. __extends(SetParentAction, _super);
  49246. function SetParentAction(triggerOptions, target, parent, condition) {
  49247. var _this = _super.call(this, triggerOptions, condition) || this;
  49248. _this._target = target;
  49249. _this._parent = parent;
  49250. return _this;
  49251. }
  49252. SetParentAction.prototype._prepare = function () {
  49253. };
  49254. SetParentAction.prototype.execute = function () {
  49255. if (this._target.parent === this._parent) {
  49256. return;
  49257. }
  49258. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49259. invertParentWorldMatrix.invert();
  49260. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49261. this._target.parent = this._parent;
  49262. };
  49263. SetParentAction.prototype.serialize = function (parent) {
  49264. return _super.prototype._serialize.call(this, {
  49265. name: "SetParentAction",
  49266. properties: [
  49267. BABYLON.Action._GetTargetProperty(this._target),
  49268. BABYLON.Action._GetTargetProperty(this._parent),
  49269. ]
  49270. }, parent);
  49271. };
  49272. return SetParentAction;
  49273. }(BABYLON.Action));
  49274. BABYLON.SetParentAction = SetParentAction;
  49275. var PlaySoundAction = /** @class */ (function (_super) {
  49276. __extends(PlaySoundAction, _super);
  49277. function PlaySoundAction(triggerOptions, sound, condition) {
  49278. var _this = _super.call(this, triggerOptions, condition) || this;
  49279. _this._sound = sound;
  49280. return _this;
  49281. }
  49282. PlaySoundAction.prototype._prepare = function () {
  49283. };
  49284. PlaySoundAction.prototype.execute = function () {
  49285. if (this._sound !== undefined)
  49286. this._sound.play();
  49287. };
  49288. PlaySoundAction.prototype.serialize = function (parent) {
  49289. return _super.prototype._serialize.call(this, {
  49290. name: "PlaySoundAction",
  49291. properties: [{ name: "sound", value: this._sound.name }]
  49292. }, parent);
  49293. };
  49294. return PlaySoundAction;
  49295. }(BABYLON.Action));
  49296. BABYLON.PlaySoundAction = PlaySoundAction;
  49297. var StopSoundAction = /** @class */ (function (_super) {
  49298. __extends(StopSoundAction, _super);
  49299. function StopSoundAction(triggerOptions, sound, condition) {
  49300. var _this = _super.call(this, triggerOptions, condition) || this;
  49301. _this._sound = sound;
  49302. return _this;
  49303. }
  49304. StopSoundAction.prototype._prepare = function () {
  49305. };
  49306. StopSoundAction.prototype.execute = function () {
  49307. if (this._sound !== undefined)
  49308. this._sound.stop();
  49309. };
  49310. StopSoundAction.prototype.serialize = function (parent) {
  49311. return _super.prototype._serialize.call(this, {
  49312. name: "StopSoundAction",
  49313. properties: [{ name: "sound", value: this._sound.name }]
  49314. }, parent);
  49315. };
  49316. return StopSoundAction;
  49317. }(BABYLON.Action));
  49318. BABYLON.StopSoundAction = StopSoundAction;
  49319. })(BABYLON || (BABYLON = {}));
  49320. //# sourceMappingURL=babylon.directActions.js.map
  49321. var BABYLON;
  49322. (function (BABYLON) {
  49323. var SpriteManager = /** @class */ (function () {
  49324. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49325. if (epsilon === void 0) { epsilon = 0.01; }
  49326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49327. this.name = name;
  49328. this.sprites = new Array();
  49329. this.renderingGroupId = 0;
  49330. this.layerMask = 0x0FFFFFFF;
  49331. this.fogEnabled = true;
  49332. this.isPickable = false;
  49333. /**
  49334. * An event triggered when the manager is disposed.
  49335. * @type {BABYLON.Observable}
  49336. */
  49337. this.onDisposeObservable = new BABYLON.Observable();
  49338. this._vertexBuffers = {};
  49339. this._capacity = capacity;
  49340. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49341. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49342. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49343. if (cellSize.width && cellSize.height) {
  49344. this.cellWidth = cellSize.width;
  49345. this.cellHeight = cellSize.height;
  49346. }
  49347. else if (cellSize !== undefined) {
  49348. this.cellWidth = cellSize;
  49349. this.cellHeight = cellSize;
  49350. }
  49351. else {
  49352. return;
  49353. }
  49354. this._epsilon = epsilon;
  49355. this._scene = scene;
  49356. this._scene.spriteManagers.push(this);
  49357. var indices = [];
  49358. var index = 0;
  49359. for (var count = 0; count < capacity; count++) {
  49360. indices.push(index);
  49361. indices.push(index + 1);
  49362. indices.push(index + 2);
  49363. indices.push(index);
  49364. indices.push(index + 2);
  49365. indices.push(index + 3);
  49366. index += 4;
  49367. }
  49368. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49369. // VBO
  49370. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49371. this._vertexData = new Float32Array(capacity * 16 * 4);
  49372. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49373. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49374. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49375. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49376. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49377. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49378. this._vertexBuffers["options"] = options;
  49379. this._vertexBuffers["cellInfo"] = cellInfo;
  49380. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49381. // Effects
  49382. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49383. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49384. }
  49385. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49386. set: function (callback) {
  49387. if (this._onDisposeObserver) {
  49388. this.onDisposeObservable.remove(this._onDisposeObserver);
  49389. }
  49390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49391. },
  49392. enumerable: true,
  49393. configurable: true
  49394. });
  49395. Object.defineProperty(SpriteManager.prototype, "texture", {
  49396. get: function () {
  49397. return this._spriteTexture;
  49398. },
  49399. set: function (value) {
  49400. this._spriteTexture = value;
  49401. },
  49402. enumerable: true,
  49403. configurable: true
  49404. });
  49405. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49406. var arrayOffset = index * 16;
  49407. if (offsetX === 0)
  49408. offsetX = this._epsilon;
  49409. else if (offsetX === 1)
  49410. offsetX = 1 - this._epsilon;
  49411. if (offsetY === 0)
  49412. offsetY = this._epsilon;
  49413. else if (offsetY === 1)
  49414. offsetY = 1 - this._epsilon;
  49415. this._vertexData[arrayOffset] = sprite.position.x;
  49416. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49417. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49418. this._vertexData[arrayOffset + 3] = sprite.angle;
  49419. this._vertexData[arrayOffset + 4] = sprite.width;
  49420. this._vertexData[arrayOffset + 5] = sprite.height;
  49421. this._vertexData[arrayOffset + 6] = offsetX;
  49422. this._vertexData[arrayOffset + 7] = offsetY;
  49423. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49424. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49425. var offset = (sprite.cellIndex / rowSize) >> 0;
  49426. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49427. this._vertexData[arrayOffset + 11] = offset;
  49428. // Color
  49429. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49430. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49431. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49432. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49433. };
  49434. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49435. var count = Math.min(this._capacity, this.sprites.length);
  49436. var min = BABYLON.Vector3.Zero();
  49437. var max = BABYLON.Vector3.Zero();
  49438. var distance = Number.MAX_VALUE;
  49439. var currentSprite = null;
  49440. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49441. var cameraView = camera.getViewMatrix();
  49442. for (var index = 0; index < count; index++) {
  49443. var sprite = this.sprites[index];
  49444. if (!sprite) {
  49445. continue;
  49446. }
  49447. if (predicate) {
  49448. if (!predicate(sprite)) {
  49449. continue;
  49450. }
  49451. }
  49452. else if (!sprite.isPickable) {
  49453. continue;
  49454. }
  49455. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49456. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49457. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49458. if (ray.intersectsBoxMinMax(min, max)) {
  49459. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49460. if (distance > currentDistance) {
  49461. distance = currentDistance;
  49462. currentSprite = sprite;
  49463. if (fastCheck) {
  49464. break;
  49465. }
  49466. }
  49467. }
  49468. }
  49469. if (currentSprite) {
  49470. var result = new BABYLON.PickingInfo();
  49471. result.hit = true;
  49472. result.pickedSprite = currentSprite;
  49473. result.distance = distance;
  49474. return result;
  49475. }
  49476. return null;
  49477. };
  49478. SpriteManager.prototype.render = function () {
  49479. // Check
  49480. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49481. return;
  49482. var engine = this._scene.getEngine();
  49483. var baseSize = this._spriteTexture.getBaseSize();
  49484. // Sprites
  49485. var deltaTime = engine.getDeltaTime();
  49486. var max = Math.min(this._capacity, this.sprites.length);
  49487. var rowSize = baseSize.width / this.cellWidth;
  49488. var offset = 0;
  49489. for (var index = 0; index < max; index++) {
  49490. var sprite = this.sprites[index];
  49491. if (!sprite) {
  49492. continue;
  49493. }
  49494. sprite._animate(deltaTime);
  49495. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49496. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49497. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49498. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49499. }
  49500. this._buffer.update(this._vertexData);
  49501. // Render
  49502. var effect = this._effectBase;
  49503. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49504. effect = this._effectFog;
  49505. }
  49506. engine.enableEffect(effect);
  49507. var viewMatrix = this._scene.getViewMatrix();
  49508. effect.setTexture("diffuseSampler", this._spriteTexture);
  49509. effect.setMatrix("view", viewMatrix);
  49510. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49511. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49512. // Fog
  49513. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49514. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49515. effect.setColor3("vFogColor", this._scene.fogColor);
  49516. }
  49517. // VBOs
  49518. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49519. // Draw order
  49520. engine.setDepthFunctionToLessOrEqual();
  49521. effect.setBool("alphaTest", true);
  49522. engine.setColorWrite(false);
  49523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49524. engine.setColorWrite(true);
  49525. effect.setBool("alphaTest", false);
  49526. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49527. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49529. };
  49530. SpriteManager.prototype.dispose = function () {
  49531. if (this._buffer) {
  49532. this._buffer.dispose();
  49533. this._buffer = null;
  49534. }
  49535. if (this._indexBuffer) {
  49536. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49537. this._indexBuffer = null;
  49538. }
  49539. if (this._spriteTexture) {
  49540. this._spriteTexture.dispose();
  49541. this._spriteTexture = null;
  49542. }
  49543. // Remove from scene
  49544. var index = this._scene.spriteManagers.indexOf(this);
  49545. this._scene.spriteManagers.splice(index, 1);
  49546. // Callback
  49547. this.onDisposeObservable.notifyObservers(this);
  49548. this.onDisposeObservable.clear();
  49549. };
  49550. return SpriteManager;
  49551. }());
  49552. BABYLON.SpriteManager = SpriteManager;
  49553. })(BABYLON || (BABYLON = {}));
  49554. //# sourceMappingURL=babylon.spriteManager.js.map
  49555. var BABYLON;
  49556. (function (BABYLON) {
  49557. var Sprite = /** @class */ (function () {
  49558. function Sprite(name, manager) {
  49559. this.name = name;
  49560. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49561. this.width = 1.0;
  49562. this.height = 1.0;
  49563. this.angle = 0;
  49564. this.cellIndex = 0;
  49565. this.invertU = 0;
  49566. this.invertV = 0;
  49567. this.animations = new Array();
  49568. this.isPickable = false;
  49569. this._animationStarted = false;
  49570. this._loopAnimation = false;
  49571. this._fromIndex = 0;
  49572. this._toIndex = 0;
  49573. this._delay = 0;
  49574. this._direction = 1;
  49575. this._time = 0;
  49576. this._manager = manager;
  49577. this._manager.sprites.push(this);
  49578. this.position = BABYLON.Vector3.Zero();
  49579. }
  49580. Object.defineProperty(Sprite.prototype, "size", {
  49581. get: function () {
  49582. return this.width;
  49583. },
  49584. set: function (value) {
  49585. this.width = value;
  49586. this.height = value;
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49592. this._fromIndex = from;
  49593. this._toIndex = to;
  49594. this._loopAnimation = loop;
  49595. this._delay = delay;
  49596. this._animationStarted = true;
  49597. this._direction = from < to ? 1 : -1;
  49598. this.cellIndex = from;
  49599. this._time = 0;
  49600. this._onAnimationEnd = onAnimationEnd;
  49601. };
  49602. Sprite.prototype.stopAnimation = function () {
  49603. this._animationStarted = false;
  49604. };
  49605. Sprite.prototype._animate = function (deltaTime) {
  49606. if (!this._animationStarted)
  49607. return;
  49608. this._time += deltaTime;
  49609. if (this._time > this._delay) {
  49610. this._time = this._time % this._delay;
  49611. this.cellIndex += this._direction;
  49612. if (this.cellIndex > this._toIndex) {
  49613. if (this._loopAnimation) {
  49614. this.cellIndex = this._fromIndex;
  49615. }
  49616. else {
  49617. this.cellIndex = this._toIndex;
  49618. this._animationStarted = false;
  49619. if (this._onAnimationEnd) {
  49620. this._onAnimationEnd();
  49621. }
  49622. if (this.disposeWhenFinishedAnimating) {
  49623. this.dispose();
  49624. }
  49625. }
  49626. }
  49627. }
  49628. };
  49629. Sprite.prototype.dispose = function () {
  49630. for (var i = 0; i < this._manager.sprites.length; i++) {
  49631. if (this._manager.sprites[i] == this) {
  49632. this._manager.sprites.splice(i, 1);
  49633. }
  49634. }
  49635. };
  49636. return Sprite;
  49637. }());
  49638. BABYLON.Sprite = Sprite;
  49639. })(BABYLON || (BABYLON = {}));
  49640. //# sourceMappingURL=babylon.sprite.js.map
  49641. var BABYLON;
  49642. (function (BABYLON) {
  49643. var IntersectionInfo = /** @class */ (function () {
  49644. function IntersectionInfo(bu, bv, distance) {
  49645. this.bu = bu;
  49646. this.bv = bv;
  49647. this.distance = distance;
  49648. this.faceId = 0;
  49649. this.subMeshId = 0;
  49650. }
  49651. return IntersectionInfo;
  49652. }());
  49653. BABYLON.IntersectionInfo = IntersectionInfo;
  49654. var PickingInfo = /** @class */ (function () {
  49655. function PickingInfo() {
  49656. this.hit = false;
  49657. this.distance = 0;
  49658. this.pickedPoint = null;
  49659. this.pickedMesh = null;
  49660. this.bu = 0;
  49661. this.bv = 0;
  49662. this.faceId = -1;
  49663. this.subMeshId = 0;
  49664. this.pickedSprite = null;
  49665. }
  49666. // Methods
  49667. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49668. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49669. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49670. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49671. return null;
  49672. }
  49673. var indices = this.pickedMesh.getIndices();
  49674. if (!indices) {
  49675. return null;
  49676. }
  49677. var result;
  49678. if (useVerticesNormals) {
  49679. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49680. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49681. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49682. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49683. normal0 = normal0.scale(this.bu);
  49684. normal1 = normal1.scale(this.bv);
  49685. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49686. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49687. }
  49688. else {
  49689. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49690. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49691. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49692. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49693. var p1p2 = vertex1.subtract(vertex2);
  49694. var p3p2 = vertex3.subtract(vertex2);
  49695. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49696. }
  49697. if (useWorldCoordinates) {
  49698. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49699. }
  49700. return BABYLON.Vector3.Normalize(result);
  49701. };
  49702. PickingInfo.prototype.getTextureCoordinates = function () {
  49703. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49704. return null;
  49705. }
  49706. var indices = this.pickedMesh.getIndices();
  49707. if (!indices) {
  49708. return null;
  49709. }
  49710. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49711. if (!uvs) {
  49712. return null;
  49713. }
  49714. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49715. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49716. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49717. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49718. uv1 = uv1.scale(this.bu);
  49719. uv2 = uv2.scale(this.bv);
  49720. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49721. };
  49722. return PickingInfo;
  49723. }());
  49724. BABYLON.PickingInfo = PickingInfo;
  49725. })(BABYLON || (BABYLON = {}));
  49726. //# sourceMappingURL=babylon.pickingInfo.js.map
  49727. var BABYLON;
  49728. (function (BABYLON) {
  49729. var Ray = /** @class */ (function () {
  49730. function Ray(origin, direction, length) {
  49731. if (length === void 0) { length = Number.MAX_VALUE; }
  49732. this.origin = origin;
  49733. this.direction = direction;
  49734. this.length = length;
  49735. }
  49736. // Methods
  49737. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49738. var d = 0.0;
  49739. var maxValue = Number.MAX_VALUE;
  49740. var inv;
  49741. var min;
  49742. var max;
  49743. var temp;
  49744. if (Math.abs(this.direction.x) < 0.0000001) {
  49745. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49746. return false;
  49747. }
  49748. }
  49749. else {
  49750. inv = 1.0 / this.direction.x;
  49751. min = (minimum.x - this.origin.x) * inv;
  49752. max = (maximum.x - this.origin.x) * inv;
  49753. if (max === -Infinity) {
  49754. max = Infinity;
  49755. }
  49756. if (min > max) {
  49757. temp = min;
  49758. min = max;
  49759. max = temp;
  49760. }
  49761. d = Math.max(min, d);
  49762. maxValue = Math.min(max, maxValue);
  49763. if (d > maxValue) {
  49764. return false;
  49765. }
  49766. }
  49767. if (Math.abs(this.direction.y) < 0.0000001) {
  49768. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49769. return false;
  49770. }
  49771. }
  49772. else {
  49773. inv = 1.0 / this.direction.y;
  49774. min = (minimum.y - this.origin.y) * inv;
  49775. max = (maximum.y - this.origin.y) * inv;
  49776. if (max === -Infinity) {
  49777. max = Infinity;
  49778. }
  49779. if (min > max) {
  49780. temp = min;
  49781. min = max;
  49782. max = temp;
  49783. }
  49784. d = Math.max(min, d);
  49785. maxValue = Math.min(max, maxValue);
  49786. if (d > maxValue) {
  49787. return false;
  49788. }
  49789. }
  49790. if (Math.abs(this.direction.z) < 0.0000001) {
  49791. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49792. return false;
  49793. }
  49794. }
  49795. else {
  49796. inv = 1.0 / this.direction.z;
  49797. min = (minimum.z - this.origin.z) * inv;
  49798. max = (maximum.z - this.origin.z) * inv;
  49799. if (max === -Infinity) {
  49800. max = Infinity;
  49801. }
  49802. if (min > max) {
  49803. temp = min;
  49804. min = max;
  49805. max = temp;
  49806. }
  49807. d = Math.max(min, d);
  49808. maxValue = Math.min(max, maxValue);
  49809. if (d > maxValue) {
  49810. return false;
  49811. }
  49812. }
  49813. return true;
  49814. };
  49815. Ray.prototype.intersectsBox = function (box) {
  49816. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49817. };
  49818. Ray.prototype.intersectsSphere = function (sphere) {
  49819. var x = sphere.center.x - this.origin.x;
  49820. var y = sphere.center.y - this.origin.y;
  49821. var z = sphere.center.z - this.origin.z;
  49822. var pyth = (x * x) + (y * y) + (z * z);
  49823. var rr = sphere.radius * sphere.radius;
  49824. if (pyth <= rr) {
  49825. return true;
  49826. }
  49827. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49828. if (dot < 0.0) {
  49829. return false;
  49830. }
  49831. var temp = pyth - (dot * dot);
  49832. return temp <= rr;
  49833. };
  49834. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49835. if (!this._edge1) {
  49836. this._edge1 = BABYLON.Vector3.Zero();
  49837. this._edge2 = BABYLON.Vector3.Zero();
  49838. this._pvec = BABYLON.Vector3.Zero();
  49839. this._tvec = BABYLON.Vector3.Zero();
  49840. this._qvec = BABYLON.Vector3.Zero();
  49841. }
  49842. vertex1.subtractToRef(vertex0, this._edge1);
  49843. vertex2.subtractToRef(vertex0, this._edge2);
  49844. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49845. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49846. if (det === 0) {
  49847. return null;
  49848. }
  49849. var invdet = 1 / det;
  49850. this.origin.subtractToRef(vertex0, this._tvec);
  49851. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49852. if (bu < 0 || bu > 1.0) {
  49853. return null;
  49854. }
  49855. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49856. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49857. if (bv < 0 || bu + bv > 1.0) {
  49858. return null;
  49859. }
  49860. //check if the distance is longer than the predefined length.
  49861. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49862. if (distance > this.length) {
  49863. return null;
  49864. }
  49865. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49866. };
  49867. Ray.prototype.intersectsPlane = function (plane) {
  49868. var distance;
  49869. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49870. if (Math.abs(result1) < 9.99999997475243E-07) {
  49871. return null;
  49872. }
  49873. else {
  49874. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49875. distance = (-plane.d - result2) / result1;
  49876. if (distance < 0.0) {
  49877. if (distance < -9.99999997475243E-07) {
  49878. return null;
  49879. }
  49880. else {
  49881. return 0;
  49882. }
  49883. }
  49884. return distance;
  49885. }
  49886. };
  49887. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49888. var tm = BABYLON.Tmp.Matrix[0];
  49889. mesh.getWorldMatrix().invertToRef(tm);
  49890. if (this._tmpRay) {
  49891. Ray.TransformToRef(this, tm, this._tmpRay);
  49892. }
  49893. else {
  49894. this._tmpRay = Ray.Transform(this, tm);
  49895. }
  49896. return mesh.intersects(this._tmpRay, fastCheck);
  49897. };
  49898. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49899. if (results) {
  49900. results.length = 0;
  49901. }
  49902. else {
  49903. results = [];
  49904. }
  49905. for (var i = 0; i < meshes.length; i++) {
  49906. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49907. if (pickInfo.hit) {
  49908. results.push(pickInfo);
  49909. }
  49910. }
  49911. results.sort(this._comparePickingInfo);
  49912. return results;
  49913. };
  49914. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49915. if (pickingInfoA.distance < pickingInfoB.distance) {
  49916. return -1;
  49917. }
  49918. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49919. return 1;
  49920. }
  49921. else {
  49922. return 0;
  49923. }
  49924. };
  49925. /**
  49926. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49927. * @param sega the first point of the segment to test the intersection against
  49928. * @param segb the second point of the segment to test the intersection against
  49929. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49930. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49931. */
  49932. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49933. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49934. var u = segb.subtract(sega);
  49935. var v = rsegb.subtract(this.origin);
  49936. var w = sega.subtract(this.origin);
  49937. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49938. var b = BABYLON.Vector3.Dot(u, v);
  49939. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49940. var d = BABYLON.Vector3.Dot(u, w);
  49941. var e = BABYLON.Vector3.Dot(v, w);
  49942. var D = a * c - b * b; // always >= 0
  49943. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49944. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49945. // compute the line parameters of the two closest points
  49946. if (D < Ray.smallnum) {
  49947. sN = 0.0; // force using point P0 on segment S1
  49948. sD = 1.0; // to prevent possible division by 0.0 later
  49949. tN = e;
  49950. tD = c;
  49951. }
  49952. else {
  49953. sN = (b * e - c * d);
  49954. tN = (a * e - b * d);
  49955. if (sN < 0.0) {
  49956. sN = 0.0;
  49957. tN = e;
  49958. tD = c;
  49959. }
  49960. else if (sN > sD) {
  49961. sN = sD;
  49962. tN = e + b;
  49963. tD = c;
  49964. }
  49965. }
  49966. if (tN < 0.0) {
  49967. tN = 0.0;
  49968. // recompute sc for this edge
  49969. if (-d < 0.0) {
  49970. sN = 0.0;
  49971. }
  49972. else if (-d > a)
  49973. sN = sD;
  49974. else {
  49975. sN = -d;
  49976. sD = a;
  49977. }
  49978. }
  49979. else if (tN > tD) {
  49980. tN = tD;
  49981. // recompute sc for this edge
  49982. if ((-d + b) < 0.0) {
  49983. sN = 0;
  49984. }
  49985. else if ((-d + b) > a) {
  49986. sN = sD;
  49987. }
  49988. else {
  49989. sN = (-d + b);
  49990. sD = a;
  49991. }
  49992. }
  49993. // finally do the division to get sc and tc
  49994. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49995. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49996. // get the difference of the two closest points
  49997. var qtc = v.multiplyByFloats(tc, tc, tc);
  49998. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49999. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50000. if (isIntersected) {
  50001. return qtc.length();
  50002. }
  50003. return -1;
  50004. };
  50005. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50006. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50007. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50008. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50009. this.direction.normalize();
  50010. return this;
  50011. };
  50012. // Statics
  50013. Ray.Zero = function () {
  50014. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50015. };
  50016. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50017. var result = Ray.Zero();
  50018. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50019. };
  50020. /**
  50021. * 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
  50022. * transformed to the given world matrix.
  50023. * @param origin The origin point
  50024. * @param end The end point
  50025. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50026. */
  50027. Ray.CreateNewFromTo = function (origin, end, world) {
  50028. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50029. var direction = end.subtract(origin);
  50030. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50031. direction.normalize();
  50032. return Ray.Transform(new Ray(origin, direction, length), world);
  50033. };
  50034. Ray.Transform = function (ray, matrix) {
  50035. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50036. Ray.TransformToRef(ray, matrix, result);
  50037. return result;
  50038. };
  50039. Ray.TransformToRef = function (ray, matrix, result) {
  50040. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50041. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50042. result.length = ray.length;
  50043. var dir = result.direction;
  50044. var len = dir.length();
  50045. if (!(len === 0 || len === 1)) {
  50046. var num = 1.0 / len;
  50047. dir.x *= num;
  50048. dir.y *= num;
  50049. dir.z *= num;
  50050. result.length *= len;
  50051. }
  50052. };
  50053. Ray.smallnum = 0.00000001;
  50054. Ray.rayl = 10e8;
  50055. return Ray;
  50056. }());
  50057. BABYLON.Ray = Ray;
  50058. })(BABYLON || (BABYLON = {}));
  50059. //# sourceMappingURL=babylon.ray.js.map
  50060. var BABYLON;
  50061. (function (BABYLON) {
  50062. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50063. if (boxMin.x > sphereCenter.x + sphereRadius)
  50064. return false;
  50065. if (sphereCenter.x - sphereRadius > boxMax.x)
  50066. return false;
  50067. if (boxMin.y > sphereCenter.y + sphereRadius)
  50068. return false;
  50069. if (sphereCenter.y - sphereRadius > boxMax.y)
  50070. return false;
  50071. if (boxMin.z > sphereCenter.z + sphereRadius)
  50072. return false;
  50073. if (sphereCenter.z - sphereRadius > boxMax.z)
  50074. return false;
  50075. return true;
  50076. };
  50077. var getLowestRoot = (function () {
  50078. var result = { root: 0, found: false };
  50079. return function (a, b, c, maxR) {
  50080. result.root = 0;
  50081. result.found = false;
  50082. var determinant = b * b - 4.0 * a * c;
  50083. if (determinant < 0)
  50084. return result;
  50085. var sqrtD = Math.sqrt(determinant);
  50086. var r1 = (-b - sqrtD) / (2.0 * a);
  50087. var r2 = (-b + sqrtD) / (2.0 * a);
  50088. if (r1 > r2) {
  50089. var temp = r2;
  50090. r2 = r1;
  50091. r1 = temp;
  50092. }
  50093. if (r1 > 0 && r1 < maxR) {
  50094. result.root = r1;
  50095. result.found = true;
  50096. return result;
  50097. }
  50098. if (r2 > 0 && r2 < maxR) {
  50099. result.root = r2;
  50100. result.found = true;
  50101. return result;
  50102. }
  50103. return result;
  50104. };
  50105. })();
  50106. var Collider = /** @class */ (function () {
  50107. function Collider() {
  50108. this._collisionPoint = BABYLON.Vector3.Zero();
  50109. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50110. this._tempVector = BABYLON.Vector3.Zero();
  50111. this._tempVector2 = BABYLON.Vector3.Zero();
  50112. this._tempVector3 = BABYLON.Vector3.Zero();
  50113. this._tempVector4 = BABYLON.Vector3.Zero();
  50114. this._edge = BABYLON.Vector3.Zero();
  50115. this._baseToVertex = BABYLON.Vector3.Zero();
  50116. this._destinationPoint = BABYLON.Vector3.Zero();
  50117. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50118. this._displacementVector = BABYLON.Vector3.Zero();
  50119. this._radius = BABYLON.Vector3.One();
  50120. this._retry = 0;
  50121. this._basePointWorld = BABYLON.Vector3.Zero();
  50122. this._velocityWorld = BABYLON.Vector3.Zero();
  50123. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50124. this._collisionMask = -1;
  50125. }
  50126. Object.defineProperty(Collider.prototype, "collisionMask", {
  50127. get: function () {
  50128. return this._collisionMask;
  50129. },
  50130. set: function (mask) {
  50131. this._collisionMask = !isNaN(mask) ? mask : -1;
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50137. /**
  50138. * Gets the plane normal used to compute the sliding response (in local space)
  50139. */
  50140. get: function () {
  50141. return this._slidePlaneNormal;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. // Methods
  50147. Collider.prototype._initialize = function (source, dir, e) {
  50148. this._velocity = dir;
  50149. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50150. this._basePoint = source;
  50151. source.multiplyToRef(this._radius, this._basePointWorld);
  50152. dir.multiplyToRef(this._radius, this._velocityWorld);
  50153. this._velocityWorldLength = this._velocityWorld.length();
  50154. this._epsilon = e;
  50155. this.collisionFound = false;
  50156. };
  50157. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50158. pa.subtractToRef(point, this._tempVector);
  50159. pb.subtractToRef(point, this._tempVector2);
  50160. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50161. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50162. if (d < 0)
  50163. return false;
  50164. pc.subtractToRef(point, this._tempVector3);
  50165. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50166. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50167. if (d < 0)
  50168. return false;
  50169. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50170. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50171. return d >= 0;
  50172. };
  50173. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50174. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50175. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50176. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50177. return false;
  50178. }
  50179. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50180. return false;
  50181. return true;
  50182. };
  50183. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50184. var t0;
  50185. var embeddedInPlane = false;
  50186. //defensive programming, actually not needed.
  50187. if (!trianglePlaneArray) {
  50188. trianglePlaneArray = [];
  50189. }
  50190. if (!trianglePlaneArray[faceIndex]) {
  50191. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50192. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50193. }
  50194. var trianglePlane = trianglePlaneArray[faceIndex];
  50195. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50196. return;
  50197. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50198. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50199. if (normalDotVelocity == 0) {
  50200. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50201. return;
  50202. embeddedInPlane = true;
  50203. t0 = 0;
  50204. }
  50205. else {
  50206. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50207. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50208. if (t0 > t1) {
  50209. var temp = t1;
  50210. t1 = t0;
  50211. t0 = temp;
  50212. }
  50213. if (t0 > 1.0 || t1 < 0.0)
  50214. return;
  50215. if (t0 < 0)
  50216. t0 = 0;
  50217. if (t0 > 1.0)
  50218. t0 = 1.0;
  50219. }
  50220. this._collisionPoint.copyFromFloats(0, 0, 0);
  50221. var found = false;
  50222. var t = 1.0;
  50223. if (!embeddedInPlane) {
  50224. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50225. this._velocity.scaleToRef(t0, this._tempVector);
  50226. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50227. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50228. found = true;
  50229. t = t0;
  50230. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50231. }
  50232. }
  50233. if (!found) {
  50234. var velocitySquaredLength = this._velocity.lengthSquared();
  50235. var a = velocitySquaredLength;
  50236. this._basePoint.subtractToRef(p1, this._tempVector);
  50237. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50238. var c = this._tempVector.lengthSquared() - 1.0;
  50239. var lowestRoot = getLowestRoot(a, b, c, t);
  50240. if (lowestRoot.found) {
  50241. t = lowestRoot.root;
  50242. found = true;
  50243. this._collisionPoint.copyFrom(p1);
  50244. }
  50245. this._basePoint.subtractToRef(p2, this._tempVector);
  50246. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50247. c = this._tempVector.lengthSquared() - 1.0;
  50248. lowestRoot = getLowestRoot(a, b, c, t);
  50249. if (lowestRoot.found) {
  50250. t = lowestRoot.root;
  50251. found = true;
  50252. this._collisionPoint.copyFrom(p2);
  50253. }
  50254. this._basePoint.subtractToRef(p3, this._tempVector);
  50255. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50256. c = this._tempVector.lengthSquared() - 1.0;
  50257. lowestRoot = getLowestRoot(a, b, c, t);
  50258. if (lowestRoot.found) {
  50259. t = lowestRoot.root;
  50260. found = true;
  50261. this._collisionPoint.copyFrom(p3);
  50262. }
  50263. p2.subtractToRef(p1, this._edge);
  50264. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50265. var edgeSquaredLength = this._edge.lengthSquared();
  50266. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50267. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50268. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50269. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50270. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50271. lowestRoot = getLowestRoot(a, b, c, t);
  50272. if (lowestRoot.found) {
  50273. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50274. if (f >= 0.0 && f <= 1.0) {
  50275. t = lowestRoot.root;
  50276. found = true;
  50277. this._edge.scaleInPlace(f);
  50278. p1.addToRef(this._edge, this._collisionPoint);
  50279. }
  50280. }
  50281. p3.subtractToRef(p2, this._edge);
  50282. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50283. edgeSquaredLength = this._edge.lengthSquared();
  50284. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50285. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50286. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50287. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50288. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50289. lowestRoot = getLowestRoot(a, b, c, t);
  50290. if (lowestRoot.found) {
  50291. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50292. if (f >= 0.0 && f <= 1.0) {
  50293. t = lowestRoot.root;
  50294. found = true;
  50295. this._edge.scaleInPlace(f);
  50296. p2.addToRef(this._edge, this._collisionPoint);
  50297. }
  50298. }
  50299. p1.subtractToRef(p3, this._edge);
  50300. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50301. edgeSquaredLength = this._edge.lengthSquared();
  50302. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50303. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50304. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50305. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50306. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50307. lowestRoot = getLowestRoot(a, b, c, t);
  50308. if (lowestRoot.found) {
  50309. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50310. if (f >= 0.0 && f <= 1.0) {
  50311. t = lowestRoot.root;
  50312. found = true;
  50313. this._edge.scaleInPlace(f);
  50314. p3.addToRef(this._edge, this._collisionPoint);
  50315. }
  50316. }
  50317. }
  50318. if (found) {
  50319. var distToCollision = t * this._velocity.length();
  50320. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50321. if (!this.intersectionPoint) {
  50322. this.intersectionPoint = this._collisionPoint.clone();
  50323. }
  50324. else {
  50325. this.intersectionPoint.copyFrom(this._collisionPoint);
  50326. }
  50327. this._nearestDistance = distToCollision;
  50328. this.collisionFound = true;
  50329. }
  50330. }
  50331. };
  50332. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50333. for (var i = indexStart; i < indexEnd; i += 3) {
  50334. var p1 = pts[indices[i] - decal];
  50335. var p2 = pts[indices[i + 1] - decal];
  50336. var p3 = pts[indices[i + 2] - decal];
  50337. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50338. }
  50339. };
  50340. Collider.prototype._getResponse = function (pos, vel) {
  50341. pos.addToRef(vel, this._destinationPoint);
  50342. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50343. this._basePoint.addToRef(vel, pos);
  50344. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50345. this._slidePlaneNormal.normalize();
  50346. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50347. pos.addInPlace(this._displacementVector);
  50348. this.intersectionPoint.addInPlace(this._displacementVector);
  50349. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50350. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50351. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50352. };
  50353. return Collider;
  50354. }());
  50355. BABYLON.Collider = Collider;
  50356. })(BABYLON || (BABYLON = {}));
  50357. //# sourceMappingURL=babylon.collider.js.map
  50358. var BABYLON;
  50359. (function (BABYLON) {
  50360. //WebWorker code will be inserted to this variable.
  50361. BABYLON.CollisionWorker = "";
  50362. var WorkerTaskType;
  50363. (function (WorkerTaskType) {
  50364. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50365. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50366. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50367. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50368. var WorkerReplyType;
  50369. (function (WorkerReplyType) {
  50370. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50371. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50372. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50373. var CollisionCoordinatorWorker = /** @class */ (function () {
  50374. function CollisionCoordinatorWorker() {
  50375. var _this = this;
  50376. this._scaledPosition = BABYLON.Vector3.Zero();
  50377. this._scaledVelocity = BABYLON.Vector3.Zero();
  50378. this.onMeshUpdated = function (transformNode) {
  50379. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50380. };
  50381. this.onGeometryUpdated = function (geometry) {
  50382. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50383. };
  50384. this._afterRender = function () {
  50385. if (!_this._init)
  50386. return;
  50387. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50388. return;
  50389. }
  50390. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50391. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50392. if (_this._runningUpdated > 4) {
  50393. return;
  50394. }
  50395. ++_this._runningUpdated;
  50396. var payload = {
  50397. updatedMeshes: _this._addUpdateMeshesList,
  50398. updatedGeometries: _this._addUpdateGeometriesList,
  50399. removedGeometries: _this._toRemoveGeometryArray,
  50400. removedMeshes: _this._toRemoveMeshesArray
  50401. };
  50402. var message = {
  50403. payload: payload,
  50404. taskType: WorkerTaskType.UPDATE
  50405. };
  50406. var serializable = [];
  50407. for (var id in payload.updatedGeometries) {
  50408. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50409. //prepare transferables
  50410. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50411. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50412. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50413. }
  50414. }
  50415. _this._worker.postMessage(message, serializable);
  50416. _this._addUpdateMeshesList = {};
  50417. _this._addUpdateGeometriesList = {};
  50418. _this._toRemoveGeometryArray = [];
  50419. _this._toRemoveMeshesArray = [];
  50420. };
  50421. this._onMessageFromWorker = function (e) {
  50422. var returnData = e.data;
  50423. if (returnData.error != WorkerReplyType.SUCCESS) {
  50424. //TODO what errors can be returned from the worker?
  50425. BABYLON.Tools.Warn("error returned from worker!");
  50426. return;
  50427. }
  50428. switch (returnData.taskType) {
  50429. case WorkerTaskType.INIT:
  50430. _this._init = true;
  50431. //Update the worked with ALL of the scene's current state
  50432. _this._scene.meshes.forEach(function (mesh) {
  50433. _this.onMeshAdded(mesh);
  50434. });
  50435. _this._scene.getGeometries().forEach(function (geometry) {
  50436. _this.onGeometryAdded(geometry);
  50437. });
  50438. break;
  50439. case WorkerTaskType.UPDATE:
  50440. _this._runningUpdated--;
  50441. break;
  50442. case WorkerTaskType.COLLIDE:
  50443. var returnPayload = returnData.payload;
  50444. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50445. return;
  50446. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50447. if (callback) {
  50448. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50449. if (mesh) {
  50450. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50451. }
  50452. }
  50453. //cleanup
  50454. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50455. break;
  50456. }
  50457. };
  50458. this._collisionsCallbackArray = [];
  50459. this._init = false;
  50460. this._runningUpdated = 0;
  50461. this._addUpdateMeshesList = {};
  50462. this._addUpdateGeometriesList = {};
  50463. this._toRemoveGeometryArray = [];
  50464. this._toRemoveMeshesArray = [];
  50465. }
  50466. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50467. if (!this._init)
  50468. return;
  50469. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50470. return;
  50471. position.divideToRef(collider._radius, this._scaledPosition);
  50472. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50473. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50474. var payload = {
  50475. collider: {
  50476. position: this._scaledPosition.asArray(),
  50477. velocity: this._scaledVelocity.asArray(),
  50478. radius: collider._radius.asArray()
  50479. },
  50480. collisionId: collisionIndex,
  50481. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50482. maximumRetry: maximumRetry
  50483. };
  50484. var message = {
  50485. payload: payload,
  50486. taskType: WorkerTaskType.COLLIDE
  50487. };
  50488. this._worker.postMessage(message);
  50489. };
  50490. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50491. this._scene = scene;
  50492. this._scene.registerAfterRender(this._afterRender);
  50493. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50494. this._worker = new Worker(workerUrl);
  50495. this._worker.onmessage = this._onMessageFromWorker;
  50496. var message = {
  50497. payload: {},
  50498. taskType: WorkerTaskType.INIT
  50499. };
  50500. this._worker.postMessage(message);
  50501. };
  50502. CollisionCoordinatorWorker.prototype.destroy = function () {
  50503. this._scene.unregisterAfterRender(this._afterRender);
  50504. this._worker.terminate();
  50505. };
  50506. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50507. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50508. this.onMeshUpdated(mesh);
  50509. };
  50510. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50511. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50512. };
  50513. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50514. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50515. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50516. this.onGeometryUpdated(geometry);
  50517. };
  50518. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50519. this._toRemoveGeometryArray.push(geometry.id);
  50520. };
  50521. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50522. var submeshes = [];
  50523. if (mesh.subMeshes) {
  50524. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50525. var boundingInfo = sm.getBoundingInfo();
  50526. return {
  50527. position: idx,
  50528. verticesStart: sm.verticesStart,
  50529. verticesCount: sm.verticesCount,
  50530. indexStart: sm.indexStart,
  50531. indexCount: sm.indexCount,
  50532. hasMaterial: !!sm.getMaterial(),
  50533. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50534. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50535. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50536. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50537. };
  50538. });
  50539. }
  50540. var geometryId = null;
  50541. if (mesh instanceof BABYLON.Mesh) {
  50542. var geometry = mesh.geometry;
  50543. geometryId = geometry ? geometry.id : null;
  50544. }
  50545. else if (mesh instanceof BABYLON.InstancedMesh) {
  50546. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50547. geometryId = geometry ? geometry.id : null;
  50548. }
  50549. var boundingInfo = mesh.getBoundingInfo();
  50550. return {
  50551. uniqueId: mesh.uniqueId,
  50552. id: mesh.id,
  50553. name: mesh.name,
  50554. geometryId: geometryId,
  50555. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50556. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50557. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50558. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50559. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50560. subMeshes: submeshes,
  50561. checkCollisions: mesh.checkCollisions
  50562. };
  50563. };
  50564. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50565. return {
  50566. id: geometry.id,
  50567. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50568. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50569. indices: new Uint32Array(geometry.getIndices() || []),
  50570. };
  50571. };
  50572. return CollisionCoordinatorWorker;
  50573. }());
  50574. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50575. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50576. function CollisionCoordinatorLegacy() {
  50577. this._scaledPosition = BABYLON.Vector3.Zero();
  50578. this._scaledVelocity = BABYLON.Vector3.Zero();
  50579. this._finalPosition = BABYLON.Vector3.Zero();
  50580. }
  50581. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50582. position.divideToRef(collider._radius, this._scaledPosition);
  50583. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50584. collider.collidedMesh = null;
  50585. collider._retry = 0;
  50586. collider._initialVelocity = this._scaledVelocity;
  50587. collider._initialPosition = this._scaledPosition;
  50588. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50589. this._finalPosition.multiplyInPlace(collider._radius);
  50590. //run the callback
  50591. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50592. };
  50593. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50594. this._scene = scene;
  50595. };
  50596. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50597. //Legacy need no destruction method.
  50598. };
  50599. //No update in legacy mode
  50600. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50601. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50602. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50603. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50604. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50605. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50606. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50607. if (excludedMesh === void 0) { excludedMesh = null; }
  50608. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50609. if (collider._retry >= maximumRetry) {
  50610. finalPosition.copyFrom(position);
  50611. return;
  50612. }
  50613. // Check if this is a mesh else camera or -1
  50614. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50615. collider._initialize(position, velocity, closeDistance);
  50616. // Check all meshes
  50617. for (var index = 0; index < this._scene.meshes.length; index++) {
  50618. var mesh = this._scene.meshes[index];
  50619. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50620. mesh._checkCollision(collider);
  50621. }
  50622. }
  50623. if (!collider.collisionFound) {
  50624. position.addToRef(velocity, finalPosition);
  50625. return;
  50626. }
  50627. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50628. collider._getResponse(position, velocity);
  50629. }
  50630. if (velocity.length() <= closeDistance) {
  50631. finalPosition.copyFrom(position);
  50632. return;
  50633. }
  50634. collider._retry++;
  50635. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50636. };
  50637. return CollisionCoordinatorLegacy;
  50638. }());
  50639. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50640. })(BABYLON || (BABYLON = {}));
  50641. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50642. var BABYLON;
  50643. (function (BABYLON) {
  50644. /**
  50645. * A particle represents one of the element emitted by a particle system.
  50646. * This is mainly define by its coordinates, direction, velocity and age.
  50647. */
  50648. var Particle = /** @class */ (function () {
  50649. /**
  50650. * Creates a new instance of @see Particle
  50651. * @param particleSystem the particle system the particle belongs to
  50652. */
  50653. function Particle(
  50654. /**
  50655. * particleSystem the particle system the particle belongs to.
  50656. */
  50657. particleSystem) {
  50658. this.particleSystem = particleSystem;
  50659. /**
  50660. * The world position of the particle in the scene.
  50661. */
  50662. this.position = BABYLON.Vector3.Zero();
  50663. /**
  50664. * The world direction of the particle in the scene.
  50665. */
  50666. this.direction = BABYLON.Vector3.Zero();
  50667. /**
  50668. * The color of the particle.
  50669. */
  50670. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50671. /**
  50672. * The color change of the particle per step.
  50673. */
  50674. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50675. /**
  50676. * Defines how long will the life of the particle be.
  50677. */
  50678. this.lifeTime = 1.0;
  50679. /**
  50680. * The current age of the particle.
  50681. */
  50682. this.age = 0;
  50683. /**
  50684. * The current size of the particle.
  50685. */
  50686. this.size = 0;
  50687. /**
  50688. * The current angle of the particle.
  50689. */
  50690. this.angle = 0;
  50691. /**
  50692. * Defines how fast is the angle changing.
  50693. */
  50694. this.angularSpeed = 0;
  50695. /**
  50696. * Defines the cell index used by the particle to be rendered from a sprite.
  50697. */
  50698. this.cellIndex = 0;
  50699. this._currentFrameCounter = 0;
  50700. if (!this.particleSystem.isAnimationSheetEnabled) {
  50701. return;
  50702. }
  50703. this.updateCellInfoFromSystem();
  50704. }
  50705. Particle.prototype.updateCellInfoFromSystem = function () {
  50706. this.cellIndex = this.particleSystem.startSpriteCellID;
  50707. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50708. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50709. }
  50710. else {
  50711. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50712. }
  50713. };
  50714. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50715. // (ageOffset / scaledUpdateSpeed) / available cells
  50716. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50717. this._currentFrameCounter += scaledUpdateSpeed;
  50718. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50719. this._currentFrameCounter = 0;
  50720. this.cellIndex++;
  50721. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50722. this.cellIndex = this.particleSystem.endSpriteCellID;
  50723. }
  50724. }
  50725. };
  50726. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50727. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50728. this.cellIndex++;
  50729. this._currentFrameCounter = 0;
  50730. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50731. if (this.particleSystem.spriteCellLoop) {
  50732. this.cellIndex = this.particleSystem.startSpriteCellID;
  50733. }
  50734. else {
  50735. this.cellIndex = this.particleSystem.endSpriteCellID;
  50736. }
  50737. }
  50738. }
  50739. else {
  50740. this._currentFrameCounter++;
  50741. }
  50742. };
  50743. /**
  50744. * Copy the properties of particle to another one.
  50745. * @param other the particle to copy the information to.
  50746. */
  50747. Particle.prototype.copyTo = function (other) {
  50748. other.position.copyFrom(this.position);
  50749. other.direction.copyFrom(this.direction);
  50750. other.color.copyFrom(this.color);
  50751. other.colorStep.copyFrom(this.colorStep);
  50752. other.lifeTime = this.lifeTime;
  50753. other.age = this.age;
  50754. other.size = this.size;
  50755. other.angle = this.angle;
  50756. other.angularSpeed = this.angularSpeed;
  50757. other.particleSystem = this.particleSystem;
  50758. other.cellIndex = this.cellIndex;
  50759. };
  50760. return Particle;
  50761. }());
  50762. BABYLON.Particle = Particle;
  50763. })(BABYLON || (BABYLON = {}));
  50764. //# sourceMappingURL=babylon.particle.js.map
  50765. var BABYLON;
  50766. (function (BABYLON) {
  50767. /**
  50768. * This represents a particle system in Babylon.
  50769. * 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.
  50770. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50771. * @example https://doc.babylonjs.com/babylon101/particles
  50772. */
  50773. var ParticleSystem = /** @class */ (function () {
  50774. /**
  50775. * Instantiates a particle system.
  50776. * 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.
  50777. * @param name The name of the particle system
  50778. * @param capacity The max number of particles alive at the same time
  50779. * @param scene The scene the particle system belongs to
  50780. * @param customEffect a custom effect used to change the way particles are rendered by default
  50781. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50782. * @param epsilon Offset used to render the particles
  50783. */
  50784. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50785. if (customEffect === void 0) { customEffect = null; }
  50786. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50787. if (epsilon === void 0) { epsilon = 0.01; }
  50788. var _this = this;
  50789. /**
  50790. * List of animations used by the particle system.
  50791. */
  50792. this.animations = [];
  50793. /**
  50794. * The rendering group used by the Particle system to chose when to render.
  50795. */
  50796. this.renderingGroupId = 0;
  50797. /**
  50798. * The emitter represents the Mesh or position we are attaching the particle system to.
  50799. */
  50800. this.emitter = null;
  50801. /**
  50802. * The maximum number of particles to emit per frame
  50803. */
  50804. this.emitRate = 10;
  50805. /**
  50806. * If you want to launch only a few particles at once, that can be done, as well.
  50807. */
  50808. this.manualEmitCount = -1;
  50809. /**
  50810. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50811. */
  50812. this.updateSpeed = 0.01;
  50813. /**
  50814. * The amount of time the particle system is running (depends of the overall update speed).
  50815. */
  50816. this.targetStopDuration = 0;
  50817. /**
  50818. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50819. */
  50820. this.disposeOnStop = false;
  50821. /**
  50822. * Minimum power of emitting particles.
  50823. */
  50824. this.minEmitPower = 1;
  50825. /**
  50826. * Maximum power of emitting particles.
  50827. */
  50828. this.maxEmitPower = 1;
  50829. /**
  50830. * Minimum life time of emitting particles.
  50831. */
  50832. this.minLifeTime = 1;
  50833. /**
  50834. * Maximum life time of emitting particles.
  50835. */
  50836. this.maxLifeTime = 1;
  50837. /**
  50838. * Minimum Size of emitting particles.
  50839. */
  50840. this.minSize = 1;
  50841. /**
  50842. * Maximum Size of emitting particles.
  50843. */
  50844. this.maxSize = 1;
  50845. /**
  50846. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50847. */
  50848. this.minAngularSpeed = 0;
  50849. /**
  50850. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50851. */
  50852. this.maxAngularSpeed = 0;
  50853. /**
  50854. * The layer mask we are rendering the particles through.
  50855. */
  50856. this.layerMask = 0x0FFFFFFF;
  50857. /**
  50858. * This can help using your own shader to render the particle system.
  50859. * The according effect will be created
  50860. */
  50861. this.customShader = null;
  50862. /**
  50863. * By default particle system starts as soon as they are created. This prevents the
  50864. * automatic start to happen and let you decide when to start emitting particles.
  50865. */
  50866. this.preventAutoStart = false;
  50867. /**
  50868. * Callback triggered when the particle animation is ending.
  50869. */
  50870. this.onAnimationEnd = null;
  50871. /**
  50872. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50873. */
  50874. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50875. /**
  50876. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50877. * to override the particles.
  50878. */
  50879. this.forceDepthWrite = false;
  50880. /**
  50881. * You can use gravity if you want to give an orientation to your particles.
  50882. */
  50883. this.gravity = BABYLON.Vector3.Zero();
  50884. /**
  50885. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50886. */
  50887. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50888. /**
  50889. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50890. */
  50891. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50892. /**
  50893. * Color the particle will have at the end of its lifetime.
  50894. */
  50895. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50896. /**
  50897. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50898. */
  50899. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50900. /**
  50901. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50902. */
  50903. this.spriteCellLoop = true;
  50904. /**
  50905. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50906. */
  50907. this.spriteCellChangeSpeed = 0;
  50908. /**
  50909. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50910. */
  50911. this.startSpriteCellID = 0;
  50912. /**
  50913. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50914. */
  50915. this.endSpriteCellID = 0;
  50916. /**
  50917. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50918. */
  50919. this.spriteCellWidth = 0;
  50920. /**
  50921. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50922. */
  50923. this.spriteCellHeight = 0;
  50924. /**
  50925. * An event triggered when the system is disposed.
  50926. */
  50927. this.onDisposeObservable = new BABYLON.Observable();
  50928. this._particles = new Array();
  50929. this._stockParticles = new Array();
  50930. this._newPartsExcess = 0;
  50931. this._vertexBuffers = {};
  50932. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50933. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50934. this._scaledDirection = BABYLON.Vector3.Zero();
  50935. this._scaledGravity = BABYLON.Vector3.Zero();
  50936. this._currentRenderId = -1;
  50937. this._started = false;
  50938. this._stopped = false;
  50939. this._actualFrame = 0;
  50940. this._vertexBufferSize = 11;
  50941. // start of sub system methods
  50942. /**
  50943. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50944. * Its lifetime will start back at 0.
  50945. */
  50946. this.recycleParticle = function (particle) {
  50947. var lastParticle = _this._particles.pop();
  50948. if (lastParticle !== particle) {
  50949. lastParticle.copyTo(particle);
  50950. }
  50951. _this._stockParticles.push(lastParticle);
  50952. };
  50953. this._createParticle = function () {
  50954. var particle;
  50955. if (_this._stockParticles.length !== 0) {
  50956. particle = _this._stockParticles.pop();
  50957. particle.age = 0;
  50958. particle.cellIndex = _this.startSpriteCellID;
  50959. }
  50960. else {
  50961. particle = new BABYLON.Particle(_this);
  50962. }
  50963. return particle;
  50964. };
  50965. this._emitFromParticle = function (particle) {
  50966. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  50967. return;
  50968. }
  50969. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  50970. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  50971. subSystem._rootParticleSystem = _this;
  50972. _this.activeSubSystems.push(subSystem);
  50973. subSystem.start();
  50974. };
  50975. this._appendParticleVertexes = null;
  50976. this.id = name;
  50977. this.name = name;
  50978. this._capacity = capacity;
  50979. this._epsilon = epsilon;
  50980. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50981. if (isAnimationSheetEnabled) {
  50982. this._vertexBufferSize = 12;
  50983. }
  50984. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50985. this._customEffect = customEffect;
  50986. scene.particleSystems.push(this);
  50987. this._createIndexBuffer();
  50988. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50989. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50990. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50991. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50992. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50993. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50994. if (this._isAnimationSheetEnabled) {
  50995. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50996. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50997. }
  50998. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50999. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51000. this._vertexBuffers["options"] = options;
  51001. // Default emitter type
  51002. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51003. this.updateFunction = function (particles) {
  51004. for (var index = 0; index < particles.length; index++) {
  51005. var particle = particles[index];
  51006. particle.age += _this._scaledUpdateSpeed;
  51007. if (particle.age >= particle.lifeTime) {
  51008. _this._emitFromParticle(particle);
  51009. _this.recycleParticle(particle);
  51010. index--;
  51011. continue;
  51012. }
  51013. else {
  51014. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51015. particle.color.addInPlace(_this._scaledColorStep);
  51016. if (particle.color.a < 0)
  51017. particle.color.a = 0;
  51018. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51019. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51020. particle.position.addInPlace(_this._scaledDirection);
  51021. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51022. particle.direction.addInPlace(_this._scaledGravity);
  51023. if (_this._isAnimationSheetEnabled) {
  51024. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51025. }
  51026. }
  51027. }
  51028. };
  51029. }
  51030. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51031. /**
  51032. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51033. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51034. */
  51035. get: function () {
  51036. if (this.particleEmitterType.direction1) {
  51037. return this.particleEmitterType.direction1;
  51038. }
  51039. return BABYLON.Vector3.Zero();
  51040. },
  51041. set: function (value) {
  51042. if (this.particleEmitterType.direction1) {
  51043. this.particleEmitterType.direction1 = value;
  51044. }
  51045. },
  51046. enumerable: true,
  51047. configurable: true
  51048. });
  51049. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51050. /**
  51051. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51052. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51053. */
  51054. get: function () {
  51055. if (this.particleEmitterType.direction2) {
  51056. return this.particleEmitterType.direction2;
  51057. }
  51058. return BABYLON.Vector3.Zero();
  51059. },
  51060. set: function (value) {
  51061. if (this.particleEmitterType.direction2) {
  51062. this.particleEmitterType.direction2 = value;
  51063. }
  51064. },
  51065. enumerable: true,
  51066. configurable: true
  51067. });
  51068. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51069. /**
  51070. * 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.
  51071. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51072. */
  51073. get: function () {
  51074. if (this.particleEmitterType.minEmitBox) {
  51075. return this.particleEmitterType.minEmitBox;
  51076. }
  51077. return BABYLON.Vector3.Zero();
  51078. },
  51079. set: function (value) {
  51080. if (this.particleEmitterType.minEmitBox) {
  51081. this.particleEmitterType.minEmitBox = value;
  51082. }
  51083. },
  51084. enumerable: true,
  51085. configurable: true
  51086. });
  51087. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51088. /**
  51089. * 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.
  51090. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51091. */
  51092. get: function () {
  51093. if (this.particleEmitterType.maxEmitBox) {
  51094. return this.particleEmitterType.maxEmitBox;
  51095. }
  51096. return BABYLON.Vector3.Zero();
  51097. },
  51098. set: function (value) {
  51099. if (this.particleEmitterType.maxEmitBox) {
  51100. this.particleEmitterType.maxEmitBox = value;
  51101. }
  51102. },
  51103. enumerable: true,
  51104. configurable: true
  51105. });
  51106. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51107. /**
  51108. * Sets a callback that will be triggered when the system is disposed.
  51109. */
  51110. set: function (callback) {
  51111. if (this._onDisposeObserver) {
  51112. this.onDisposeObservable.remove(this._onDisposeObserver);
  51113. }
  51114. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51115. },
  51116. enumerable: true,
  51117. configurable: true
  51118. });
  51119. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51120. /**
  51121. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51122. */
  51123. get: function () {
  51124. return this._isAnimationSheetEnabled;
  51125. },
  51126. enumerable: true,
  51127. configurable: true
  51128. });
  51129. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51130. //end of Sub-emitter
  51131. /**
  51132. * Gets the current list of active particles
  51133. */
  51134. get: function () {
  51135. return this._particles;
  51136. },
  51137. enumerable: true,
  51138. configurable: true
  51139. });
  51140. /**
  51141. * Returns the string "ParticleSystem"
  51142. * @returns a string containing the class name
  51143. */
  51144. ParticleSystem.prototype.getClassName = function () {
  51145. return "ParticleSystem";
  51146. };
  51147. ParticleSystem.prototype._createIndexBuffer = function () {
  51148. var indices = [];
  51149. var index = 0;
  51150. for (var count = 0; count < this._capacity; count++) {
  51151. indices.push(index);
  51152. indices.push(index + 1);
  51153. indices.push(index + 2);
  51154. indices.push(index);
  51155. indices.push(index + 2);
  51156. indices.push(index + 3);
  51157. index += 4;
  51158. }
  51159. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51160. };
  51161. /**
  51162. * Gets the maximum number of particles active at the same time.
  51163. * @returns The max number of active particles.
  51164. */
  51165. ParticleSystem.prototype.getCapacity = function () {
  51166. return this._capacity;
  51167. };
  51168. /**
  51169. * Gets Wether there are still active particles in the system.
  51170. * @returns True if it is alive, otherwise false.
  51171. */
  51172. ParticleSystem.prototype.isAlive = function () {
  51173. return this._alive;
  51174. };
  51175. /**
  51176. * Gets Wether the system has been started.
  51177. * @returns True if it has been started, otherwise false.
  51178. */
  51179. ParticleSystem.prototype.isStarted = function () {
  51180. return this._started;
  51181. };
  51182. /**
  51183. * Starts the particle system and begins to emit.
  51184. */
  51185. ParticleSystem.prototype.start = function () {
  51186. this._started = true;
  51187. this._stopped = false;
  51188. this._actualFrame = 0;
  51189. if (this.subEmitters && this.subEmitters.length != 0) {
  51190. this.activeSubSystems = new Array();
  51191. }
  51192. };
  51193. /**
  51194. * Stops the particle system.
  51195. * @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.
  51196. */
  51197. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51198. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51199. this._stopped = true;
  51200. if (stopSubEmitters) {
  51201. this._stopSubEmitters();
  51202. }
  51203. };
  51204. // animation sheet
  51205. /**
  51206. * Remove all active particles
  51207. */
  51208. ParticleSystem.prototype.reset = function () {
  51209. this._stockParticles = [];
  51210. this._particles = [];
  51211. };
  51212. /**
  51213. * @ignore (for internal use only)
  51214. */
  51215. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51216. var offset = index * this._vertexBufferSize;
  51217. this._vertexData[offset] = particle.position.x;
  51218. this._vertexData[offset + 1] = particle.position.y;
  51219. this._vertexData[offset + 2] = particle.position.z;
  51220. this._vertexData[offset + 3] = particle.color.r;
  51221. this._vertexData[offset + 4] = particle.color.g;
  51222. this._vertexData[offset + 5] = particle.color.b;
  51223. this._vertexData[offset + 6] = particle.color.a;
  51224. this._vertexData[offset + 7] = particle.angle;
  51225. this._vertexData[offset + 8] = particle.size;
  51226. this._vertexData[offset + 9] = offsetX;
  51227. this._vertexData[offset + 10] = offsetY;
  51228. };
  51229. /**
  51230. * @ignore (for internal use only)
  51231. */
  51232. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51233. if (offsetX === 0)
  51234. offsetX = this._epsilon;
  51235. else if (offsetX === 1)
  51236. offsetX = 1 - this._epsilon;
  51237. if (offsetY === 0)
  51238. offsetY = this._epsilon;
  51239. else if (offsetY === 1)
  51240. offsetY = 1 - this._epsilon;
  51241. var offset = index * this._vertexBufferSize;
  51242. this._vertexData[offset] = particle.position.x;
  51243. this._vertexData[offset + 1] = particle.position.y;
  51244. this._vertexData[offset + 2] = particle.position.z;
  51245. this._vertexData[offset + 3] = particle.color.r;
  51246. this._vertexData[offset + 4] = particle.color.g;
  51247. this._vertexData[offset + 5] = particle.color.b;
  51248. this._vertexData[offset + 6] = particle.color.a;
  51249. this._vertexData[offset + 7] = particle.angle;
  51250. this._vertexData[offset + 8] = particle.size;
  51251. this._vertexData[offset + 9] = offsetX;
  51252. this._vertexData[offset + 10] = offsetY;
  51253. this._vertexData[offset + 11] = particle.cellIndex;
  51254. };
  51255. ParticleSystem.prototype._stopSubEmitters = function () {
  51256. if (!this.activeSubSystems) {
  51257. return;
  51258. }
  51259. this.activeSubSystems.forEach(function (subSystem) {
  51260. subSystem.stop(true);
  51261. });
  51262. this.activeSubSystems = new Array();
  51263. };
  51264. ParticleSystem.prototype._removeFromRoot = function () {
  51265. if (!this._rootParticleSystem) {
  51266. return;
  51267. }
  51268. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51269. if (index !== -1) {
  51270. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51271. }
  51272. };
  51273. // end of sub system methods
  51274. ParticleSystem.prototype._update = function (newParticles) {
  51275. // Update current
  51276. this._alive = this._particles.length > 0;
  51277. this.updateFunction(this._particles);
  51278. // Add new ones
  51279. var worldMatrix;
  51280. if (this.emitter.position) {
  51281. var emitterMesh = this.emitter;
  51282. worldMatrix = emitterMesh.getWorldMatrix();
  51283. }
  51284. else {
  51285. var emitterPosition = this.emitter;
  51286. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51287. }
  51288. var particle;
  51289. for (var index = 0; index < newParticles; index++) {
  51290. if (this._particles.length === this._capacity) {
  51291. break;
  51292. }
  51293. particle = this._createParticle();
  51294. this._particles.push(particle);
  51295. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51296. if (this.startPositionFunction) {
  51297. this.startPositionFunction(worldMatrix, particle.position, particle);
  51298. }
  51299. else {
  51300. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51301. }
  51302. if (this.startDirectionFunction) {
  51303. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51304. }
  51305. else {
  51306. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51307. }
  51308. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51309. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51310. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51311. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51312. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51313. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51314. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51315. }
  51316. };
  51317. ParticleSystem.prototype._getEffect = function () {
  51318. if (this._customEffect) {
  51319. return this._customEffect;
  51320. }
  51321. ;
  51322. var defines = [];
  51323. if (this._scene.clipPlane) {
  51324. defines.push("#define CLIPPLANE");
  51325. }
  51326. if (this._isAnimationSheetEnabled) {
  51327. defines.push("#define ANIMATESHEET");
  51328. }
  51329. // Effect
  51330. var join = defines.join("\n");
  51331. if (this._cachedDefines !== join) {
  51332. this._cachedDefines = join;
  51333. var attributesNamesOrOptions;
  51334. var effectCreationOption;
  51335. if (this._isAnimationSheetEnabled) {
  51336. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51337. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51338. }
  51339. else {
  51340. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51341. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51342. }
  51343. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51344. }
  51345. return this._effect;
  51346. };
  51347. /**
  51348. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51349. */
  51350. ParticleSystem.prototype.animate = function () {
  51351. if (!this._started)
  51352. return;
  51353. var effect = this._getEffect();
  51354. // Check
  51355. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51356. return;
  51357. if (this._currentRenderId === this._scene.getRenderId()) {
  51358. return;
  51359. }
  51360. this._currentRenderId = this._scene.getRenderId();
  51361. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51362. // determine the number of particles we need to create
  51363. var newParticles;
  51364. if (this.manualEmitCount > -1) {
  51365. newParticles = this.manualEmitCount;
  51366. this._newPartsExcess = 0;
  51367. this.manualEmitCount = 0;
  51368. }
  51369. else {
  51370. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51371. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51372. }
  51373. if (this._newPartsExcess > 1.0) {
  51374. newParticles += this._newPartsExcess >> 0;
  51375. this._newPartsExcess -= this._newPartsExcess >> 0;
  51376. }
  51377. this._alive = false;
  51378. if (!this._stopped) {
  51379. this._actualFrame += this._scaledUpdateSpeed;
  51380. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51381. this.stop();
  51382. }
  51383. else {
  51384. newParticles = 0;
  51385. }
  51386. this._update(newParticles);
  51387. // Stopped?
  51388. if (this._stopped) {
  51389. if (!this._alive) {
  51390. this._started = false;
  51391. if (this.onAnimationEnd) {
  51392. this.onAnimationEnd();
  51393. }
  51394. if (this.disposeOnStop) {
  51395. this._scene._toBeDisposed.push(this);
  51396. }
  51397. }
  51398. }
  51399. // Animation sheet
  51400. if (this._isAnimationSheetEnabled) {
  51401. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51402. }
  51403. else {
  51404. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51405. }
  51406. // Update VBO
  51407. var offset = 0;
  51408. for (var index = 0; index < this._particles.length; index++) {
  51409. var particle = this._particles[index];
  51410. this._appendParticleVertexes(offset, particle);
  51411. offset += 4;
  51412. }
  51413. if (this._vertexBuffer) {
  51414. this._vertexBuffer.update(this._vertexData);
  51415. }
  51416. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51417. this.stop();
  51418. }
  51419. };
  51420. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51421. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51422. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51423. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51424. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51425. };
  51426. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51427. this._appendParticleVertex(offset++, particle, 0, 0);
  51428. this._appendParticleVertex(offset++, particle, 1, 0);
  51429. this._appendParticleVertex(offset++, particle, 1, 1);
  51430. this._appendParticleVertex(offset++, particle, 0, 1);
  51431. };
  51432. /**
  51433. * Rebuilds the particle system.
  51434. */
  51435. ParticleSystem.prototype.rebuild = function () {
  51436. this._createIndexBuffer();
  51437. if (this._vertexBuffer) {
  51438. this._vertexBuffer._rebuild();
  51439. }
  51440. };
  51441. /**
  51442. * Renders the particle system in its current state.
  51443. * @returns the current number of particles
  51444. */
  51445. ParticleSystem.prototype.render = function () {
  51446. var effect = this._getEffect();
  51447. // Check
  51448. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51449. return 0;
  51450. }
  51451. var engine = this._scene.getEngine();
  51452. // Render
  51453. engine.enableEffect(effect);
  51454. engine.setState(false);
  51455. var viewMatrix = this._scene.getViewMatrix();
  51456. effect.setTexture("diffuseSampler", this.particleTexture);
  51457. effect.setMatrix("view", viewMatrix);
  51458. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51459. if (this._isAnimationSheetEnabled) {
  51460. var baseSize = this.particleTexture.getBaseSize();
  51461. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51462. }
  51463. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51464. if (this._scene.clipPlane) {
  51465. var clipPlane = this._scene.clipPlane;
  51466. var invView = viewMatrix.clone();
  51467. invView.invert();
  51468. effect.setMatrix("invView", invView);
  51469. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51470. }
  51471. // VBOs
  51472. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51473. // Draw order
  51474. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51475. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51476. }
  51477. else {
  51478. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51479. }
  51480. if (this.forceDepthWrite) {
  51481. engine.setDepthWrite(true);
  51482. }
  51483. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51484. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51485. return this._particles.length;
  51486. };
  51487. /**
  51488. * Disposes the particle system and free the associated resources
  51489. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51490. */
  51491. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51492. if (disposeTexture === void 0) { disposeTexture = true; }
  51493. if (this._vertexBuffer) {
  51494. this._vertexBuffer.dispose();
  51495. this._vertexBuffer = null;
  51496. }
  51497. if (this._indexBuffer) {
  51498. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51499. this._indexBuffer = null;
  51500. }
  51501. if (disposeTexture && this.particleTexture) {
  51502. this.particleTexture.dispose();
  51503. this.particleTexture = null;
  51504. }
  51505. this._removeFromRoot();
  51506. // Remove from scene
  51507. var index = this._scene.particleSystems.indexOf(this);
  51508. if (index > -1) {
  51509. this._scene.particleSystems.splice(index, 1);
  51510. }
  51511. // Callback
  51512. this.onDisposeObservable.notifyObservers(this);
  51513. this.onDisposeObservable.clear();
  51514. };
  51515. /**
  51516. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51517. * @param radius The radius of the sphere to emit from
  51518. * @returns the emitter
  51519. */
  51520. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51521. if (radius === void 0) { radius = 1; }
  51522. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51523. this.particleEmitterType = particleEmitter;
  51524. return particleEmitter;
  51525. };
  51526. /**
  51527. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51528. * @param radius The radius of the sphere to emit from
  51529. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51530. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51531. * @returns the emitter
  51532. */
  51533. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51534. if (radius === void 0) { radius = 1; }
  51535. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51536. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51537. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51538. this.particleEmitterType = particleEmitter;
  51539. return particleEmitter;
  51540. };
  51541. /**
  51542. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51543. * @param radius The radius of the cone to emit from
  51544. * @param angle The base angle of the cone
  51545. * @returns the emitter
  51546. */
  51547. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51548. if (radius === void 0) { radius = 1; }
  51549. if (angle === void 0) { angle = Math.PI / 4; }
  51550. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51551. this.particleEmitterType = particleEmitter;
  51552. return particleEmitter;
  51553. };
  51554. // 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.
  51555. /**
  51556. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51557. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51558. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51559. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51560. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51561. * @returns the emitter
  51562. */
  51563. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51564. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51565. this.direction1 = direction1;
  51566. this.direction2 = direction2;
  51567. this.minEmitBox = minEmitBox;
  51568. this.maxEmitBox = maxEmitBox;
  51569. this.particleEmitterType = particleEmitter;
  51570. return particleEmitter;
  51571. };
  51572. // Clone
  51573. /**
  51574. * Clones the particle system.
  51575. * @param name The name of the cloned object
  51576. * @param newEmitter The new emitter to use
  51577. * @returns the cloned particle system
  51578. */
  51579. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51580. var custom = null;
  51581. var program = null;
  51582. if (this.customShader != null) {
  51583. program = this.customShader;
  51584. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51585. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51586. }
  51587. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51588. result.customShader = program;
  51589. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51590. if (newEmitter === undefined) {
  51591. newEmitter = this.emitter;
  51592. }
  51593. result.emitter = newEmitter;
  51594. if (this.particleTexture) {
  51595. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51596. }
  51597. if (!this.preventAutoStart) {
  51598. result.start();
  51599. }
  51600. return result;
  51601. };
  51602. /**
  51603. * Serializes the particle system to a JSON object.
  51604. * @returns the JSON object
  51605. */
  51606. ParticleSystem.prototype.serialize = function () {
  51607. var serializationObject = {};
  51608. serializationObject.name = this.name;
  51609. serializationObject.id = this.id;
  51610. // Emitter
  51611. if (this.emitter.position) {
  51612. var emitterMesh = this.emitter;
  51613. serializationObject.emitterId = emitterMesh.id;
  51614. }
  51615. else {
  51616. var emitterPosition = this.emitter;
  51617. serializationObject.emitter = emitterPosition.asArray();
  51618. }
  51619. serializationObject.capacity = this.getCapacity();
  51620. if (this.particleTexture) {
  51621. serializationObject.textureName = this.particleTexture.name;
  51622. }
  51623. // Animations
  51624. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51625. // Particle system
  51626. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51627. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51628. serializationObject.minSize = this.minSize;
  51629. serializationObject.maxSize = this.maxSize;
  51630. serializationObject.minEmitPower = this.minEmitPower;
  51631. serializationObject.maxEmitPower = this.maxEmitPower;
  51632. serializationObject.minLifeTime = this.minLifeTime;
  51633. serializationObject.maxLifeTime = this.maxLifeTime;
  51634. serializationObject.emitRate = this.emitRate;
  51635. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51636. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51637. serializationObject.gravity = this.gravity.asArray();
  51638. serializationObject.direction1 = this.direction1.asArray();
  51639. serializationObject.direction2 = this.direction2.asArray();
  51640. serializationObject.color1 = this.color1.asArray();
  51641. serializationObject.color2 = this.color2.asArray();
  51642. serializationObject.colorDead = this.colorDead.asArray();
  51643. serializationObject.updateSpeed = this.updateSpeed;
  51644. serializationObject.targetStopDuration = this.targetStopDuration;
  51645. serializationObject.textureMask = this.textureMask.asArray();
  51646. serializationObject.blendMode = this.blendMode;
  51647. serializationObject.customShader = this.customShader;
  51648. serializationObject.preventAutoStart = this.preventAutoStart;
  51649. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51650. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51651. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51652. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51653. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51654. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51655. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51656. // Emitter
  51657. if (this.particleEmitterType) {
  51658. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51659. }
  51660. return serializationObject;
  51661. };
  51662. /**
  51663. * Parses a JSON object to create a particle system.
  51664. * @param parsedParticleSystem The JSON object to parse
  51665. * @param scene The scene to create the particle system in
  51666. * @param rootUrl The root url to use to load external dependencies like texture
  51667. * @returns the Parsed particle system
  51668. */
  51669. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51670. var name = parsedParticleSystem.name;
  51671. var custom = null;
  51672. var program = null;
  51673. if (parsedParticleSystem.customShader) {
  51674. program = parsedParticleSystem.customShader;
  51675. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51676. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51677. }
  51678. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51679. particleSystem.customShader = program;
  51680. if (parsedParticleSystem.id) {
  51681. particleSystem.id = parsedParticleSystem.id;
  51682. }
  51683. // Auto start
  51684. if (parsedParticleSystem.preventAutoStart) {
  51685. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51686. }
  51687. // Texture
  51688. if (parsedParticleSystem.textureName) {
  51689. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51690. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51691. }
  51692. // Emitter
  51693. if (parsedParticleSystem.emitterId) {
  51694. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51695. }
  51696. else {
  51697. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51698. }
  51699. // Animations
  51700. if (parsedParticleSystem.animations) {
  51701. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51702. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51703. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51704. }
  51705. }
  51706. if (parsedParticleSystem.autoAnimate) {
  51707. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51708. }
  51709. // Particle system
  51710. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51711. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51712. particleSystem.minSize = parsedParticleSystem.minSize;
  51713. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51714. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51715. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51716. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51717. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51718. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51719. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51720. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51721. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51722. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51723. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51724. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51725. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51726. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51727. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51728. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51729. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51730. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51731. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51732. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51733. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51734. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51735. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51736. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51737. if (!particleSystem.preventAutoStart) {
  51738. particleSystem.start();
  51739. }
  51740. return particleSystem;
  51741. };
  51742. /**
  51743. * Source color is added to the destination color without alpha affecting the result.
  51744. */
  51745. ParticleSystem.BLENDMODE_ONEONE = 0;
  51746. /**
  51747. * Blend current color and particle color using particle’s alpha.
  51748. */
  51749. ParticleSystem.BLENDMODE_STANDARD = 1;
  51750. return ParticleSystem;
  51751. }());
  51752. BABYLON.ParticleSystem = ParticleSystem;
  51753. })(BABYLON || (BABYLON = {}));
  51754. //# sourceMappingURL=babylon.particleSystem.js.map
  51755. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51756. var BABYLON;
  51757. (function (BABYLON) {
  51758. /**
  51759. * Particle emitter emitting particles from the inside of a box.
  51760. * It emits the particles randomly between 2 given directions.
  51761. */
  51762. var BoxParticleEmitter = /** @class */ (function () {
  51763. /**
  51764. * Creates a new instance of @see BoxParticleEmitter
  51765. */
  51766. function BoxParticleEmitter() {
  51767. /**
  51768. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51769. */
  51770. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51771. /**
  51772. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51773. */
  51774. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51775. /**
  51776. * 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.
  51777. */
  51778. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51779. /**
  51780. * 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.
  51781. */
  51782. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51783. }
  51784. /**
  51785. * Called by the particle System when the direction is computed for the created particle.
  51786. * @param emitPower is the power of the particle (speed)
  51787. * @param worldMatrix is the world matrix of the particle system
  51788. * @param directionToUpdate is the direction vector to update with the result
  51789. * @param particle is the particle we are computed the direction for
  51790. */
  51791. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51792. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51793. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51794. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51795. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51796. };
  51797. /**
  51798. * Called by the particle System when the position is computed for the created particle.
  51799. * @param worldMatrix is the world matrix of the particle system
  51800. * @param positionToUpdate is the position vector to update with the result
  51801. * @param particle is the particle we are computed the position for
  51802. */
  51803. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51804. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51805. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51806. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51807. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51808. };
  51809. /**
  51810. * Clones the current emitter and returns a copy of it
  51811. * @returns the new emitter
  51812. */
  51813. BoxParticleEmitter.prototype.clone = function () {
  51814. var newOne = new BoxParticleEmitter();
  51815. BABYLON.Tools.DeepCopy(this, newOne);
  51816. return newOne;
  51817. };
  51818. /**
  51819. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51820. * @param effect defines the update shader
  51821. */
  51822. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51823. effect.setVector3("direction1", this.direction1);
  51824. effect.setVector3("direction2", this.direction2);
  51825. effect.setVector3("minEmitBox", this.minEmitBox);
  51826. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51827. };
  51828. /**
  51829. * Returns a string to use to update the GPU particles update shader
  51830. * @returns a string containng the defines string
  51831. */
  51832. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51833. return "#define BOXEMITTER";
  51834. };
  51835. /**
  51836. * Returns the string "BoxEmitter"
  51837. * @returns a string containing the class name
  51838. */
  51839. BoxParticleEmitter.prototype.getClassName = function () {
  51840. return "BoxEmitter";
  51841. };
  51842. /**
  51843. * Serializes the particle system to a JSON object.
  51844. * @returns the JSON object
  51845. */
  51846. BoxParticleEmitter.prototype.serialize = function () {
  51847. var serializationObject = {};
  51848. serializationObject.type = this.getClassName();
  51849. serializationObject.direction1 = this.direction1.asArray();
  51850. ;
  51851. serializationObject.direction2 = this.direction2.asArray();
  51852. ;
  51853. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51854. ;
  51855. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51856. ;
  51857. return serializationObject;
  51858. };
  51859. /**
  51860. * Parse properties from a JSON object
  51861. * @param serializationObject defines the JSON object
  51862. */
  51863. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51864. this.direction1.copyFrom(serializationObject.direction1);
  51865. this.direction2.copyFrom(serializationObject.direction2);
  51866. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51867. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51868. };
  51869. return BoxParticleEmitter;
  51870. }());
  51871. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51872. })(BABYLON || (BABYLON = {}));
  51873. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51874. var BABYLON;
  51875. (function (BABYLON) {
  51876. /**
  51877. * Particle emitter emitting particles from the inside of a cone.
  51878. * It emits the particles alongside the cone volume from the base to the particle.
  51879. * The emission direction might be randomized.
  51880. */
  51881. var ConeParticleEmitter = /** @class */ (function () {
  51882. /**
  51883. * Creates a new instance of @see ConeParticleEmitter
  51884. * @param radius the radius of the emission cone (1 by default)
  51885. * @param angles the cone base angle (PI by default)
  51886. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51887. */
  51888. function ConeParticleEmitter(radius,
  51889. /**
  51890. * The radius of the emission cone.
  51891. */
  51892. angle,
  51893. /**
  51894. * The cone base angle.
  51895. */
  51896. directionRandomizer) {
  51897. if (radius === void 0) { radius = 1; }
  51898. if (angle === void 0) { angle = Math.PI; }
  51899. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51900. this.angle = angle;
  51901. this.directionRandomizer = directionRandomizer;
  51902. this.radius = radius;
  51903. }
  51904. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51905. /**
  51906. * Gets the radius of the emission cone.
  51907. */
  51908. get: function () {
  51909. return this._radius;
  51910. },
  51911. /**
  51912. * Sets the radius of the emission cone.
  51913. */
  51914. set: function (value) {
  51915. this._radius = value;
  51916. if (this.angle !== 0) {
  51917. this._height = value / Math.tan(this.angle / 2);
  51918. }
  51919. else {
  51920. this._height = 1;
  51921. }
  51922. },
  51923. enumerable: true,
  51924. configurable: true
  51925. });
  51926. /**
  51927. * Called by the particle System when the direction is computed for the created particle.
  51928. * @param emitPower is the power of the particle (speed)
  51929. * @param worldMatrix is the world matrix of the particle system
  51930. * @param directionToUpdate is the direction vector to update with the result
  51931. * @param particle is the particle we are computed the direction for
  51932. */
  51933. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51934. if (this.angle === 0) {
  51935. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51936. }
  51937. else {
  51938. // measure the direction Vector from the emitter to the particle.
  51939. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51940. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51941. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51942. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51943. direction.x += randX;
  51944. direction.y += randY;
  51945. direction.z += randZ;
  51946. direction.normalize();
  51947. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51948. }
  51949. };
  51950. /**
  51951. * Called by the particle System when the position is computed for the created particle.
  51952. * @param worldMatrix is the world matrix of the particle system
  51953. * @param positionToUpdate is the position vector to update with the result
  51954. * @param particle is the particle we are computed the position for
  51955. */
  51956. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51957. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51958. var h = BABYLON.Scalar.RandomRange(0, 1);
  51959. // Better distribution in a cone at normal angles.
  51960. h = 1 - h * h;
  51961. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51962. radius = radius * h / this._height;
  51963. var randX = radius * Math.sin(s);
  51964. var randZ = radius * Math.cos(s);
  51965. var randY = h * this._height;
  51966. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51967. };
  51968. /**
  51969. * Clones the current emitter and returns a copy of it
  51970. * @returns the new emitter
  51971. */
  51972. ConeParticleEmitter.prototype.clone = function () {
  51973. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51974. BABYLON.Tools.DeepCopy(this, newOne);
  51975. return newOne;
  51976. };
  51977. /**
  51978. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51979. * @param effect defines the update shader
  51980. */
  51981. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51982. effect.setFloat("radius", this.radius);
  51983. effect.setFloat("angle", this.angle);
  51984. effect.setFloat("height", this._height);
  51985. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51986. };
  51987. /**
  51988. * Returns a string to use to update the GPU particles update shader
  51989. * @returns a string containng the defines string
  51990. */
  51991. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51992. return "#define CONEEMITTER";
  51993. };
  51994. /**
  51995. * Returns the string "BoxEmitter"
  51996. * @returns a string containing the class name
  51997. */
  51998. ConeParticleEmitter.prototype.getClassName = function () {
  51999. return "ConeEmitter";
  52000. };
  52001. /**
  52002. * Serializes the particle system to a JSON object.
  52003. * @returns the JSON object
  52004. */
  52005. ConeParticleEmitter.prototype.serialize = function () {
  52006. var serializationObject = {};
  52007. serializationObject.type = this.getClassName();
  52008. serializationObject.radius = this.radius;
  52009. serializationObject.angle = this.angle;
  52010. serializationObject.directionRandomizer = this.directionRandomizer;
  52011. return serializationObject;
  52012. };
  52013. /**
  52014. * Parse properties from a JSON object
  52015. * @param serializationObject defines the JSON object
  52016. */
  52017. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52018. this.radius = serializationObject.radius;
  52019. this.angle = serializationObject.angle;
  52020. this.directionRandomizer = serializationObject.directionRandomizer;
  52021. };
  52022. return ConeParticleEmitter;
  52023. }());
  52024. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52025. })(BABYLON || (BABYLON = {}));
  52026. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52027. var BABYLON;
  52028. (function (BABYLON) {
  52029. /**
  52030. * Particle emitter emitting particles from the inside of a sphere.
  52031. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52032. */
  52033. var SphereParticleEmitter = /** @class */ (function () {
  52034. /**
  52035. * Creates a new instance of @see SphereParticleEmitter
  52036. * @param radius the radius of the emission sphere (1 by default)
  52037. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52038. */
  52039. function SphereParticleEmitter(
  52040. /**
  52041. * The radius of the emission sphere.
  52042. */
  52043. radius,
  52044. /**
  52045. * How much to randomize the particle direction [0-1].
  52046. */
  52047. directionRandomizer) {
  52048. if (radius === void 0) { radius = 1; }
  52049. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52050. this.radius = radius;
  52051. this.directionRandomizer = directionRandomizer;
  52052. }
  52053. /**
  52054. * Called by the particle System when the direction is computed for the created particle.
  52055. * @param emitPower is the power of the particle (speed)
  52056. * @param worldMatrix is the world matrix of the particle system
  52057. * @param directionToUpdate is the direction vector to update with the result
  52058. * @param particle is the particle we are computed the direction for
  52059. */
  52060. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52061. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52062. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52063. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52064. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52065. direction.x += randX;
  52066. direction.y += randY;
  52067. direction.z += randZ;
  52068. direction.normalize();
  52069. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52070. };
  52071. /**
  52072. * Called by the particle System when the position is computed for the created particle.
  52073. * @param worldMatrix is the world matrix of the particle system
  52074. * @param positionToUpdate is the position vector to update with the result
  52075. * @param particle is the particle we are computed the position for
  52076. */
  52077. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52078. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52079. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52080. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52081. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52082. var randY = randRadius * Math.cos(theta);
  52083. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52085. };
  52086. /**
  52087. * Clones the current emitter and returns a copy of it
  52088. * @returns the new emitter
  52089. */
  52090. SphereParticleEmitter.prototype.clone = function () {
  52091. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52092. BABYLON.Tools.DeepCopy(this, newOne);
  52093. return newOne;
  52094. };
  52095. /**
  52096. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52097. * @param effect defines the update shader
  52098. */
  52099. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52100. effect.setFloat("radius", this.radius);
  52101. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52102. };
  52103. /**
  52104. * Returns a string to use to update the GPU particles update shader
  52105. * @returns a string containng the defines string
  52106. */
  52107. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52108. return "#define SPHEREEMITTER";
  52109. };
  52110. /**
  52111. * Returns the string "SphereParticleEmitter"
  52112. * @returns a string containing the class name
  52113. */
  52114. SphereParticleEmitter.prototype.getClassName = function () {
  52115. return "SphereParticleEmitter";
  52116. };
  52117. /**
  52118. * Serializes the particle system to a JSON object.
  52119. * @returns the JSON object
  52120. */
  52121. SphereParticleEmitter.prototype.serialize = function () {
  52122. var serializationObject = {};
  52123. serializationObject.type = this.getClassName();
  52124. serializationObject.radius = this.radius;
  52125. serializationObject.directionRandomizer = this.directionRandomizer;
  52126. return serializationObject;
  52127. };
  52128. /**
  52129. * Parse properties from a JSON object
  52130. * @param serializationObject defines the JSON object
  52131. */
  52132. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52133. this.radius = serializationObject.radius;
  52134. this.directionRandomizer = serializationObject.directionRandomizer;
  52135. };
  52136. return SphereParticleEmitter;
  52137. }());
  52138. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52139. /**
  52140. * Particle emitter emitting particles from the inside of a sphere.
  52141. * It emits the particles randomly between two vectors.
  52142. */
  52143. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52144. __extends(SphereDirectedParticleEmitter, _super);
  52145. /**
  52146. * Creates a new instance of @see SphereDirectedParticleEmitter
  52147. * @param radius the radius of the emission sphere (1 by default)
  52148. * @param direction1 the min limit of the emission direction (up vector by default)
  52149. * @param direction2 the max limit of the emission direction (up vector by default)
  52150. */
  52151. function SphereDirectedParticleEmitter(radius,
  52152. /**
  52153. * The min limit of the emission direction.
  52154. */
  52155. direction1,
  52156. /**
  52157. * The max limit of the emission direction.
  52158. */
  52159. direction2) {
  52160. if (radius === void 0) { radius = 1; }
  52161. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52162. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52163. var _this = _super.call(this, radius) || this;
  52164. _this.direction1 = direction1;
  52165. _this.direction2 = direction2;
  52166. return _this;
  52167. }
  52168. /**
  52169. * Called by the particle System when the direction is computed for the created particle.
  52170. * @param emitPower is the power of the particle (speed)
  52171. * @param worldMatrix is the world matrix of the particle system
  52172. * @param directionToUpdate is the direction vector to update with the result
  52173. * @param particle is the particle we are computed the direction for
  52174. */
  52175. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52176. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52177. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52178. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52179. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52180. };
  52181. /**
  52182. * Clones the current emitter and returns a copy of it
  52183. * @returns the new emitter
  52184. */
  52185. SphereDirectedParticleEmitter.prototype.clone = function () {
  52186. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52187. BABYLON.Tools.DeepCopy(this, newOne);
  52188. return newOne;
  52189. };
  52190. /**
  52191. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52192. * @param effect defines the update shader
  52193. */
  52194. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52195. effect.setFloat("radius", this.radius);
  52196. effect.setVector3("direction1", this.direction1);
  52197. effect.setVector3("direction2", this.direction2);
  52198. };
  52199. /**
  52200. * Returns a string to use to update the GPU particles update shader
  52201. * @returns a string containng the defines string
  52202. */
  52203. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52204. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52205. };
  52206. /**
  52207. * Returns the string "SphereDirectedParticleEmitter"
  52208. * @returns a string containing the class name
  52209. */
  52210. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52211. return "SphereDirectedParticleEmitter";
  52212. };
  52213. /**
  52214. * Serializes the particle system to a JSON object.
  52215. * @returns the JSON object
  52216. */
  52217. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52218. var serializationObject = _super.prototype.serialize.call(this);
  52219. ;
  52220. serializationObject.direction1 = this.direction1.asArray();
  52221. ;
  52222. serializationObject.direction2 = this.direction2.asArray();
  52223. ;
  52224. return serializationObject;
  52225. };
  52226. /**
  52227. * Parse properties from a JSON object
  52228. * @param serializationObject defines the JSON object
  52229. */
  52230. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52231. _super.prototype.parse.call(this, serializationObject);
  52232. this.direction1.copyFrom(serializationObject.direction1);
  52233. this.direction2.copyFrom(serializationObject.direction2);
  52234. };
  52235. return SphereDirectedParticleEmitter;
  52236. }(SphereParticleEmitter));
  52237. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52238. })(BABYLON || (BABYLON = {}));
  52239. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52240. var BABYLON;
  52241. (function (BABYLON) {
  52242. /**
  52243. * Represents one particle of a solid particle system.
  52244. * @see SolidParticleSystem
  52245. */
  52246. var SolidParticle = /** @class */ (function () {
  52247. /**
  52248. * Creates a Solid Particle object.
  52249. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52250. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52251. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52252. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52253. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52254. * @param shapeId (integer) is the model shape identifier in the SPS.
  52255. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52256. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52257. */
  52258. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52259. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52260. /**
  52261. * particle global index
  52262. */
  52263. this.idx = 0;
  52264. /**
  52265. * The color of the particle
  52266. */
  52267. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52268. /**
  52269. * The world space position of the particle.
  52270. */
  52271. this.position = BABYLON.Vector3.Zero();
  52272. /**
  52273. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52274. */
  52275. this.rotation = BABYLON.Vector3.Zero();
  52276. /**
  52277. * The scaling of the particle.
  52278. */
  52279. this.scaling = BABYLON.Vector3.One();
  52280. /**
  52281. * The uvs of the particle.
  52282. */
  52283. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52284. /**
  52285. * The current speed of the particle.
  52286. */
  52287. this.velocity = BABYLON.Vector3.Zero();
  52288. /**
  52289. * The pivot point in the particle local space.
  52290. */
  52291. this.pivot = BABYLON.Vector3.Zero();
  52292. /**
  52293. * Must the particle be translated from its pivot point in its local space ?
  52294. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52295. * Default : false
  52296. */
  52297. this.translateFromPivot = false;
  52298. /**
  52299. * Is the particle active or not ?
  52300. */
  52301. this.alive = true;
  52302. /**
  52303. * Is the particle visible or not ?
  52304. */
  52305. this.isVisible = true;
  52306. /**
  52307. * Index of this particle in the global "positions" array (Internal use)
  52308. */
  52309. this._pos = 0;
  52310. /**
  52311. * Index of this particle in the global "indices" array (Internal use)
  52312. */
  52313. this._ind = 0;
  52314. /**
  52315. * ModelShape id of this particle
  52316. */
  52317. this.shapeId = 0;
  52318. /**
  52319. * Index of the particle in its shape id (Internal use)
  52320. */
  52321. this.idxInShape = 0;
  52322. /**
  52323. * Still set as invisible in order to skip useless computations (Internal use)
  52324. */
  52325. this._stillInvisible = false;
  52326. /**
  52327. * Last computed particle rotation matrix
  52328. */
  52329. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52330. /**
  52331. * Parent particle Id, if any.
  52332. * Default null.
  52333. */
  52334. this.parentId = null;
  52335. /**
  52336. * Internal global position in the SPS.
  52337. */
  52338. this._globalPosition = BABYLON.Vector3.Zero();
  52339. this.idx = particleIndex;
  52340. this._pos = positionIndex;
  52341. this._ind = indiceIndex;
  52342. this._model = model;
  52343. this.shapeId = shapeId;
  52344. this.idxInShape = idxInShape;
  52345. this._sps = sps;
  52346. if (modelBoundingInfo) {
  52347. this._modelBoundingInfo = modelBoundingInfo;
  52348. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52349. }
  52350. }
  52351. Object.defineProperty(SolidParticle.prototype, "scale", {
  52352. /**
  52353. * Legacy support, changed scale to scaling
  52354. */
  52355. get: function () {
  52356. return this.scaling;
  52357. },
  52358. /**
  52359. * Legacy support, changed scale to scaling
  52360. */
  52361. set: function (scale) {
  52362. this.scaling = scale;
  52363. },
  52364. enumerable: true,
  52365. configurable: true
  52366. });
  52367. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52368. /**
  52369. * Legacy support, changed quaternion to rotationQuaternion
  52370. */
  52371. get: function () {
  52372. return this.rotationQuaternion;
  52373. },
  52374. /**
  52375. * Legacy support, changed quaternion to rotationQuaternion
  52376. */
  52377. set: function (q) {
  52378. this.rotationQuaternion = q;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. /**
  52384. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52385. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52386. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52387. * @returns true if it intersects
  52388. */
  52389. SolidParticle.prototype.intersectsMesh = function (target) {
  52390. if (!this._boundingInfo || !target._boundingInfo) {
  52391. return false;
  52392. }
  52393. if (this._sps._bSphereOnly) {
  52394. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52395. }
  52396. return this._boundingInfo.intersects(target._boundingInfo, false);
  52397. };
  52398. return SolidParticle;
  52399. }());
  52400. BABYLON.SolidParticle = SolidParticle;
  52401. /**
  52402. * Represents the shape of the model used by one particle of a solid particle system.
  52403. * SPS internal tool, don't use it manually.
  52404. * @see SolidParticleSystem
  52405. */
  52406. var ModelShape = /** @class */ (function () {
  52407. /**
  52408. * 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.
  52409. * SPS internal tool, don't use it manually.
  52410. * @ignore
  52411. */
  52412. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52413. /**
  52414. * length of the shape in the model indices array (internal use)
  52415. */
  52416. this._indicesLength = 0;
  52417. this.shapeID = id;
  52418. this._shape = shape;
  52419. this._indicesLength = indicesLength;
  52420. this._shapeUV = shapeUV;
  52421. this._positionFunction = posFunction;
  52422. this._vertexFunction = vtxFunction;
  52423. }
  52424. return ModelShape;
  52425. }());
  52426. BABYLON.ModelShape = ModelShape;
  52427. /**
  52428. * Represents a Depth Sorted Particle in the solid particle system.
  52429. * @see SolidParticleSystem
  52430. */
  52431. var DepthSortedParticle = /** @class */ (function () {
  52432. function DepthSortedParticle() {
  52433. /**
  52434. * Index of the particle in the "indices" array
  52435. */
  52436. this.ind = 0;
  52437. /**
  52438. * Length of the particle shape in the "indices" array
  52439. */
  52440. this.indicesLength = 0;
  52441. /**
  52442. * Squared distance from the particle to the camera
  52443. */
  52444. this.sqDistance = 0.0;
  52445. }
  52446. return DepthSortedParticle;
  52447. }());
  52448. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52449. })(BABYLON || (BABYLON = {}));
  52450. //# sourceMappingURL=babylon.solidParticle.js.map
  52451. var BABYLON;
  52452. (function (BABYLON) {
  52453. /**
  52454. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52455. *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.
  52456. * The SPS is also a particle system. It provides some methods to manage the particles.
  52457. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52458. *
  52459. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52460. */
  52461. var SolidParticleSystem = /** @class */ (function () {
  52462. /**
  52463. * Creates a SPS (Solid Particle System) object.
  52464. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52465. * @param scene (Scene) is the scene in which the SPS is added.
  52466. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52467. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52468. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52469. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52470. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52471. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52472. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52473. */
  52474. function SolidParticleSystem(name, scene, options) {
  52475. /**
  52476. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52477. * Example : var p = SPS.particles[i];
  52478. */
  52479. this.particles = new Array();
  52480. /**
  52481. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52482. */
  52483. this.nbParticles = 0;
  52484. /**
  52485. * If the particles must ever face the camera (default false). Useful for planar particles.
  52486. */
  52487. this.billboard = false;
  52488. /**
  52489. * Recompute normals when adding a shape
  52490. */
  52491. this.recomputeNormals = true;
  52492. /**
  52493. * This a counter ofr your own usage. It's not set by any SPS functions.
  52494. */
  52495. this.counter = 0;
  52496. /**
  52497. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52498. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52499. */
  52500. this.vars = {};
  52501. /**
  52502. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52503. */
  52504. this._bSphereOnly = false;
  52505. /**
  52506. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52507. */
  52508. this._bSphereRadiusFactor = 1.0;
  52509. this._positions = new Array();
  52510. this._indices = new Array();
  52511. this._normals = new Array();
  52512. this._colors = new Array();
  52513. this._uvs = new Array();
  52514. this._index = 0; // indices index
  52515. this._updatable = true;
  52516. this._pickable = false;
  52517. this._isVisibilityBoxLocked = false;
  52518. this._alwaysVisible = false;
  52519. this._depthSort = false;
  52520. this._shapeCounter = 0;
  52521. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52522. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52523. this._computeParticleColor = true;
  52524. this._computeParticleTexture = true;
  52525. this._computeParticleRotation = true;
  52526. this._computeParticleVertex = false;
  52527. this._computeBoundingBox = false;
  52528. this._depthSortParticles = true;
  52529. this._cam_axisZ = BABYLON.Vector3.Zero();
  52530. this._cam_axisY = BABYLON.Vector3.Zero();
  52531. this._cam_axisX = BABYLON.Vector3.Zero();
  52532. this._axisZ = BABYLON.Axis.Z;
  52533. this._camDir = BABYLON.Vector3.Zero();
  52534. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52535. this._rotMatrix = new BABYLON.Matrix();
  52536. this._invertMatrix = new BABYLON.Matrix();
  52537. this._rotated = BABYLON.Vector3.Zero();
  52538. this._quaternion = new BABYLON.Quaternion();
  52539. this._vertex = BABYLON.Vector3.Zero();
  52540. this._normal = BABYLON.Vector3.Zero();
  52541. this._yaw = 0.0;
  52542. this._pitch = 0.0;
  52543. this._roll = 0.0;
  52544. this._halfroll = 0.0;
  52545. this._halfpitch = 0.0;
  52546. this._halfyaw = 0.0;
  52547. this._sinRoll = 0.0;
  52548. this._cosRoll = 0.0;
  52549. this._sinPitch = 0.0;
  52550. this._cosPitch = 0.0;
  52551. this._sinYaw = 0.0;
  52552. this._cosYaw = 0.0;
  52553. this._mustUnrotateFixedNormals = false;
  52554. this._minimum = BABYLON.Vector3.Zero();
  52555. this._maximum = BABYLON.Vector3.Zero();
  52556. this._minBbox = BABYLON.Vector3.Zero();
  52557. this._maxBbox = BABYLON.Vector3.Zero();
  52558. this._particlesIntersect = false;
  52559. this._depthSortFunction = function (p1, p2) {
  52560. return (p2.sqDistance - p1.sqDistance);
  52561. };
  52562. this._needs32Bits = false;
  52563. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52564. this._scaledPivot = BABYLON.Vector3.Zero();
  52565. this._particleHasParent = false;
  52566. this.name = name;
  52567. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52568. this._camera = scene.activeCamera;
  52569. this._pickable = options ? options.isPickable : false;
  52570. this._depthSort = options ? options.enableDepthSort : false;
  52571. this._particlesIntersect = options ? options.particleIntersection : false;
  52572. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52573. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52574. if (options && options.updatable) {
  52575. this._updatable = options.updatable;
  52576. }
  52577. else {
  52578. this._updatable = true;
  52579. }
  52580. if (this._pickable) {
  52581. this.pickedParticles = [];
  52582. }
  52583. if (this._depthSort) {
  52584. this.depthSortedParticles = [];
  52585. }
  52586. }
  52587. /**
  52588. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52589. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52590. * @returns the created mesh
  52591. */
  52592. SolidParticleSystem.prototype.buildMesh = function () {
  52593. if (this.nbParticles === 0) {
  52594. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52595. this.addShape(triangle, 1);
  52596. triangle.dispose();
  52597. }
  52598. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52599. this._positions32 = new Float32Array(this._positions);
  52600. this._uvs32 = new Float32Array(this._uvs);
  52601. this._colors32 = new Float32Array(this._colors);
  52602. if (this.recomputeNormals) {
  52603. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52604. }
  52605. this._normals32 = new Float32Array(this._normals);
  52606. this._fixedNormal32 = new Float32Array(this._normals);
  52607. if (this._mustUnrotateFixedNormals) {
  52608. this._unrotateFixedNormals();
  52609. }
  52610. var vertexData = new BABYLON.VertexData();
  52611. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52612. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52613. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52614. if (this._uvs32) {
  52615. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52616. ;
  52617. }
  52618. if (this._colors32) {
  52619. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52620. }
  52621. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52622. vertexData.applyToMesh(mesh, this._updatable);
  52623. this.mesh = mesh;
  52624. this.mesh.isPickable = this._pickable;
  52625. // free memory
  52626. if (!this._depthSort) {
  52627. this._indices = null;
  52628. }
  52629. this._positions = null;
  52630. this._normals = null;
  52631. this._uvs = null;
  52632. this._colors = null;
  52633. if (!this._updatable) {
  52634. this.particles.length = 0;
  52635. }
  52636. return mesh;
  52637. };
  52638. /**
  52639. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52640. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52641. * Thus the particles generated from `digest()` have their property `position` set yet.
  52642. * @param mesh ( Mesh ) is the mesh to be digested
  52643. * @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
  52644. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52645. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52646. * @returns the current SPS
  52647. */
  52648. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52649. var size = (options && options.facetNb) || 1;
  52650. var number = (options && options.number) || 0;
  52651. var delta = (options && options.delta) || 0;
  52652. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52653. var meshInd = mesh.getIndices();
  52654. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52655. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52656. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52657. var f = 0; // facet counter
  52658. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52659. // compute size from number
  52660. if (number) {
  52661. number = (number > totalFacets) ? totalFacets : number;
  52662. size = Math.round(totalFacets / number);
  52663. delta = 0;
  52664. }
  52665. else {
  52666. size = (size > totalFacets) ? totalFacets : size;
  52667. }
  52668. var facetPos = []; // submesh positions
  52669. var facetInd = []; // submesh indices
  52670. var facetUV = []; // submesh UV
  52671. var facetCol = []; // submesh colors
  52672. var barycenter = BABYLON.Vector3.Zero();
  52673. var sizeO = size;
  52674. while (f < totalFacets) {
  52675. size = sizeO + Math.floor((1 + delta) * Math.random());
  52676. if (f > totalFacets - size) {
  52677. size = totalFacets - f;
  52678. }
  52679. // reset temp arrays
  52680. facetPos.length = 0;
  52681. facetInd.length = 0;
  52682. facetUV.length = 0;
  52683. facetCol.length = 0;
  52684. // iterate over "size" facets
  52685. var fi = 0;
  52686. for (var j = f * 3; j < (f + size) * 3; j++) {
  52687. facetInd.push(fi);
  52688. var i = meshInd[j];
  52689. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52690. if (meshUV) {
  52691. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52692. }
  52693. if (meshCol) {
  52694. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52695. }
  52696. fi++;
  52697. }
  52698. // create a model shape for each single particle
  52699. var idx = this.nbParticles;
  52700. var shape = this._posToShape(facetPos);
  52701. var shapeUV = this._uvsToShapeUV(facetUV);
  52702. // compute the barycenter of the shape
  52703. var v;
  52704. for (v = 0; v < shape.length; v++) {
  52705. barycenter.addInPlace(shape[v]);
  52706. }
  52707. barycenter.scaleInPlace(1 / shape.length);
  52708. // shift the shape from its barycenter to the origin
  52709. for (v = 0; v < shape.length; v++) {
  52710. shape[v].subtractInPlace(barycenter);
  52711. }
  52712. var bInfo;
  52713. if (this._particlesIntersect) {
  52714. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52715. }
  52716. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52717. // add the particle in the SPS
  52718. var currentPos = this._positions.length;
  52719. var currentInd = this._indices.length;
  52720. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52721. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52722. // initialize the particle position
  52723. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52724. this._index += shape.length;
  52725. idx++;
  52726. this.nbParticles++;
  52727. this._shapeCounter++;
  52728. f += size;
  52729. }
  52730. return this;
  52731. };
  52732. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52733. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52734. var index = 0;
  52735. var idx = 0;
  52736. for (var p = 0; p < this.particles.length; p++) {
  52737. this._particle = this.particles[p];
  52738. this._shape = this._particle._model._shape;
  52739. if (this._particle.rotationQuaternion) {
  52740. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52741. }
  52742. else {
  52743. this._yaw = this._particle.rotation.y;
  52744. this._pitch = this._particle.rotation.x;
  52745. this._roll = this._particle.rotation.z;
  52746. this._quaternionRotationYPR();
  52747. }
  52748. this._quaternionToRotationMatrix();
  52749. this._rotMatrix.invertToRef(this._invertMatrix);
  52750. for (var pt = 0; pt < this._shape.length; pt++) {
  52751. idx = index + pt * 3;
  52752. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52753. this._fixedNormal32[idx] = this._normal.x;
  52754. this._fixedNormal32[idx + 1] = this._normal.y;
  52755. this._fixedNormal32[idx + 2] = this._normal.z;
  52756. }
  52757. index = idx + 3;
  52758. }
  52759. };
  52760. //reset copy
  52761. SolidParticleSystem.prototype._resetCopy = function () {
  52762. this._copy.position.x = 0;
  52763. this._copy.position.y = 0;
  52764. this._copy.position.z = 0;
  52765. this._copy.rotation.x = 0;
  52766. this._copy.rotation.y = 0;
  52767. this._copy.rotation.z = 0;
  52768. this._copy.rotationQuaternion = null;
  52769. this._copy.scaling.x = 1.0;
  52770. this._copy.scaling.y = 1.0;
  52771. this._copy.scaling.z = 1.0;
  52772. this._copy.uvs.x = 0;
  52773. this._copy.uvs.y = 0;
  52774. this._copy.uvs.z = 1.0;
  52775. this._copy.uvs.w = 1.0;
  52776. this._copy.color = null;
  52777. this._copy.translateFromPivot = false;
  52778. };
  52779. // _meshBuilder : inserts the shape model in the global SPS mesh
  52780. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52781. var i;
  52782. var u = 0;
  52783. var c = 0;
  52784. var n = 0;
  52785. this._resetCopy();
  52786. if (options && options.positionFunction) {
  52787. options.positionFunction(this._copy, idx, idxInShape);
  52788. this._mustUnrotateFixedNormals = true;
  52789. }
  52790. if (this._copy.rotationQuaternion) {
  52791. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52792. }
  52793. else {
  52794. this._yaw = this._copy.rotation.y;
  52795. this._pitch = this._copy.rotation.x;
  52796. this._roll = this._copy.rotation.z;
  52797. this._quaternionRotationYPR();
  52798. }
  52799. this._quaternionToRotationMatrix();
  52800. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52801. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52802. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52803. if (this._copy.translateFromPivot) {
  52804. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52805. }
  52806. else {
  52807. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52808. }
  52809. for (i = 0; i < shape.length; i++) {
  52810. this._vertex.x = shape[i].x;
  52811. this._vertex.y = shape[i].y;
  52812. this._vertex.z = shape[i].z;
  52813. if (options && options.vertexFunction) {
  52814. options.vertexFunction(this._copy, this._vertex, i);
  52815. }
  52816. this._vertex.x *= this._copy.scaling.x;
  52817. this._vertex.y *= this._copy.scaling.y;
  52818. this._vertex.z *= this._copy.scaling.z;
  52819. this._vertex.x -= this._scaledPivot.x;
  52820. this._vertex.y -= this._scaledPivot.y;
  52821. this._vertex.z -= this._scaledPivot.z;
  52822. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52823. this._rotated.addInPlace(this._pivotBackTranslation);
  52824. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52825. if (meshUV) {
  52826. 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);
  52827. u += 2;
  52828. }
  52829. if (this._copy.color) {
  52830. this._color = this._copy.color;
  52831. }
  52832. else if (meshCol && meshCol[c] !== undefined) {
  52833. this._color.r = meshCol[c];
  52834. this._color.g = meshCol[c + 1];
  52835. this._color.b = meshCol[c + 2];
  52836. this._color.a = meshCol[c + 3];
  52837. }
  52838. else {
  52839. this._color.r = 1.0;
  52840. this._color.g = 1.0;
  52841. this._color.b = 1.0;
  52842. this._color.a = 1.0;
  52843. }
  52844. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52845. c += 4;
  52846. if (!this.recomputeNormals && meshNor) {
  52847. this._normal.x = meshNor[n];
  52848. this._normal.y = meshNor[n + 1];
  52849. this._normal.z = meshNor[n + 2];
  52850. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52851. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52852. n += 3;
  52853. }
  52854. }
  52855. for (i = 0; i < meshInd.length; i++) {
  52856. var current_ind = p + meshInd[i];
  52857. indices.push(current_ind);
  52858. if (current_ind > 65535) {
  52859. this._needs32Bits = true;
  52860. }
  52861. }
  52862. if (this._pickable) {
  52863. var nbfaces = meshInd.length / 3;
  52864. for (i = 0; i < nbfaces; i++) {
  52865. this.pickedParticles.push({ idx: idx, faceId: i });
  52866. }
  52867. }
  52868. if (this._depthSort) {
  52869. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52870. }
  52871. return this._copy;
  52872. };
  52873. // returns a shape array from positions array
  52874. SolidParticleSystem.prototype._posToShape = function (positions) {
  52875. var shape = [];
  52876. for (var i = 0; i < positions.length; i += 3) {
  52877. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52878. }
  52879. return shape;
  52880. };
  52881. // returns a shapeUV array from a Vector4 uvs
  52882. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52883. var shapeUV = [];
  52884. if (uvs) {
  52885. for (var i = 0; i < uvs.length; i++)
  52886. shapeUV.push(uvs[i]);
  52887. }
  52888. return shapeUV;
  52889. };
  52890. // adds a new particle object in the particles array
  52891. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52892. if (bInfo === void 0) { bInfo = null; }
  52893. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52894. this.particles.push(sp);
  52895. return sp;
  52896. };
  52897. /**
  52898. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52899. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52900. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52901. * @param nb (positive integer) the number of particles to be created from this model
  52902. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52903. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52904. * @returns the number of shapes in the system
  52905. */
  52906. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52907. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52908. var meshInd = mesh.getIndices();
  52909. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52910. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52911. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52912. var bbInfo;
  52913. if (this._particlesIntersect) {
  52914. bbInfo = mesh.getBoundingInfo();
  52915. }
  52916. var shape = this._posToShape(meshPos);
  52917. var shapeUV = this._uvsToShapeUV(meshUV);
  52918. var posfunc = options ? options.positionFunction : null;
  52919. var vtxfunc = options ? options.vertexFunction : null;
  52920. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52921. // particles
  52922. var sp;
  52923. var currentCopy;
  52924. var idx = this.nbParticles;
  52925. for (var i = 0; i < nb; i++) {
  52926. var currentPos = this._positions.length;
  52927. var currentInd = this._indices.length;
  52928. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52929. if (this._updatable) {
  52930. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52931. sp.position.copyFrom(currentCopy.position);
  52932. sp.rotation.copyFrom(currentCopy.rotation);
  52933. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52934. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52935. }
  52936. if (currentCopy.color && sp.color) {
  52937. sp.color.copyFrom(currentCopy.color);
  52938. }
  52939. sp.scaling.copyFrom(currentCopy.scaling);
  52940. sp.uvs.copyFrom(currentCopy.uvs);
  52941. }
  52942. this._index += shape.length;
  52943. idx++;
  52944. }
  52945. this.nbParticles += nb;
  52946. this._shapeCounter++;
  52947. return this._shapeCounter - 1;
  52948. };
  52949. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52950. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52951. this._resetCopy();
  52952. if (particle._model._positionFunction) {
  52953. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52954. }
  52955. if (this._copy.rotationQuaternion) {
  52956. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52957. }
  52958. else {
  52959. this._yaw = this._copy.rotation.y;
  52960. this._pitch = this._copy.rotation.x;
  52961. this._roll = this._copy.rotation.z;
  52962. this._quaternionRotationYPR();
  52963. }
  52964. this._quaternionToRotationMatrix();
  52965. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52966. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52967. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52968. if (this._copy.translateFromPivot) {
  52969. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52970. }
  52971. else {
  52972. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52973. }
  52974. this._shape = particle._model._shape;
  52975. for (var pt = 0; pt < this._shape.length; pt++) {
  52976. this._vertex.x = this._shape[pt].x;
  52977. this._vertex.y = this._shape[pt].y;
  52978. this._vertex.z = this._shape[pt].z;
  52979. if (particle._model._vertexFunction) {
  52980. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52981. }
  52982. this._vertex.x *= this._copy.scaling.x;
  52983. this._vertex.y *= this._copy.scaling.y;
  52984. this._vertex.z *= this._copy.scaling.z;
  52985. this._vertex.x -= this._scaledPivot.x;
  52986. this._vertex.y -= this._scaledPivot.y;
  52987. this._vertex.z -= this._scaledPivot.z;
  52988. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52989. this._rotated.addInPlace(this._pivotBackTranslation);
  52990. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52991. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52992. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52993. }
  52994. particle.position.x = 0.0;
  52995. particle.position.y = 0.0;
  52996. particle.position.z = 0.0;
  52997. particle.rotation.x = 0.0;
  52998. particle.rotation.y = 0.0;
  52999. particle.rotation.z = 0.0;
  53000. particle.rotationQuaternion = null;
  53001. particle.scaling.x = 1.0;
  53002. particle.scaling.y = 1.0;
  53003. particle.scaling.z = 1.0;
  53004. particle.uvs.x = 0.0;
  53005. particle.uvs.y = 0.0;
  53006. particle.uvs.z = 1.0;
  53007. particle.uvs.w = 1.0;
  53008. particle.pivot.x = 0.0;
  53009. particle.pivot.y = 0.0;
  53010. particle.pivot.z = 0.0;
  53011. particle.translateFromPivot = false;
  53012. particle.parentId = null;
  53013. };
  53014. /**
  53015. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53016. * @returns the SPS.
  53017. */
  53018. SolidParticleSystem.prototype.rebuildMesh = function () {
  53019. for (var p = 0; p < this.particles.length; p++) {
  53020. this._rebuildParticle(this.particles[p]);
  53021. }
  53022. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53023. return this;
  53024. };
  53025. /**
  53026. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53027. * This method calls `updateParticle()` for each particle of the SPS.
  53028. * For an animated SPS, it is usually called within the render loop.
  53029. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53030. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53031. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53032. * @returns the SPS.
  53033. */
  53034. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53035. if (start === void 0) { start = 0; }
  53036. if (end === void 0) { end = this.nbParticles - 1; }
  53037. if (update === void 0) { update = true; }
  53038. if (!this._updatable) {
  53039. return this;
  53040. }
  53041. // custom beforeUpdate
  53042. this.beforeUpdateParticles(start, end, update);
  53043. this._cam_axisX.x = 1.0;
  53044. this._cam_axisX.y = 0.0;
  53045. this._cam_axisX.z = 0.0;
  53046. this._cam_axisY.x = 0.0;
  53047. this._cam_axisY.y = 1.0;
  53048. this._cam_axisY.z = 0.0;
  53049. this._cam_axisZ.x = 0.0;
  53050. this._cam_axisZ.y = 0.0;
  53051. this._cam_axisZ.z = 1.0;
  53052. // cases when the World Matrix is to be computed first
  53053. if (this.billboard || this._depthSort) {
  53054. this.mesh.computeWorldMatrix(true);
  53055. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53056. }
  53057. // if the particles will always face the camera
  53058. if (this.billboard) {
  53059. // compute the camera position and un-rotate it by the current mesh rotation
  53060. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53061. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53062. this._cam_axisZ.normalize();
  53063. // same for camera up vector extracted from the cam view matrix
  53064. var view = this._camera.getViewMatrix(true);
  53065. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53066. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53067. this._cam_axisY.normalize();
  53068. this._cam_axisX.normalize();
  53069. }
  53070. // if depthSort, compute the camera global position in the mesh local system
  53071. if (this._depthSort) {
  53072. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53073. }
  53074. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53075. var idx = 0; // current position index in the global array positions32
  53076. var index = 0; // position start index in the global array positions32 of the current particle
  53077. var colidx = 0; // current color index in the global array colors32
  53078. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53079. var uvidx = 0; // current uv index in the global array uvs32
  53080. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53081. var pt = 0; // current index in the particle model shape
  53082. if (this.mesh.isFacetDataEnabled) {
  53083. this._computeBoundingBox = true;
  53084. }
  53085. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53086. if (this._computeBoundingBox) {
  53087. if (start == 0 && end == this.nbParticles - 1) {
  53088. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53089. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53090. }
  53091. else {
  53092. if (this.mesh._boundingInfo) {
  53093. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53094. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53095. }
  53096. }
  53097. }
  53098. // particle loop
  53099. index = this.particles[start]._pos;
  53100. var vpos = (index / 3) | 0;
  53101. colorIndex = vpos * 4;
  53102. uvIndex = vpos * 2;
  53103. for (var p = start; p <= end; p++) {
  53104. this._particle = this.particles[p];
  53105. this._shape = this._particle._model._shape;
  53106. this._shapeUV = this._particle._model._shapeUV;
  53107. // call to custom user function to update the particle properties
  53108. this.updateParticle(this._particle);
  53109. // camera-particle distance for depth sorting
  53110. if (this._depthSort && this._depthSortParticles) {
  53111. var dsp = this.depthSortedParticles[p];
  53112. dsp.ind = this._particle._ind;
  53113. dsp.indicesLength = this._particle._model._indicesLength;
  53114. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53115. }
  53116. // skip the computations for inactive or already invisible particles
  53117. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53118. // increment indexes for the next particle
  53119. pt = this._shape.length;
  53120. index += pt * 3;
  53121. colorIndex += pt * 4;
  53122. uvIndex += pt * 2;
  53123. continue;
  53124. }
  53125. if (this._particle.isVisible) {
  53126. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53127. this._particleHasParent = (this._particle.parentId !== null);
  53128. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53129. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53130. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53131. // particle rotation matrix
  53132. if (this.billboard) {
  53133. this._particle.rotation.x = 0.0;
  53134. this._particle.rotation.y = 0.0;
  53135. }
  53136. if (this._computeParticleRotation || this.billboard) {
  53137. if (this._particle.rotationQuaternion) {
  53138. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53139. }
  53140. else {
  53141. this._yaw = this._particle.rotation.y;
  53142. this._pitch = this._particle.rotation.x;
  53143. this._roll = this._particle.rotation.z;
  53144. this._quaternionRotationYPR();
  53145. }
  53146. this._quaternionToRotationMatrix();
  53147. }
  53148. if (this._particleHasParent) {
  53149. this._parent = this.particles[this._particle.parentId];
  53150. 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];
  53151. 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];
  53152. 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];
  53153. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53154. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53155. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53156. if (this._computeParticleRotation || this.billboard) {
  53157. 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];
  53158. 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];
  53159. 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];
  53160. 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];
  53161. 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];
  53162. 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];
  53163. 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];
  53164. 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];
  53165. 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];
  53166. }
  53167. }
  53168. else {
  53169. this._particle._globalPosition.x = this._particle.position.x;
  53170. this._particle._globalPosition.y = this._particle.position.y;
  53171. this._particle._globalPosition.z = this._particle.position.z;
  53172. if (this._computeParticleRotation || this.billboard) {
  53173. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53174. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53175. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53176. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53177. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53178. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53179. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53180. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53181. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53182. }
  53183. }
  53184. if (this._particle.translateFromPivot) {
  53185. this._pivotBackTranslation.x = 0.0;
  53186. this._pivotBackTranslation.y = 0.0;
  53187. this._pivotBackTranslation.z = 0.0;
  53188. }
  53189. else {
  53190. this._pivotBackTranslation.x = this._scaledPivot.x;
  53191. this._pivotBackTranslation.y = this._scaledPivot.y;
  53192. this._pivotBackTranslation.z = this._scaledPivot.z;
  53193. }
  53194. // particle vertex loop
  53195. for (pt = 0; pt < this._shape.length; pt++) {
  53196. idx = index + pt * 3;
  53197. colidx = colorIndex + pt * 4;
  53198. uvidx = uvIndex + pt * 2;
  53199. this._vertex.x = this._shape[pt].x;
  53200. this._vertex.y = this._shape[pt].y;
  53201. this._vertex.z = this._shape[pt].z;
  53202. if (this._computeParticleVertex) {
  53203. this.updateParticleVertex(this._particle, this._vertex, pt);
  53204. }
  53205. // positions
  53206. this._vertex.x *= this._particle.scaling.x;
  53207. this._vertex.y *= this._particle.scaling.y;
  53208. this._vertex.z *= this._particle.scaling.z;
  53209. this._vertex.x -= this._scaledPivot.x;
  53210. this._vertex.y -= this._scaledPivot.y;
  53211. this._vertex.z -= this._scaledPivot.z;
  53212. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53213. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53214. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53215. this._rotated.x += this._pivotBackTranslation.x;
  53216. this._rotated.y += this._pivotBackTranslation.y;
  53217. this._rotated.z += this._pivotBackTranslation.z;
  53218. 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;
  53219. 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;
  53220. 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;
  53221. if (this._computeBoundingBox) {
  53222. if (this._positions32[idx] < this._minimum.x) {
  53223. this._minimum.x = this._positions32[idx];
  53224. }
  53225. if (this._positions32[idx] > this._maximum.x) {
  53226. this._maximum.x = this._positions32[idx];
  53227. }
  53228. if (this._positions32[idx + 1] < this._minimum.y) {
  53229. this._minimum.y = this._positions32[idx + 1];
  53230. }
  53231. if (this._positions32[idx + 1] > this._maximum.y) {
  53232. this._maximum.y = this._positions32[idx + 1];
  53233. }
  53234. if (this._positions32[idx + 2] < this._minimum.z) {
  53235. this._minimum.z = this._positions32[idx + 2];
  53236. }
  53237. if (this._positions32[idx + 2] > this._maximum.z) {
  53238. this._maximum.z = this._positions32[idx + 2];
  53239. }
  53240. }
  53241. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53242. if (!this._computeParticleVertex) {
  53243. this._normal.x = this._fixedNormal32[idx];
  53244. this._normal.y = this._fixedNormal32[idx + 1];
  53245. this._normal.z = this._fixedNormal32[idx + 2];
  53246. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53247. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53248. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53249. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53250. 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;
  53251. 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;
  53252. }
  53253. if (this._computeParticleColor && this._particle.color) {
  53254. this._colors32[colidx] = this._particle.color.r;
  53255. this._colors32[colidx + 1] = this._particle.color.g;
  53256. this._colors32[colidx + 2] = this._particle.color.b;
  53257. this._colors32[colidx + 3] = this._particle.color.a;
  53258. }
  53259. if (this._computeParticleTexture) {
  53260. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53261. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53262. }
  53263. }
  53264. }
  53265. else {
  53266. this._particle._stillInvisible = true; // mark the particle as invisible
  53267. for (pt = 0; pt < this._shape.length; pt++) {
  53268. idx = index + pt * 3;
  53269. colidx = colorIndex + pt * 4;
  53270. uvidx = uvIndex + pt * 2;
  53271. this._positions32[idx] = 0.0;
  53272. this._positions32[idx + 1] = 0.0;
  53273. this._positions32[idx + 2] = 0.0;
  53274. this._normals32[idx] = 0.0;
  53275. this._normals32[idx + 1] = 0.0;
  53276. this._normals32[idx + 2] = 0.0;
  53277. if (this._computeParticleColor && this._particle.color) {
  53278. this._colors32[colidx] = this._particle.color.r;
  53279. this._colors32[colidx + 1] = this._particle.color.g;
  53280. this._colors32[colidx + 2] = this._particle.color.b;
  53281. this._colors32[colidx + 3] = this._particle.color.a;
  53282. }
  53283. if (this._computeParticleTexture) {
  53284. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53285. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53286. }
  53287. }
  53288. }
  53289. // if the particle intersections must be computed : update the bbInfo
  53290. if (this._particlesIntersect) {
  53291. var bInfo = this._particle._boundingInfo;
  53292. var bBox = bInfo.boundingBox;
  53293. var bSphere = bInfo.boundingSphere;
  53294. if (!this._bSphereOnly) {
  53295. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53296. for (var b = 0; b < bBox.vectors.length; b++) {
  53297. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53298. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53299. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53300. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53301. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53302. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53303. 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;
  53304. 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;
  53305. 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;
  53306. }
  53307. bBox._update(this.mesh._worldMatrix);
  53308. }
  53309. // place and scale the particle bouding sphere in the SPS local system, then update it
  53310. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53311. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53312. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53313. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53314. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53315. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53316. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53317. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53318. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53319. 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));
  53320. bSphere._update(this.mesh._worldMatrix);
  53321. }
  53322. // increment indexes for the next particle
  53323. index = idx + 3;
  53324. colorIndex = colidx + 4;
  53325. uvIndex = uvidx + 2;
  53326. }
  53327. // if the VBO must be updated
  53328. if (update) {
  53329. if (this._computeParticleColor) {
  53330. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53331. }
  53332. if (this._computeParticleTexture) {
  53333. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53334. }
  53335. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53336. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53337. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53338. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53339. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53340. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53341. for (var i = 0; i < this._normals32.length; i++) {
  53342. this._fixedNormal32[i] = this._normals32[i];
  53343. }
  53344. }
  53345. if (!this.mesh.areNormalsFrozen) {
  53346. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53347. }
  53348. }
  53349. if (this._depthSort && this._depthSortParticles) {
  53350. this.depthSortedParticles.sort(this._depthSortFunction);
  53351. var dspl = this.depthSortedParticles.length;
  53352. var sorted = 0;
  53353. var lind = 0;
  53354. var sind = 0;
  53355. var sid = 0;
  53356. for (sorted = 0; sorted < dspl; sorted++) {
  53357. lind = this.depthSortedParticles[sorted].indicesLength;
  53358. sind = this.depthSortedParticles[sorted].ind;
  53359. for (var i = 0; i < lind; i++) {
  53360. this._indices32[sid] = this._indices[sind + i];
  53361. sid++;
  53362. }
  53363. }
  53364. this.mesh.updateIndices(this._indices32);
  53365. }
  53366. }
  53367. if (this._computeBoundingBox) {
  53368. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53369. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53370. }
  53371. this.afterUpdateParticles(start, end, update);
  53372. return this;
  53373. };
  53374. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53375. this._halfroll = this._roll * 0.5;
  53376. this._halfpitch = this._pitch * 0.5;
  53377. this._halfyaw = this._yaw * 0.5;
  53378. this._sinRoll = Math.sin(this._halfroll);
  53379. this._cosRoll = Math.cos(this._halfroll);
  53380. this._sinPitch = Math.sin(this._halfpitch);
  53381. this._cosPitch = Math.cos(this._halfpitch);
  53382. this._sinYaw = Math.sin(this._halfyaw);
  53383. this._cosYaw = Math.cos(this._halfyaw);
  53384. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53385. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53386. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53387. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53388. };
  53389. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53390. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53391. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53392. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53393. this._rotMatrix.m[3] = 0;
  53394. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53395. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53396. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53397. this._rotMatrix.m[7] = 0;
  53398. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53399. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53400. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53401. this._rotMatrix.m[11] = 0;
  53402. this._rotMatrix.m[12] = 0;
  53403. this._rotMatrix.m[13] = 0;
  53404. this._rotMatrix.m[14] = 0;
  53405. this._rotMatrix.m[15] = 1.0;
  53406. };
  53407. /**
  53408. * Disposes the SPS.
  53409. */
  53410. SolidParticleSystem.prototype.dispose = function () {
  53411. this.mesh.dispose();
  53412. this.vars = null;
  53413. // drop references to internal big arrays for the GC
  53414. this._positions = null;
  53415. this._indices = null;
  53416. this._normals = null;
  53417. this._uvs = null;
  53418. this._colors = null;
  53419. this._indices32 = null;
  53420. this._positions32 = null;
  53421. this._normals32 = null;
  53422. this._fixedNormal32 = null;
  53423. this._uvs32 = null;
  53424. this._colors32 = null;
  53425. this.pickedParticles = null;
  53426. };
  53427. /**
  53428. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53429. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53430. * @returns the SPS.
  53431. */
  53432. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53433. if (!this._isVisibilityBoxLocked) {
  53434. this.mesh.refreshBoundingInfo();
  53435. }
  53436. return this;
  53437. };
  53438. /**
  53439. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53440. * @param size the size (float) of the visibility box
  53441. * note : this doesn't lock the SPS mesh bounding box.
  53442. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53443. */
  53444. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53445. var vis = size / 2;
  53446. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53447. };
  53448. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53449. /**
  53450. * Gets whether the SPS as always visible or not
  53451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53452. */
  53453. get: function () {
  53454. return this._alwaysVisible;
  53455. },
  53456. /**
  53457. * Sets the SPS as always visible or not
  53458. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53459. */
  53460. set: function (val) {
  53461. this._alwaysVisible = val;
  53462. this.mesh.alwaysSelectAsActiveMesh = val;
  53463. },
  53464. enumerable: true,
  53465. configurable: true
  53466. });
  53467. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53468. /**
  53469. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53470. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53471. */
  53472. get: function () {
  53473. return this._isVisibilityBoxLocked;
  53474. },
  53475. /**
  53476. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53477. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53478. */
  53479. set: function (val) {
  53480. this._isVisibilityBoxLocked = val;
  53481. var boundingInfo = this.mesh.getBoundingInfo();
  53482. boundingInfo.isLocked = val;
  53483. },
  53484. enumerable: true,
  53485. configurable: true
  53486. });
  53487. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53488. /**
  53489. * Gets if `setParticles()` computes the particle rotations or not.
  53490. * Default value : true. The SPS is faster when it's set to false.
  53491. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53492. */
  53493. get: function () {
  53494. return this._computeParticleRotation;
  53495. },
  53496. /**
  53497. * Tells to `setParticles()` to compute the particle rotations or not.
  53498. * Default value : true. The SPS is faster when it's set to false.
  53499. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53500. */
  53501. set: function (val) {
  53502. this._computeParticleRotation = val;
  53503. },
  53504. enumerable: true,
  53505. configurable: true
  53506. });
  53507. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53508. /**
  53509. * Gets if `setParticles()` computes the particle colors or not.
  53510. * Default value : true. The SPS is faster when it's set to false.
  53511. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53512. */
  53513. get: function () {
  53514. return this._computeParticleColor;
  53515. },
  53516. /**
  53517. * Tells to `setParticles()` to compute the particle colors or not.
  53518. * Default value : true. The SPS is faster when it's set to false.
  53519. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53520. */
  53521. set: function (val) {
  53522. this._computeParticleColor = val;
  53523. },
  53524. enumerable: true,
  53525. configurable: true
  53526. });
  53527. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53528. /**
  53529. * Gets if `setParticles()` computes the particle textures or not.
  53530. * Default value : true. The SPS is faster when it's set to false.
  53531. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53532. */
  53533. get: function () {
  53534. return this._computeParticleTexture;
  53535. },
  53536. set: function (val) {
  53537. this._computeParticleTexture = val;
  53538. },
  53539. enumerable: true,
  53540. configurable: true
  53541. });
  53542. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53543. /**
  53544. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53545. * Default value : false. The SPS is faster when it's set to false.
  53546. * Note : the particle custom vertex positions aren't stored values.
  53547. */
  53548. get: function () {
  53549. return this._computeParticleVertex;
  53550. },
  53551. /**
  53552. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53553. * Default value : false. The SPS is faster when it's set to false.
  53554. * Note : the particle custom vertex positions aren't stored values.
  53555. */
  53556. set: function (val) {
  53557. this._computeParticleVertex = val;
  53558. },
  53559. enumerable: true,
  53560. configurable: true
  53561. });
  53562. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53563. /**
  53564. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53565. */
  53566. get: function () {
  53567. return this._computeBoundingBox;
  53568. },
  53569. /**
  53570. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53571. */
  53572. set: function (val) {
  53573. this._computeBoundingBox = val;
  53574. },
  53575. enumerable: true,
  53576. configurable: true
  53577. });
  53578. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53579. /**
  53580. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53581. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53582. * Default : `true`
  53583. */
  53584. get: function () {
  53585. return this._depthSortParticles;
  53586. },
  53587. /**
  53588. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53589. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53590. * Default : `true`
  53591. */
  53592. set: function (val) {
  53593. this._depthSortParticles = val;
  53594. },
  53595. enumerable: true,
  53596. configurable: true
  53597. });
  53598. // =======================================================================
  53599. // Particle behavior logic
  53600. // these following methods may be overwritten by the user to fit his needs
  53601. /**
  53602. * This function does nothing. It may be overwritten to set all the particle first values.
  53603. * The SPS doesn't call this function, you may have to call it by your own.
  53604. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53605. */
  53606. SolidParticleSystem.prototype.initParticles = function () {
  53607. };
  53608. /**
  53609. * This function does nothing. It may be overwritten to recycle a particle.
  53610. * The SPS doesn't call this function, you may have to call it by your own.
  53611. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53612. * @param particle The particle to recycle
  53613. * @returns the recycled particle
  53614. */
  53615. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53616. return particle;
  53617. };
  53618. /**
  53619. * Updates a particle : this function should be overwritten by the user.
  53620. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53621. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53622. * @example : just set a particle position or velocity and recycle conditions
  53623. * @param particle The particle to update
  53624. * @returns the updated particle
  53625. */
  53626. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53627. return particle;
  53628. };
  53629. /**
  53630. * Updates a vertex of a particle : it can be overwritten by the user.
  53631. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53632. * @param particle the current particle
  53633. * @param vertex the current index of the current particle
  53634. * @param pt the index of the current vertex in the particle shape
  53635. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53636. * @example : just set a vertex particle position
  53637. * @returns the updated vertex
  53638. */
  53639. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53640. return vertex;
  53641. };
  53642. /**
  53643. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53644. * This does nothing and may be overwritten by the user.
  53645. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53646. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53647. * @param update the boolean update value actually passed to setParticles()
  53648. */
  53649. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53650. };
  53651. /**
  53652. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53653. * This will be passed three parameters.
  53654. * This does nothing and may be overwritten by the user.
  53655. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53656. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53657. * @param update the boolean update value actually passed to setParticles()
  53658. */
  53659. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53660. };
  53661. return SolidParticleSystem;
  53662. }());
  53663. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53664. })(BABYLON || (BABYLON = {}));
  53665. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53666. var BABYLON;
  53667. (function (BABYLON) {
  53668. var ShaderMaterial = /** @class */ (function (_super) {
  53669. __extends(ShaderMaterial, _super);
  53670. function ShaderMaterial(name, scene, shaderPath, options) {
  53671. var _this = _super.call(this, name, scene) || this;
  53672. _this._textures = {};
  53673. _this._textureArrays = {};
  53674. _this._floats = {};
  53675. _this._ints = {};
  53676. _this._floatsArrays = {};
  53677. _this._colors3 = {};
  53678. _this._colors3Arrays = {};
  53679. _this._colors4 = {};
  53680. _this._vectors2 = {};
  53681. _this._vectors3 = {};
  53682. _this._vectors4 = {};
  53683. _this._matrices = {};
  53684. _this._matrices3x3 = {};
  53685. _this._matrices2x2 = {};
  53686. _this._vectors2Arrays = {};
  53687. _this._vectors3Arrays = {};
  53688. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53689. _this._shaderPath = shaderPath;
  53690. options.needAlphaBlending = options.needAlphaBlending || false;
  53691. options.needAlphaTesting = options.needAlphaTesting || false;
  53692. options.attributes = options.attributes || ["position", "normal", "uv"];
  53693. options.uniforms = options.uniforms || ["worldViewProjection"];
  53694. options.uniformBuffers = options.uniformBuffers || [];
  53695. options.samplers = options.samplers || [];
  53696. options.defines = options.defines || [];
  53697. _this._options = options;
  53698. return _this;
  53699. }
  53700. ShaderMaterial.prototype.getClassName = function () {
  53701. return "ShaderMaterial";
  53702. };
  53703. ShaderMaterial.prototype.needAlphaBlending = function () {
  53704. return this._options.needAlphaBlending;
  53705. };
  53706. ShaderMaterial.prototype.needAlphaTesting = function () {
  53707. return this._options.needAlphaTesting;
  53708. };
  53709. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53710. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53711. this._options.uniforms.push(uniformName);
  53712. }
  53713. };
  53714. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53715. if (this._options.samplers.indexOf(name) === -1) {
  53716. this._options.samplers.push(name);
  53717. }
  53718. this._textures[name] = texture;
  53719. return this;
  53720. };
  53721. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53722. if (this._options.samplers.indexOf(name) === -1) {
  53723. this._options.samplers.push(name);
  53724. }
  53725. this._checkUniform(name);
  53726. this._textureArrays[name] = textures;
  53727. return this;
  53728. };
  53729. ShaderMaterial.prototype.setFloat = function (name, value) {
  53730. this._checkUniform(name);
  53731. this._floats[name] = value;
  53732. return this;
  53733. };
  53734. ShaderMaterial.prototype.setInt = function (name, value) {
  53735. this._checkUniform(name);
  53736. this._ints[name] = value;
  53737. return this;
  53738. };
  53739. ShaderMaterial.prototype.setFloats = function (name, value) {
  53740. this._checkUniform(name);
  53741. this._floatsArrays[name] = value;
  53742. return this;
  53743. };
  53744. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53745. this._checkUniform(name);
  53746. this._colors3[name] = value;
  53747. return this;
  53748. };
  53749. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53750. this._checkUniform(name);
  53751. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53752. color.toArray(arr, arr.length);
  53753. return arr;
  53754. }, []);
  53755. return this;
  53756. };
  53757. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53758. this._checkUniform(name);
  53759. this._colors4[name] = value;
  53760. return this;
  53761. };
  53762. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53763. this._checkUniform(name);
  53764. this._vectors2[name] = value;
  53765. return this;
  53766. };
  53767. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53768. this._checkUniform(name);
  53769. this._vectors3[name] = value;
  53770. return this;
  53771. };
  53772. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53773. this._checkUniform(name);
  53774. this._vectors4[name] = value;
  53775. return this;
  53776. };
  53777. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53778. this._checkUniform(name);
  53779. this._matrices[name] = value;
  53780. return this;
  53781. };
  53782. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53783. this._checkUniform(name);
  53784. this._matrices3x3[name] = value;
  53785. return this;
  53786. };
  53787. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53788. this._checkUniform(name);
  53789. this._matrices2x2[name] = value;
  53790. return this;
  53791. };
  53792. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53793. this._checkUniform(name);
  53794. this._vectors2Arrays[name] = value;
  53795. return this;
  53796. };
  53797. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53798. this._checkUniform(name);
  53799. this._vectors3Arrays[name] = value;
  53800. return this;
  53801. };
  53802. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53803. if (!mesh) {
  53804. return true;
  53805. }
  53806. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53807. return false;
  53808. }
  53809. return false;
  53810. };
  53811. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53812. var scene = this.getScene();
  53813. var engine = scene.getEngine();
  53814. if (!this.checkReadyOnEveryCall) {
  53815. if (this._renderId === scene.getRenderId()) {
  53816. if (this._checkCache(scene, mesh, useInstances)) {
  53817. return true;
  53818. }
  53819. }
  53820. }
  53821. // Instances
  53822. var defines = [];
  53823. var attribs = [];
  53824. var fallbacks = new BABYLON.EffectFallbacks();
  53825. if (useInstances) {
  53826. defines.push("#define INSTANCES");
  53827. }
  53828. for (var index = 0; index < this._options.defines.length; index++) {
  53829. defines.push(this._options.defines[index]);
  53830. }
  53831. for (var index = 0; index < this._options.attributes.length; index++) {
  53832. attribs.push(this._options.attributes[index]);
  53833. }
  53834. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53835. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53836. defines.push("#define VERTEXCOLOR");
  53837. }
  53838. // Bones
  53839. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53840. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53841. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53842. if (mesh.numBoneInfluencers > 4) {
  53843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53845. }
  53846. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53847. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53848. fallbacks.addCPUSkinningFallback(0, mesh);
  53849. if (this._options.uniforms.indexOf("mBones") === -1) {
  53850. this._options.uniforms.push("mBones");
  53851. }
  53852. }
  53853. else {
  53854. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53855. }
  53856. // Textures
  53857. for (var name in this._textures) {
  53858. if (!this._textures[name].isReady()) {
  53859. return false;
  53860. }
  53861. }
  53862. // Alpha test
  53863. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53864. defines.push("#define ALPHATEST");
  53865. }
  53866. var previousEffect = this._effect;
  53867. var join = defines.join("\n");
  53868. this._effect = engine.createEffect(this._shaderPath, {
  53869. attributes: attribs,
  53870. uniformsNames: this._options.uniforms,
  53871. uniformBuffersNames: this._options.uniformBuffers,
  53872. samplers: this._options.samplers,
  53873. defines: join,
  53874. fallbacks: fallbacks,
  53875. onCompiled: this.onCompiled,
  53876. onError: this.onError
  53877. }, engine);
  53878. if (!this._effect.isReady()) {
  53879. return false;
  53880. }
  53881. if (previousEffect !== this._effect) {
  53882. scene.resetCachedMaterial();
  53883. }
  53884. this._renderId = scene.getRenderId();
  53885. return true;
  53886. };
  53887. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53888. var scene = this.getScene();
  53889. if (!this._effect) {
  53890. return;
  53891. }
  53892. if (this._options.uniforms.indexOf("world") !== -1) {
  53893. this._effect.setMatrix("world", world);
  53894. }
  53895. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53896. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53897. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53898. }
  53899. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53900. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53901. }
  53902. };
  53903. ShaderMaterial.prototype.bind = function (world, mesh) {
  53904. // Std values
  53905. this.bindOnlyWorldMatrix(world);
  53906. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53907. if (this._options.uniforms.indexOf("view") !== -1) {
  53908. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53909. }
  53910. if (this._options.uniforms.indexOf("projection") !== -1) {
  53911. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53912. }
  53913. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53914. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53915. }
  53916. // Bones
  53917. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53918. var name;
  53919. // Texture
  53920. for (name in this._textures) {
  53921. this._effect.setTexture(name, this._textures[name]);
  53922. }
  53923. // Texture arrays
  53924. for (name in this._textureArrays) {
  53925. this._effect.setTextureArray(name, this._textureArrays[name]);
  53926. }
  53927. // Int
  53928. for (name in this._ints) {
  53929. this._effect.setInt(name, this._ints[name]);
  53930. }
  53931. // Float
  53932. for (name in this._floats) {
  53933. this._effect.setFloat(name, this._floats[name]);
  53934. }
  53935. // Floats
  53936. for (name in this._floatsArrays) {
  53937. this._effect.setArray(name, this._floatsArrays[name]);
  53938. }
  53939. // Color3
  53940. for (name in this._colors3) {
  53941. this._effect.setColor3(name, this._colors3[name]);
  53942. }
  53943. for (name in this._colors3Arrays) {
  53944. this._effect.setArray3(name, this._colors3Arrays[name]);
  53945. }
  53946. // Color4
  53947. for (name in this._colors4) {
  53948. var color = this._colors4[name];
  53949. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53950. }
  53951. // Vector2
  53952. for (name in this._vectors2) {
  53953. this._effect.setVector2(name, this._vectors2[name]);
  53954. }
  53955. // Vector3
  53956. for (name in this._vectors3) {
  53957. this._effect.setVector3(name, this._vectors3[name]);
  53958. }
  53959. // Vector4
  53960. for (name in this._vectors4) {
  53961. this._effect.setVector4(name, this._vectors4[name]);
  53962. }
  53963. // Matrix
  53964. for (name in this._matrices) {
  53965. this._effect.setMatrix(name, this._matrices[name]);
  53966. }
  53967. // Matrix 3x3
  53968. for (name in this._matrices3x3) {
  53969. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53970. }
  53971. // Matrix 2x2
  53972. for (name in this._matrices2x2) {
  53973. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53974. }
  53975. // Vector2Array
  53976. for (name in this._vectors2Arrays) {
  53977. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53978. }
  53979. // Vector3Array
  53980. for (name in this._vectors3Arrays) {
  53981. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53982. }
  53983. }
  53984. this._afterBind(mesh);
  53985. };
  53986. ShaderMaterial.prototype.getActiveTextures = function () {
  53987. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53988. for (var name in this._textures) {
  53989. activeTextures.push(this._textures[name]);
  53990. }
  53991. for (var name in this._textureArrays) {
  53992. var array = this._textureArrays[name];
  53993. for (var index = 0; index < array.length; index++) {
  53994. activeTextures.push(array[index]);
  53995. }
  53996. }
  53997. return activeTextures;
  53998. };
  53999. ShaderMaterial.prototype.hasTexture = function (texture) {
  54000. if (_super.prototype.hasTexture.call(this, texture)) {
  54001. return true;
  54002. }
  54003. for (var name in this._textures) {
  54004. if (this._textures[name] === texture) {
  54005. return true;
  54006. }
  54007. }
  54008. for (var name in this._textureArrays) {
  54009. var array = this._textureArrays[name];
  54010. for (var index = 0; index < array.length; index++) {
  54011. if (array[index] === texture) {
  54012. return true;
  54013. }
  54014. }
  54015. }
  54016. return false;
  54017. };
  54018. ShaderMaterial.prototype.clone = function (name) {
  54019. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54020. return newShaderMaterial;
  54021. };
  54022. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54023. if (forceDisposeTextures) {
  54024. var name;
  54025. for (name in this._textures) {
  54026. this._textures[name].dispose();
  54027. }
  54028. for (name in this._textureArrays) {
  54029. var array = this._textureArrays[name];
  54030. for (var index = 0; index < array.length; index++) {
  54031. array[index].dispose();
  54032. }
  54033. }
  54034. }
  54035. this._textures = {};
  54036. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54037. };
  54038. ShaderMaterial.prototype.serialize = function () {
  54039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54040. serializationObject.customType = "BABYLON.ShaderMaterial";
  54041. serializationObject.options = this._options;
  54042. serializationObject.shaderPath = this._shaderPath;
  54043. var name;
  54044. // Texture
  54045. serializationObject.textures = {};
  54046. for (name in this._textures) {
  54047. serializationObject.textures[name] = this._textures[name].serialize();
  54048. }
  54049. // Texture arrays
  54050. serializationObject.textureArrays = {};
  54051. for (name in this._textureArrays) {
  54052. serializationObject.textureArrays[name] = [];
  54053. var array = this._textureArrays[name];
  54054. for (var index = 0; index < array.length; index++) {
  54055. serializationObject.textureArrays[name].push(array[index].serialize());
  54056. }
  54057. }
  54058. // Float
  54059. serializationObject.floats = {};
  54060. for (name in this._floats) {
  54061. serializationObject.floats[name] = this._floats[name];
  54062. }
  54063. // Float s
  54064. serializationObject.FloatArrays = {};
  54065. for (name in this._floatsArrays) {
  54066. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54067. }
  54068. // Color3
  54069. serializationObject.colors3 = {};
  54070. for (name in this._colors3) {
  54071. serializationObject.colors3[name] = this._colors3[name].asArray();
  54072. }
  54073. // Color3 array
  54074. serializationObject.colors3Arrays = {};
  54075. for (name in this._colors3Arrays) {
  54076. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54077. }
  54078. // Color4
  54079. serializationObject.colors4 = {};
  54080. for (name in this._colors4) {
  54081. serializationObject.colors4[name] = this._colors4[name].asArray();
  54082. }
  54083. // Vector2
  54084. serializationObject.vectors2 = {};
  54085. for (name in this._vectors2) {
  54086. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54087. }
  54088. // Vector3
  54089. serializationObject.vectors3 = {};
  54090. for (name in this._vectors3) {
  54091. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54092. }
  54093. // Vector4
  54094. serializationObject.vectors4 = {};
  54095. for (name in this._vectors4) {
  54096. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54097. }
  54098. // Matrix
  54099. serializationObject.matrices = {};
  54100. for (name in this._matrices) {
  54101. serializationObject.matrices[name] = this._matrices[name].asArray();
  54102. }
  54103. // Matrix 3x3
  54104. serializationObject.matrices3x3 = {};
  54105. for (name in this._matrices3x3) {
  54106. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54107. }
  54108. // Matrix 2x2
  54109. serializationObject.matrices2x2 = {};
  54110. for (name in this._matrices2x2) {
  54111. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54112. }
  54113. // Vector2Array
  54114. serializationObject.vectors2Arrays = {};
  54115. for (name in this._vectors2Arrays) {
  54116. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54117. }
  54118. // Vector3Array
  54119. serializationObject.vectors3Arrays = {};
  54120. for (name in this._vectors3Arrays) {
  54121. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54122. }
  54123. return serializationObject;
  54124. };
  54125. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54126. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54127. var name;
  54128. // Texture
  54129. for (name in source.textures) {
  54130. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54131. }
  54132. // Texture arrays
  54133. for (name in source.textureArrays) {
  54134. var array = source.textureArrays[name];
  54135. var textureArray = new Array();
  54136. for (var index = 0; index < array.length; index++) {
  54137. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54138. }
  54139. material.setTextureArray(name, textureArray);
  54140. }
  54141. // Float
  54142. for (name in source.floats) {
  54143. material.setFloat(name, source.floats[name]);
  54144. }
  54145. // Float s
  54146. for (name in source.floatsArrays) {
  54147. material.setFloats(name, source.floatsArrays[name]);
  54148. }
  54149. // Color3
  54150. for (name in source.colors3) {
  54151. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54152. }
  54153. // Color3 arrays
  54154. for (name in source.colors3Arrays) {
  54155. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54156. if (i % 3 === 0) {
  54157. arr.push([num]);
  54158. }
  54159. else {
  54160. arr[arr.length - 1].push(num);
  54161. }
  54162. return arr;
  54163. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54164. material.setColor3Array(name, colors);
  54165. }
  54166. // Color4
  54167. for (name in source.colors4) {
  54168. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54169. }
  54170. // Vector2
  54171. for (name in source.vectors2) {
  54172. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54173. }
  54174. // Vector3
  54175. for (name in source.vectors3) {
  54176. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54177. }
  54178. // Vector4
  54179. for (name in source.vectors4) {
  54180. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54181. }
  54182. // Matrix
  54183. for (name in source.matrices) {
  54184. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54185. }
  54186. // Matrix 3x3
  54187. for (name in source.matrices3x3) {
  54188. material.setMatrix3x3(name, source.matrices3x3[name]);
  54189. }
  54190. // Matrix 2x2
  54191. for (name in source.matrices2x2) {
  54192. material.setMatrix2x2(name, source.matrices2x2[name]);
  54193. }
  54194. // Vector2Array
  54195. for (name in source.vectors2Arrays) {
  54196. material.setArray2(name, source.vectors2Arrays[name]);
  54197. }
  54198. // Vector3Array
  54199. for (name in source.vectors3Arrays) {
  54200. material.setArray3(name, source.vectors3Arrays[name]);
  54201. }
  54202. return material;
  54203. };
  54204. return ShaderMaterial;
  54205. }(BABYLON.Material));
  54206. BABYLON.ShaderMaterial = ShaderMaterial;
  54207. })(BABYLON || (BABYLON = {}));
  54208. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54209. var BABYLON;
  54210. (function (BABYLON) {
  54211. var GroundMesh = /** @class */ (function (_super) {
  54212. __extends(GroundMesh, _super);
  54213. function GroundMesh(name, scene) {
  54214. var _this = _super.call(this, name, scene) || this;
  54215. _this.generateOctree = false;
  54216. return _this;
  54217. }
  54218. GroundMesh.prototype.getClassName = function () {
  54219. return "GroundMesh";
  54220. };
  54221. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54222. get: function () {
  54223. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54224. },
  54225. enumerable: true,
  54226. configurable: true
  54227. });
  54228. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54229. get: function () {
  54230. return this._subdivisionsX;
  54231. },
  54232. enumerable: true,
  54233. configurable: true
  54234. });
  54235. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54236. get: function () {
  54237. return this._subdivisionsY;
  54238. },
  54239. enumerable: true,
  54240. configurable: true
  54241. });
  54242. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54243. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54244. this._subdivisionsX = chunksCount;
  54245. this._subdivisionsY = chunksCount;
  54246. this.subdivide(chunksCount);
  54247. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54248. };
  54249. /**
  54250. * Returns a height (y) value in the Worl system :
  54251. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54252. * Returns the ground y position if (x, z) are outside the ground surface.
  54253. */
  54254. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54255. var world = this.getWorldMatrix();
  54256. var invMat = BABYLON.Tmp.Matrix[5];
  54257. world.invertToRef(invMat);
  54258. var tmpVect = BABYLON.Tmp.Vector3[8];
  54259. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54260. x = tmpVect.x;
  54261. z = tmpVect.z;
  54262. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54263. return this.position.y;
  54264. }
  54265. if (!this._heightQuads || this._heightQuads.length == 0) {
  54266. this._initHeightQuads();
  54267. this._computeHeightQuads();
  54268. }
  54269. var facet = this._getFacetAt(x, z);
  54270. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54271. // return y in the World system
  54272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54273. return tmpVect.y;
  54274. };
  54275. /**
  54276. * Returns a normalized vector (Vector3) orthogonal to the ground
  54277. * at the ground coordinates (x, z) expressed in the World system.
  54278. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54279. */
  54280. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54281. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54282. this.getNormalAtCoordinatesToRef(x, z, normal);
  54283. return normal;
  54284. };
  54285. /**
  54286. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54287. * at the ground coordinates (x, z) expressed in the World system.
  54288. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54289. * Returns the GroundMesh.
  54290. */
  54291. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54292. var world = this.getWorldMatrix();
  54293. var tmpMat = BABYLON.Tmp.Matrix[5];
  54294. world.invertToRef(tmpMat);
  54295. var tmpVect = BABYLON.Tmp.Vector3[8];
  54296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54297. x = tmpVect.x;
  54298. z = tmpVect.z;
  54299. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54300. return this;
  54301. }
  54302. if (!this._heightQuads || this._heightQuads.length == 0) {
  54303. this._initHeightQuads();
  54304. this._computeHeightQuads();
  54305. }
  54306. var facet = this._getFacetAt(x, z);
  54307. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54308. return this;
  54309. };
  54310. /**
  54311. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54312. * if the ground has been updated.
  54313. * This can be used in the render loop.
  54314. * Returns the GroundMesh.
  54315. */
  54316. GroundMesh.prototype.updateCoordinateHeights = function () {
  54317. if (!this._heightQuads || this._heightQuads.length == 0) {
  54318. this._initHeightQuads();
  54319. }
  54320. this._computeHeightQuads();
  54321. return this;
  54322. };
  54323. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54324. GroundMesh.prototype._getFacetAt = function (x, z) {
  54325. // retrieve col and row from x, z coordinates in the ground local system
  54326. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54327. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54328. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54329. var facet;
  54330. if (z < quad.slope.x * x + quad.slope.y) {
  54331. facet = quad.facet1;
  54332. }
  54333. else {
  54334. facet = quad.facet2;
  54335. }
  54336. return facet;
  54337. };
  54338. // Creates and populates the heightMap array with "facet" elements :
  54339. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54340. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54341. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54342. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54343. // Returns the GroundMesh.
  54344. GroundMesh.prototype._initHeightQuads = function () {
  54345. var subdivisionsX = this._subdivisionsX;
  54346. var subdivisionsY = this._subdivisionsY;
  54347. this._heightQuads = new Array();
  54348. for (var row = 0; row < subdivisionsY; row++) {
  54349. for (var col = 0; col < subdivisionsX; col++) {
  54350. 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) };
  54351. this._heightQuads[row * subdivisionsX + col] = quad;
  54352. }
  54353. }
  54354. return this;
  54355. };
  54356. // Compute each quad element values and update the the heightMap array :
  54357. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54358. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54359. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54360. // Returns the GroundMesh.
  54361. GroundMesh.prototype._computeHeightQuads = function () {
  54362. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54363. if (!positions) {
  54364. return this;
  54365. }
  54366. var v1 = BABYLON.Tmp.Vector3[3];
  54367. var v2 = BABYLON.Tmp.Vector3[2];
  54368. var v3 = BABYLON.Tmp.Vector3[1];
  54369. var v4 = BABYLON.Tmp.Vector3[0];
  54370. var v1v2 = BABYLON.Tmp.Vector3[4];
  54371. var v1v3 = BABYLON.Tmp.Vector3[5];
  54372. var v1v4 = BABYLON.Tmp.Vector3[6];
  54373. var norm1 = BABYLON.Tmp.Vector3[7];
  54374. var norm2 = BABYLON.Tmp.Vector3[8];
  54375. var i = 0;
  54376. var j = 0;
  54377. var k = 0;
  54378. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54379. var h = 0;
  54380. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54381. var d2 = 0;
  54382. var subdivisionsX = this._subdivisionsX;
  54383. var subdivisionsY = this._subdivisionsY;
  54384. for (var row = 0; row < subdivisionsY; row++) {
  54385. for (var col = 0; col < subdivisionsX; col++) {
  54386. i = col * 3;
  54387. j = row * (subdivisionsX + 1) * 3;
  54388. k = (row + 1) * (subdivisionsX + 1) * 3;
  54389. v1.x = positions[j + i];
  54390. v1.y = positions[j + i + 1];
  54391. v1.z = positions[j + i + 2];
  54392. v2.x = positions[j + i + 3];
  54393. v2.y = positions[j + i + 4];
  54394. v2.z = positions[j + i + 5];
  54395. v3.x = positions[k + i];
  54396. v3.y = positions[k + i + 1];
  54397. v3.z = positions[k + i + 2];
  54398. v4.x = positions[k + i + 3];
  54399. v4.y = positions[k + i + 4];
  54400. v4.z = positions[k + i + 5];
  54401. // 2D slope V1V4
  54402. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54403. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54404. // facet equations :
  54405. // we compute each facet normal vector
  54406. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54407. // we compute the value d by applying the equation to v1 which belongs to the plane
  54408. // then we store the facet equation in a Vector4
  54409. v2.subtractToRef(v1, v1v2);
  54410. v3.subtractToRef(v1, v1v3);
  54411. v4.subtractToRef(v1, v1v4);
  54412. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54413. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54414. norm1.normalize();
  54415. norm2.normalize();
  54416. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54417. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54418. var quad = this._heightQuads[row * subdivisionsX + col];
  54419. quad.slope.copyFromFloats(cd, h);
  54420. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54421. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54422. }
  54423. }
  54424. return this;
  54425. };
  54426. GroundMesh.prototype.serialize = function (serializationObject) {
  54427. _super.prototype.serialize.call(this, serializationObject);
  54428. serializationObject.subdivisionsX = this._subdivisionsX;
  54429. serializationObject.subdivisionsY = this._subdivisionsY;
  54430. serializationObject.minX = this._minX;
  54431. serializationObject.maxX = this._maxX;
  54432. serializationObject.minZ = this._minZ;
  54433. serializationObject.maxZ = this._maxZ;
  54434. serializationObject.width = this._width;
  54435. serializationObject.height = this._height;
  54436. };
  54437. GroundMesh.Parse = function (parsedMesh, scene) {
  54438. var result = new GroundMesh(parsedMesh.name, scene);
  54439. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54440. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54441. result._minX = parsedMesh.minX;
  54442. result._maxX = parsedMesh.maxX;
  54443. result._minZ = parsedMesh.minZ;
  54444. result._maxZ = parsedMesh.maxZ;
  54445. result._width = parsedMesh.width;
  54446. result._height = parsedMesh.height;
  54447. return result;
  54448. };
  54449. return GroundMesh;
  54450. }(BABYLON.Mesh));
  54451. BABYLON.GroundMesh = GroundMesh;
  54452. })(BABYLON || (BABYLON = {}));
  54453. //# sourceMappingURL=babylon.groundMesh.js.map
  54454. var BABYLON;
  54455. (function (BABYLON) {
  54456. /**
  54457. * Creates an instance based on a source mesh.
  54458. */
  54459. var InstancedMesh = /** @class */ (function (_super) {
  54460. __extends(InstancedMesh, _super);
  54461. function InstancedMesh(name, source) {
  54462. var _this = _super.call(this, name, source.getScene()) || this;
  54463. source.instances.push(_this);
  54464. _this._sourceMesh = source;
  54465. _this.position.copyFrom(source.position);
  54466. _this.rotation.copyFrom(source.rotation);
  54467. _this.scaling.copyFrom(source.scaling);
  54468. if (source.rotationQuaternion) {
  54469. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54470. }
  54471. _this.infiniteDistance = source.infiniteDistance;
  54472. _this.setPivotMatrix(source.getPivotMatrix());
  54473. _this.refreshBoundingInfo();
  54474. _this._syncSubMeshes();
  54475. return _this;
  54476. }
  54477. /**
  54478. * Returns the string "InstancedMesh".
  54479. */
  54480. InstancedMesh.prototype.getClassName = function () {
  54481. return "InstancedMesh";
  54482. };
  54483. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54484. // Methods
  54485. get: function () {
  54486. return this._sourceMesh.receiveShadows;
  54487. },
  54488. enumerable: true,
  54489. configurable: true
  54490. });
  54491. Object.defineProperty(InstancedMesh.prototype, "material", {
  54492. get: function () {
  54493. return this._sourceMesh.material;
  54494. },
  54495. enumerable: true,
  54496. configurable: true
  54497. });
  54498. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54499. get: function () {
  54500. return this._sourceMesh.visibility;
  54501. },
  54502. enumerable: true,
  54503. configurable: true
  54504. });
  54505. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54506. get: function () {
  54507. return this._sourceMesh.skeleton;
  54508. },
  54509. enumerable: true,
  54510. configurable: true
  54511. });
  54512. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54513. get: function () {
  54514. return this._sourceMesh.renderingGroupId;
  54515. },
  54516. set: function (value) {
  54517. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  54518. return;
  54519. }
  54520. //no-op with warning
  54521. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  54522. },
  54523. enumerable: true,
  54524. configurable: true
  54525. });
  54526. /**
  54527. * Returns the total number of vertices (integer).
  54528. */
  54529. InstancedMesh.prototype.getTotalVertices = function () {
  54530. return this._sourceMesh.getTotalVertices();
  54531. };
  54532. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54533. get: function () {
  54534. return this._sourceMesh;
  54535. },
  54536. enumerable: true,
  54537. configurable: true
  54538. });
  54539. /**
  54540. * Is this node ready to be used/rendered
  54541. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54542. * @return {boolean} is it ready
  54543. */
  54544. InstancedMesh.prototype.isReady = function (completeCheck) {
  54545. if (completeCheck === void 0) { completeCheck = false; }
  54546. return this._sourceMesh.isReady(completeCheck, true);
  54547. };
  54548. /**
  54549. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54550. */
  54551. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54552. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54553. };
  54554. /**
  54555. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54556. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54557. * The `data` are either a numeric array either a Float32Array.
  54558. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54559. * 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).
  54560. * Note that a new underlying VertexBuffer object is created each call.
  54561. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54562. *
  54563. * Possible `kind` values :
  54564. * - BABYLON.VertexBuffer.PositionKind
  54565. * - BABYLON.VertexBuffer.UVKind
  54566. * - BABYLON.VertexBuffer.UV2Kind
  54567. * - BABYLON.VertexBuffer.UV3Kind
  54568. * - BABYLON.VertexBuffer.UV4Kind
  54569. * - BABYLON.VertexBuffer.UV5Kind
  54570. * - BABYLON.VertexBuffer.UV6Kind
  54571. * - BABYLON.VertexBuffer.ColorKind
  54572. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54573. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54574. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54575. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54576. *
  54577. * Returns the Mesh.
  54578. */
  54579. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54580. if (this.sourceMesh) {
  54581. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54582. }
  54583. return this.sourceMesh;
  54584. };
  54585. /**
  54586. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54587. * If the mesh has no geometry, it is simply returned as it is.
  54588. * The `data` are either a numeric array either a Float32Array.
  54589. * No new underlying VertexBuffer object is created.
  54590. * 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.
  54591. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54592. *
  54593. * Possible `kind` values :
  54594. * - BABYLON.VertexBuffer.PositionKind
  54595. * - BABYLON.VertexBuffer.UVKind
  54596. * - BABYLON.VertexBuffer.UV2Kind
  54597. * - BABYLON.VertexBuffer.UV3Kind
  54598. * - BABYLON.VertexBuffer.UV4Kind
  54599. * - BABYLON.VertexBuffer.UV5Kind
  54600. * - BABYLON.VertexBuffer.UV6Kind
  54601. * - BABYLON.VertexBuffer.ColorKind
  54602. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54603. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54604. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54605. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54606. *
  54607. * Returns the Mesh.
  54608. */
  54609. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54610. if (this.sourceMesh) {
  54611. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54612. }
  54613. return this.sourceMesh;
  54614. };
  54615. /**
  54616. * Sets the mesh indices.
  54617. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54618. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54619. * This method creates a new index buffer each call.
  54620. * Returns the Mesh.
  54621. */
  54622. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54623. if (totalVertices === void 0) { totalVertices = null; }
  54624. if (this.sourceMesh) {
  54625. this.sourceMesh.setIndices(indices, totalVertices);
  54626. }
  54627. return this.sourceMesh;
  54628. };
  54629. /**
  54630. * Boolean : True if the mesh owns the requested kind of data.
  54631. */
  54632. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54633. return this._sourceMesh.isVerticesDataPresent(kind);
  54634. };
  54635. /**
  54636. * Returns an array of indices (IndicesArray).
  54637. */
  54638. InstancedMesh.prototype.getIndices = function () {
  54639. return this._sourceMesh.getIndices();
  54640. };
  54641. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54642. get: function () {
  54643. return this._sourceMesh._positions;
  54644. },
  54645. enumerable: true,
  54646. configurable: true
  54647. });
  54648. /**
  54649. * Sets a new updated BoundingInfo to the mesh.
  54650. * Returns the mesh.
  54651. */
  54652. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54653. var meshBB = this._sourceMesh.getBoundingInfo();
  54654. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54655. this._updateBoundingInfo();
  54656. return this;
  54657. };
  54658. InstancedMesh.prototype._preActivate = function () {
  54659. if (this._currentLOD) {
  54660. this._currentLOD._preActivate();
  54661. }
  54662. return this;
  54663. };
  54664. InstancedMesh.prototype._activate = function (renderId) {
  54665. if (this._currentLOD) {
  54666. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54667. }
  54668. return this;
  54669. };
  54670. /**
  54671. * Returns the current associated LOD AbstractMesh.
  54672. */
  54673. InstancedMesh.prototype.getLOD = function (camera) {
  54674. if (!camera) {
  54675. return this;
  54676. }
  54677. var boundingInfo = this.getBoundingInfo();
  54678. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54679. if (this._currentLOD === this.sourceMesh) {
  54680. return this;
  54681. }
  54682. return this._currentLOD;
  54683. };
  54684. InstancedMesh.prototype._syncSubMeshes = function () {
  54685. this.releaseSubMeshes();
  54686. if (this._sourceMesh.subMeshes) {
  54687. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54688. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54689. }
  54690. }
  54691. return this;
  54692. };
  54693. InstancedMesh.prototype._generatePointsArray = function () {
  54694. return this._sourceMesh._generatePointsArray();
  54695. };
  54696. /**
  54697. * Creates a new InstancedMesh from the current mesh.
  54698. * - name (string) : the cloned mesh name
  54699. * - newParent (optional Node) : the optional Node to parent the clone to.
  54700. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54701. *
  54702. * Returns the clone.
  54703. */
  54704. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54705. var result = this._sourceMesh.createInstance(name);
  54706. // Deep copy
  54707. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54708. // Bounding info
  54709. this.refreshBoundingInfo();
  54710. // Parent
  54711. if (newParent) {
  54712. result.parent = newParent;
  54713. }
  54714. if (!doNotCloneChildren) {
  54715. // Children
  54716. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54717. var mesh = this.getScene().meshes[index];
  54718. if (mesh.parent === this) {
  54719. mesh.clone(mesh.name, result);
  54720. }
  54721. }
  54722. }
  54723. result.computeWorldMatrix(true);
  54724. return result;
  54725. };
  54726. /**
  54727. * Disposes the InstancedMesh.
  54728. * Returns nothing.
  54729. */
  54730. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54731. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54732. // Remove from mesh
  54733. var index = this._sourceMesh.instances.indexOf(this);
  54734. this._sourceMesh.instances.splice(index, 1);
  54735. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54736. };
  54737. return InstancedMesh;
  54738. }(BABYLON.AbstractMesh));
  54739. BABYLON.InstancedMesh = InstancedMesh;
  54740. })(BABYLON || (BABYLON = {}));
  54741. //# sourceMappingURL=babylon.instancedMesh.js.map
  54742. var BABYLON;
  54743. (function (BABYLON) {
  54744. var LinesMesh = /** @class */ (function (_super) {
  54745. __extends(LinesMesh, _super);
  54746. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54747. if (scene === void 0) { scene = null; }
  54748. if (parent === void 0) { parent = null; }
  54749. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54750. _this.useVertexColor = useVertexColor;
  54751. _this.useVertexAlpha = useVertexAlpha;
  54752. _this.color = new BABYLON.Color3(1, 1, 1);
  54753. _this.alpha = 1;
  54754. if (source) {
  54755. _this.color = source.color.clone();
  54756. _this.alpha = source.alpha;
  54757. _this.useVertexColor = source.useVertexColor;
  54758. _this.useVertexAlpha = source.useVertexAlpha;
  54759. }
  54760. _this._intersectionThreshold = 0.1;
  54761. var defines = [];
  54762. var options = {
  54763. attributes: [BABYLON.VertexBuffer.PositionKind],
  54764. uniforms: ["world", "viewProjection"],
  54765. needAlphaBlending: true,
  54766. defines: defines
  54767. };
  54768. if (useVertexAlpha === false) {
  54769. options.needAlphaBlending = false;
  54770. }
  54771. if (!useVertexColor) {
  54772. options.uniforms.push("color");
  54773. }
  54774. else {
  54775. options.defines.push("#define VERTEXCOLOR");
  54776. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54777. }
  54778. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54779. return _this;
  54780. }
  54781. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54782. /**
  54783. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54784. * This margin is expressed in world space coordinates, so its value may vary.
  54785. * Default value is 0.1
  54786. * @returns the intersection Threshold value.
  54787. */
  54788. get: function () {
  54789. return this._intersectionThreshold;
  54790. },
  54791. /**
  54792. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54793. * This margin is expressed in world space coordinates, so its value may vary.
  54794. * @param value the new threshold to apply
  54795. */
  54796. set: function (value) {
  54797. if (this._intersectionThreshold === value) {
  54798. return;
  54799. }
  54800. this._intersectionThreshold = value;
  54801. if (this.geometry) {
  54802. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54803. }
  54804. },
  54805. enumerable: true,
  54806. configurable: true
  54807. });
  54808. /**
  54809. * Returns the string "LineMesh"
  54810. */
  54811. LinesMesh.prototype.getClassName = function () {
  54812. return "LinesMesh";
  54813. };
  54814. Object.defineProperty(LinesMesh.prototype, "material", {
  54815. get: function () {
  54816. return this._colorShader;
  54817. },
  54818. set: function (value) {
  54819. // Do nothing
  54820. },
  54821. enumerable: true,
  54822. configurable: true
  54823. });
  54824. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54825. get: function () {
  54826. return false;
  54827. },
  54828. enumerable: true,
  54829. configurable: true
  54830. });
  54831. LinesMesh.prototype.createInstance = function (name) {
  54832. throw new Error("LinesMeshes do not support createInstance.");
  54833. };
  54834. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54835. if (!this._geometry) {
  54836. return this;
  54837. }
  54838. // VBOs
  54839. this._geometry._bind(this._colorShader.getEffect());
  54840. // Color
  54841. if (!this.useVertexColor) {
  54842. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54843. }
  54844. return this;
  54845. };
  54846. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54847. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54848. return this;
  54849. }
  54850. var engine = this.getScene().getEngine();
  54851. // Draw order
  54852. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54853. return this;
  54854. };
  54855. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54856. this._colorShader.dispose();
  54857. _super.prototype.dispose.call(this, doNotRecurse);
  54858. };
  54859. /**
  54860. * Returns a new LineMesh object cloned from the current one.
  54861. */
  54862. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54863. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54864. };
  54865. return LinesMesh;
  54866. }(BABYLON.Mesh));
  54867. BABYLON.LinesMesh = LinesMesh;
  54868. })(BABYLON || (BABYLON = {}));
  54869. //# sourceMappingURL=babylon.linesMesh.js.map
  54870. var BABYLON;
  54871. (function (BABYLON) {
  54872. var MeshBuilder = /** @class */ (function () {
  54873. function MeshBuilder() {
  54874. }
  54875. MeshBuilder.updateSideOrientation = function (orientation) {
  54876. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54877. return BABYLON.Mesh.DOUBLESIDE;
  54878. }
  54879. if (orientation === undefined || orientation === null) {
  54880. return BABYLON.Mesh.FRONTSIDE;
  54881. }
  54882. return orientation;
  54883. };
  54884. /**
  54885. * Creates a box mesh.
  54886. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54887. * The parameter `size` sets the size (float) of each box side (default 1).
  54888. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54889. * 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).
  54890. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54892. * 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).
  54893. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54895. */
  54896. MeshBuilder.CreateBox = function (name, options, scene) {
  54897. if (scene === void 0) { scene = null; }
  54898. var box = new BABYLON.Mesh(name, scene);
  54899. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54900. box._originalBuilderSideOrientation = options.sideOrientation;
  54901. var vertexData = BABYLON.VertexData.CreateBox(options);
  54902. vertexData.applyToMesh(box, options.updatable);
  54903. return box;
  54904. };
  54905. /**
  54906. * Creates a sphere mesh.
  54907. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54908. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54909. * 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`).
  54910. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54911. * 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
  54912. * 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).
  54913. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54914. * 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).
  54915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54917. */
  54918. MeshBuilder.CreateSphere = function (name, options, scene) {
  54919. var sphere = new BABYLON.Mesh(name, scene);
  54920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54921. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54922. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54923. vertexData.applyToMesh(sphere, options.updatable);
  54924. return sphere;
  54925. };
  54926. /**
  54927. * Creates a plane polygonal mesh. By default, this is a disc.
  54928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54929. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54930. * 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.
  54931. * 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
  54932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54933. * 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).
  54934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54936. */
  54937. MeshBuilder.CreateDisc = function (name, options, scene) {
  54938. if (scene === void 0) { scene = null; }
  54939. var disc = new BABYLON.Mesh(name, scene);
  54940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54941. disc._originalBuilderSideOrientation = options.sideOrientation;
  54942. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54943. vertexData.applyToMesh(disc, options.updatable);
  54944. return disc;
  54945. };
  54946. /**
  54947. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54949. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54950. * 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`).
  54951. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54952. * 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.
  54953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54954. * 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).
  54955. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54957. */
  54958. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54959. var sphere = new BABYLON.Mesh(name, scene);
  54960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54961. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54962. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54963. vertexData.applyToMesh(sphere, options.updatable);
  54964. return sphere;
  54965. };
  54966. ;
  54967. /**
  54968. * Creates a ribbon mesh.
  54969. * 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.
  54970. *
  54971. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54972. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54973. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54974. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54975. * 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.
  54976. * 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.
  54977. * 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
  54978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54979. * 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).
  54980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54981. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54982. * 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.
  54983. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54984. * 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
  54985. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54986. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54988. */
  54989. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54990. if (scene === void 0) { scene = null; }
  54991. var pathArray = options.pathArray;
  54992. var closeArray = options.closeArray;
  54993. var closePath = options.closePath;
  54994. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54995. var instance = options.instance;
  54996. var updatable = options.updatable;
  54997. if (instance) {
  54998. // positionFunction : ribbon case
  54999. // only pathArray and sideOrientation parameters are taken into account for positions update
  55000. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55001. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55002. var positionFunction = function (positions) {
  55003. var minlg = pathArray[0].length;
  55004. var i = 0;
  55005. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55006. for (var si = 1; si <= ns; si++) {
  55007. for (var p = 0; p < pathArray.length; p++) {
  55008. var path = pathArray[p];
  55009. var l = path.length;
  55010. minlg = (minlg < l) ? minlg : l;
  55011. var j = 0;
  55012. while (j < minlg) {
  55013. positions[i] = path[j].x;
  55014. positions[i + 1] = path[j].y;
  55015. positions[i + 2] = path[j].z;
  55016. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55017. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55018. }
  55019. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55020. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55021. }
  55022. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55023. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55024. }
  55025. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55026. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55027. }
  55028. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55029. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55030. }
  55031. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55032. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55033. }
  55034. j++;
  55035. i += 3;
  55036. }
  55037. if (instance._closePath) {
  55038. positions[i] = path[0].x;
  55039. positions[i + 1] = path[0].y;
  55040. positions[i + 2] = path[0].z;
  55041. i += 3;
  55042. }
  55043. }
  55044. }
  55045. };
  55046. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55047. positionFunction(positions);
  55048. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55049. instance._boundingInfo.update(instance._worldMatrix);
  55050. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55051. if (options.colors) {
  55052. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55053. for (var c = 0; c < options.colors.length; c++) {
  55054. colors[c * 4] = options.colors[c].r;
  55055. colors[c * 4 + 1] = options.colors[c].g;
  55056. colors[c * 4 + 2] = options.colors[c].b;
  55057. colors[c * 4 + 3] = options.colors[c].a;
  55058. }
  55059. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55060. }
  55061. if (options.uvs) {
  55062. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55063. for (var i = 0; i < options.uvs.length; i++) {
  55064. uvs[i * 2] = options.uvs[i].x;
  55065. uvs[i * 2 + 1] = options.uvs[i].y;
  55066. }
  55067. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55068. }
  55069. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55070. var indices = instance.getIndices();
  55071. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55072. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55073. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55074. if (instance._closePath) {
  55075. var indexFirst = 0;
  55076. var indexLast = 0;
  55077. for (var p = 0; p < pathArray.length; p++) {
  55078. indexFirst = instance._idx[p] * 3;
  55079. if (p + 1 < pathArray.length) {
  55080. indexLast = (instance._idx[p + 1] - 1) * 3;
  55081. }
  55082. else {
  55083. indexLast = normals.length - 3;
  55084. }
  55085. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55086. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55087. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55088. normals[indexLast] = normals[indexFirst];
  55089. normals[indexLast + 1] = normals[indexFirst + 1];
  55090. normals[indexLast + 2] = normals[indexFirst + 2];
  55091. }
  55092. }
  55093. if (!(instance.areNormalsFrozen)) {
  55094. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55095. }
  55096. }
  55097. return instance;
  55098. }
  55099. else {
  55100. var ribbon = new BABYLON.Mesh(name, scene);
  55101. ribbon._originalBuilderSideOrientation = sideOrientation;
  55102. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55103. if (closePath) {
  55104. ribbon._idx = vertexData._idx;
  55105. }
  55106. ribbon._closePath = closePath;
  55107. ribbon._closeArray = closeArray;
  55108. vertexData.applyToMesh(ribbon, updatable);
  55109. return ribbon;
  55110. }
  55111. };
  55112. /**
  55113. * Creates a cylinder or a cone mesh.
  55114. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55115. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55116. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55117. * 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.
  55118. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55119. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55120. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55121. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55122. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55123. * 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).
  55124. * 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
  55125. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55126. * 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
  55127. * 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.
  55128. * If `enclose` is false, a ring surface is one element.
  55129. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55130. * 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
  55131. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55132. * 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).
  55133. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55135. */
  55136. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55137. var cylinder = new BABYLON.Mesh(name, scene);
  55138. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55139. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55140. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55141. vertexData.applyToMesh(cylinder, options.updatable);
  55142. return cylinder;
  55143. };
  55144. /**
  55145. * Creates a torus mesh.
  55146. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55147. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55148. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55149. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55151. * 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).
  55152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55154. */
  55155. MeshBuilder.CreateTorus = function (name, options, scene) {
  55156. var torus = new BABYLON.Mesh(name, scene);
  55157. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55158. torus._originalBuilderSideOrientation = options.sideOrientation;
  55159. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55160. vertexData.applyToMesh(torus, options.updatable);
  55161. return torus;
  55162. };
  55163. /**
  55164. * Creates a torus knot mesh.
  55165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55166. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55167. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55168. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55169. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55171. * 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).
  55172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55174. */
  55175. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55176. var torusKnot = new BABYLON.Mesh(name, scene);
  55177. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55178. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55179. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55180. vertexData.applyToMesh(torusKnot, options.updatable);
  55181. return torusKnot;
  55182. };
  55183. /**
  55184. * Creates a line system mesh.
  55185. * A line system is a pool of many lines gathered in a single mesh.
  55186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55187. * 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.
  55188. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55189. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55190. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  55191. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55192. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55193. * 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
  55194. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55196. */
  55197. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55198. var instance = options.instance;
  55199. var lines = options.lines;
  55200. var colors = options.colors;
  55201. if (instance) {
  55202. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55203. var vertexColor;
  55204. var lineColors;
  55205. if (colors) {
  55206. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55207. }
  55208. var i = 0;
  55209. var c = 0;
  55210. for (var l = 0; l < lines.length; l++) {
  55211. var points = lines[l];
  55212. for (var p = 0; p < points.length; p++) {
  55213. positions[i] = points[p].x;
  55214. positions[i + 1] = points[p].y;
  55215. positions[i + 2] = points[p].z;
  55216. if (colors && vertexColor) {
  55217. lineColors = colors[l];
  55218. vertexColor[c] = lineColors[p].r;
  55219. vertexColor[c + 1] = lineColors[p].g;
  55220. vertexColor[c + 2] = lineColors[p].b;
  55221. vertexColor[c + 3] = lineColors[p].a;
  55222. c += 4;
  55223. }
  55224. i += 3;
  55225. }
  55226. }
  55227. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55228. if (colors && vertexColor) {
  55229. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55230. }
  55231. return instance;
  55232. }
  55233. // line system creation
  55234. var useVertexColor = (colors) ? true : false;
  55235. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55236. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55237. vertexData.applyToMesh(lineSystem, options.updatable);
  55238. return lineSystem;
  55239. };
  55240. /**
  55241. * Creates a line mesh.
  55242. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55243. * 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.
  55244. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55245. * The parameter `points` is an array successive Vector3.
  55246. * 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
  55247. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55248. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55249. * When updating an instance, remember that only point positions can change, not the number of points.
  55250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55251. */
  55252. MeshBuilder.CreateLines = function (name, options, scene) {
  55253. if (scene === void 0) { scene = null; }
  55254. var colors = (options.colors) ? [options.colors] : null;
  55255. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55256. return lines;
  55257. };
  55258. /**
  55259. * Creates a dashed line mesh.
  55260. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55261. * 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.
  55262. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55263. * The parameter `points` is an array successive Vector3.
  55264. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55265. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55266. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55267. * 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
  55268. * When updating an instance, remember that only point positions can change, not the number of points.
  55269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55270. */
  55271. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55272. if (scene === void 0) { scene = null; }
  55273. var points = options.points;
  55274. var instance = options.instance;
  55275. var gapSize = options.gapSize || 1;
  55276. var dashSize = options.dashSize || 3;
  55277. if (instance) {
  55278. var positionFunction = function (positions) {
  55279. var curvect = BABYLON.Vector3.Zero();
  55280. var nbSeg = positions.length / 6;
  55281. var lg = 0;
  55282. var nb = 0;
  55283. var shft = 0;
  55284. var dashshft = 0;
  55285. var curshft = 0;
  55286. var p = 0;
  55287. var i = 0;
  55288. var j = 0;
  55289. for (i = 0; i < points.length - 1; i++) {
  55290. points[i + 1].subtractToRef(points[i], curvect);
  55291. lg += curvect.length();
  55292. }
  55293. shft = lg / nbSeg;
  55294. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55295. for (i = 0; i < points.length - 1; i++) {
  55296. points[i + 1].subtractToRef(points[i], curvect);
  55297. nb = Math.floor(curvect.length() / shft);
  55298. curvect.normalize();
  55299. j = 0;
  55300. while (j < nb && p < positions.length) {
  55301. curshft = shft * j;
  55302. positions[p] = points[i].x + curshft * curvect.x;
  55303. positions[p + 1] = points[i].y + curshft * curvect.y;
  55304. positions[p + 2] = points[i].z + curshft * curvect.z;
  55305. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55306. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55307. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55308. p += 6;
  55309. j++;
  55310. }
  55311. }
  55312. while (p < positions.length) {
  55313. positions[p] = points[i].x;
  55314. positions[p + 1] = points[i].y;
  55315. positions[p + 2] = points[i].z;
  55316. p += 3;
  55317. }
  55318. };
  55319. instance.updateMeshPositions(positionFunction, false);
  55320. return instance;
  55321. }
  55322. // dashed lines creation
  55323. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55324. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55325. vertexData.applyToMesh(dashedLines, options.updatable);
  55326. dashedLines.dashSize = dashSize;
  55327. dashedLines.gapSize = gapSize;
  55328. return dashedLines;
  55329. };
  55330. /**
  55331. * Creates an extruded shape mesh.
  55332. * 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.
  55333. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55334. *
  55335. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55336. * 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
  55337. * extruded along the Z axis.
  55338. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55339. * 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.
  55340. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55341. * 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
  55342. * 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
  55343. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55344. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55345. * 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).
  55346. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55347. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55349. */
  55350. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55351. if (scene === void 0) { scene = null; }
  55352. var path = options.path;
  55353. var shape = options.shape;
  55354. var scale = options.scale || 1;
  55355. var rotation = options.rotation || 0;
  55356. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55357. var updatable = options.updatable;
  55358. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55359. var instance = options.instance || null;
  55360. var invertUV = options.invertUV || false;
  55361. 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);
  55362. };
  55363. /**
  55364. * Creates an custom extruded shape mesh.
  55365. * 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.
  55366. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55367. *
  55368. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55369. * 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
  55370. * extruded along the Z axis.
  55371. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55372. * 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
  55373. * and the distance of this point from the begining of the path :
  55374. * ```javascript
  55375. * var rotationFunction = function(i, distance) {
  55376. * // do things
  55377. * return rotationValue; }
  55378. * ```
  55379. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55380. * 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
  55381. * and the distance of this point from the begining of the path :
  55382. * ```javascript
  55383. * var scaleFunction = function(i, distance) {
  55384. * // do things
  55385. * return scaleValue;}
  55386. * ```
  55387. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55388. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55389. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55390. * 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
  55391. * 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
  55392. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55394. * 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).
  55395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55396. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55398. */
  55399. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55400. var path = options.path;
  55401. var shape = options.shape;
  55402. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55403. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55404. var ribbonCloseArray = options.ribbonCloseArray || false;
  55405. var ribbonClosePath = options.ribbonClosePath || false;
  55406. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55407. var updatable = options.updatable;
  55408. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55409. var instance = options.instance;
  55410. var invertUV = options.invertUV || false;
  55411. 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);
  55412. };
  55413. /**
  55414. * Creates lathe mesh.
  55415. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55416. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55417. *
  55418. * 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
  55419. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55420. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55421. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55422. * 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.
  55423. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55424. * 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
  55425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55426. * 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).
  55427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55428. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55430. */
  55431. MeshBuilder.CreateLathe = function (name, options, scene) {
  55432. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55433. var closed = (options.closed === undefined) ? true : options.closed;
  55434. var shape = options.shape;
  55435. var radius = options.radius || 1;
  55436. var tessellation = options.tessellation || 64;
  55437. var updatable = options.updatable;
  55438. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55439. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55440. var pi2 = Math.PI * 2;
  55441. var paths = new Array();
  55442. var invertUV = options.invertUV || false;
  55443. var i = 0;
  55444. var p = 0;
  55445. var step = pi2 / tessellation * arc;
  55446. var rotated;
  55447. var path = new Array();
  55448. ;
  55449. for (i = 0; i <= tessellation; i++) {
  55450. var path = [];
  55451. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55452. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55453. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55454. }
  55455. for (p = 0; p < shape.length; p++) {
  55456. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55457. path.push(rotated);
  55458. }
  55459. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55460. 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));
  55461. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55462. }
  55463. paths.push(path);
  55464. }
  55465. // lathe ribbon
  55466. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55467. return lathe;
  55468. };
  55469. /**
  55470. * Creates a plane mesh.
  55471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55472. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55473. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55474. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55476. * 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).
  55477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55479. */
  55480. MeshBuilder.CreatePlane = function (name, options, scene) {
  55481. var plane = new BABYLON.Mesh(name, scene);
  55482. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55483. plane._originalBuilderSideOrientation = options.sideOrientation;
  55484. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55485. vertexData.applyToMesh(plane, options.updatable);
  55486. if (options.sourcePlane) {
  55487. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55488. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55489. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55490. plane.rotate(vectorProduct, product);
  55491. }
  55492. return plane;
  55493. };
  55494. /**
  55495. * Creates a ground mesh.
  55496. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55497. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55498. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55500. */
  55501. MeshBuilder.CreateGround = function (name, options, scene) {
  55502. var ground = new BABYLON.GroundMesh(name, scene);
  55503. ground._setReady(false);
  55504. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55505. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55506. ground._width = options.width || 1;
  55507. ground._height = options.height || 1;
  55508. ground._maxX = ground._width / 2;
  55509. ground._maxZ = ground._height / 2;
  55510. ground._minX = -ground._maxX;
  55511. ground._minZ = -ground._maxZ;
  55512. var vertexData = BABYLON.VertexData.CreateGround(options);
  55513. vertexData.applyToMesh(ground, options.updatable);
  55514. ground._setReady(true);
  55515. return ground;
  55516. };
  55517. /**
  55518. * Creates a tiled ground mesh.
  55519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55520. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55521. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55522. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55523. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55524. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55525. * numbers of subdivisions on the ground width and height of each tile.
  55526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55527. */
  55528. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55529. var tiledGround = new BABYLON.Mesh(name, scene);
  55530. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55531. vertexData.applyToMesh(tiledGround, options.updatable);
  55532. return tiledGround;
  55533. };
  55534. /**
  55535. * Creates a ground mesh from a height map.
  55536. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55538. * The parameter `url` sets the URL of the height map image resource.
  55539. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55540. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55541. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55542. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55543. * 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.
  55544. * 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).
  55545. * This function is passed the newly built mesh :
  55546. * ```javascript
  55547. * function(mesh) { // do things
  55548. * return; }
  55549. * ```
  55550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55551. */
  55552. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55553. var width = options.width || 10.0;
  55554. var height = options.height || 10.0;
  55555. var subdivisions = options.subdivisions || 1 | 0;
  55556. var minHeight = options.minHeight || 0.0;
  55557. var maxHeight = options.maxHeight || 1.0;
  55558. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55559. var updatable = options.updatable;
  55560. var onReady = options.onReady;
  55561. var ground = new BABYLON.GroundMesh(name, scene);
  55562. ground._subdivisionsX = subdivisions;
  55563. ground._subdivisionsY = subdivisions;
  55564. ground._width = width;
  55565. ground._height = height;
  55566. ground._maxX = ground._width / 2.0;
  55567. ground._maxZ = ground._height / 2.0;
  55568. ground._minX = -ground._maxX;
  55569. ground._minZ = -ground._maxZ;
  55570. ground._setReady(false);
  55571. var onload = function (img) {
  55572. // Getting height map data
  55573. var canvas = document.createElement("canvas");
  55574. var context = canvas.getContext("2d");
  55575. if (!context) {
  55576. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55577. }
  55578. if (scene.isDisposed) {
  55579. return;
  55580. }
  55581. var bufferWidth = img.width;
  55582. var bufferHeight = img.height;
  55583. canvas.width = bufferWidth;
  55584. canvas.height = bufferHeight;
  55585. context.drawImage(img, 0, 0);
  55586. // Create VertexData from map data
  55587. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55588. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55589. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55590. width: width, height: height,
  55591. subdivisions: subdivisions,
  55592. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55593. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55594. });
  55595. vertexData.applyToMesh(ground, updatable);
  55596. ground._setReady(true);
  55597. //execute ready callback, if set
  55598. if (onReady) {
  55599. onReady(ground);
  55600. }
  55601. };
  55602. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55603. return ground;
  55604. };
  55605. /**
  55606. * Creates a polygon mesh.
  55607. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55608. * 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.
  55609. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55611. * 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).
  55612. * Remember you can only change the shape positions, not their number when updating a polygon.
  55613. */
  55614. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55615. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55616. var shape = options.shape;
  55617. var holes = options.holes || [];
  55618. var depth = options.depth || 0;
  55619. var contours = [];
  55620. var hole = [];
  55621. for (var i = 0; i < shape.length; i++) {
  55622. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55623. }
  55624. var epsilon = 0.00000001;
  55625. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55626. contours.pop();
  55627. }
  55628. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55629. for (var hNb = 0; hNb < holes.length; hNb++) {
  55630. hole = [];
  55631. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55632. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55633. }
  55634. polygonTriangulation.addHole(hole);
  55635. }
  55636. var polygon = polygonTriangulation.build(options.updatable, depth);
  55637. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55638. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55639. vertexData.applyToMesh(polygon, options.updatable);
  55640. return polygon;
  55641. };
  55642. ;
  55643. /**
  55644. * Creates an extruded polygon mesh, with depth in the Y direction.
  55645. * 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).
  55646. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55647. */
  55648. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55649. return MeshBuilder.CreatePolygon(name, options, scene);
  55650. };
  55651. ;
  55652. /**
  55653. * Creates a tube mesh.
  55654. * 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.
  55655. *
  55656. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55657. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55658. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55659. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55660. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55661. * 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.
  55662. * It must return a radius value (positive float) :
  55663. * ```javascript
  55664. * var radiusFunction = function(i, distance) {
  55665. * // do things
  55666. * return radius; }
  55667. * ```
  55668. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55669. * 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
  55670. * 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
  55671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55672. * 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).
  55673. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55674. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55676. */
  55677. MeshBuilder.CreateTube = function (name, options, scene) {
  55678. var path = options.path;
  55679. var instance = options.instance;
  55680. var radius = 1.0;
  55681. if (instance) {
  55682. radius = instance.radius;
  55683. }
  55684. if (options.radius !== undefined) {
  55685. radius = options.radius;
  55686. }
  55687. ;
  55688. var tessellation = options.tessellation || 64 | 0;
  55689. var radiusFunction = options.radiusFunction || null;
  55690. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55691. var invertUV = options.invertUV || false;
  55692. var updatable = options.updatable;
  55693. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55694. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55695. // tube geometry
  55696. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55697. var tangents = path3D.getTangents();
  55698. var normals = path3D.getNormals();
  55699. var distances = path3D.getDistances();
  55700. var pi2 = Math.PI * 2;
  55701. var step = pi2 / tessellation * arc;
  55702. var returnRadius = function () { return radius; };
  55703. var radiusFunctionFinal = radiusFunction || returnRadius;
  55704. var circlePath;
  55705. var rad;
  55706. var normal;
  55707. var rotated;
  55708. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55709. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55710. for (var i = 0; i < path.length; i++) {
  55711. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55712. circlePath = Array(); // current circle array
  55713. normal = normals[i]; // current normal
  55714. for (var t = 0; t < tessellation; t++) {
  55715. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55716. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55717. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55718. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55719. circlePath[t] = rotated;
  55720. }
  55721. circlePaths[index] = circlePath;
  55722. index++;
  55723. }
  55724. // cap
  55725. var capPath = function (nbPoints, pathIndex) {
  55726. var pointCap = Array();
  55727. for (var i = 0; i < nbPoints; i++) {
  55728. pointCap.push(path[pathIndex]);
  55729. }
  55730. return pointCap;
  55731. };
  55732. switch (cap) {
  55733. case BABYLON.Mesh.NO_CAP:
  55734. break;
  55735. case BABYLON.Mesh.CAP_START:
  55736. circlePaths[0] = capPath(tessellation, 0);
  55737. circlePaths[1] = circlePaths[2].slice(0);
  55738. break;
  55739. case BABYLON.Mesh.CAP_END:
  55740. circlePaths[index] = circlePaths[index - 1].slice(0);
  55741. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55742. break;
  55743. case BABYLON.Mesh.CAP_ALL:
  55744. circlePaths[0] = capPath(tessellation, 0);
  55745. circlePaths[1] = circlePaths[2].slice(0);
  55746. circlePaths[index] = circlePaths[index - 1].slice(0);
  55747. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55748. break;
  55749. default:
  55750. break;
  55751. }
  55752. return circlePaths;
  55753. };
  55754. var path3D;
  55755. var pathArray;
  55756. if (instance) {
  55757. var arc = options.arc || instance.arc;
  55758. path3D = (instance.path3D).update(path);
  55759. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55760. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55761. instance.path3D = path3D;
  55762. instance.pathArray = pathArray;
  55763. instance.arc = arc;
  55764. instance.radius = radius;
  55765. return instance;
  55766. }
  55767. // tube creation
  55768. path3D = new BABYLON.Path3D(path);
  55769. var newPathArray = new Array();
  55770. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55771. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55772. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55773. tube.pathArray = pathArray;
  55774. tube.path3D = path3D;
  55775. tube.tessellation = tessellation;
  55776. tube.cap = cap;
  55777. tube.arc = options.arc;
  55778. tube.radius = radius;
  55779. return tube;
  55780. };
  55781. /**
  55782. * Creates a polyhedron mesh.
  55783. *
  55784. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55785. * 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
  55786. * to choose the wanted type.
  55787. * The parameter `size` (positive float, default 1) sets the polygon size.
  55788. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55789. * 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`.
  55790. * 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
  55791. * 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)`).
  55792. * 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
  55793. * 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.
  55794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55795. * 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).
  55796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55798. */
  55799. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55800. var polyhedron = new BABYLON.Mesh(name, scene);
  55801. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55802. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55803. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55804. vertexData.applyToMesh(polyhedron, options.updatable);
  55805. return polyhedron;
  55806. };
  55807. /**
  55808. * Creates a decal mesh.
  55809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55810. * 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.
  55811. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55812. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55813. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55814. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55815. */
  55816. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55817. var indices = sourceMesh.getIndices();
  55818. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55819. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55820. var position = options.position || BABYLON.Vector3.Zero();
  55821. var normal = options.normal || BABYLON.Vector3.Up();
  55822. var size = options.size || BABYLON.Vector3.One();
  55823. var angle = options.angle || 0;
  55824. // Getting correct rotation
  55825. if (!normal) {
  55826. var target = new BABYLON.Vector3(0, 0, 1);
  55827. var camera = sourceMesh.getScene().activeCamera;
  55828. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55829. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55830. }
  55831. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55832. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55833. var pitch = Math.atan2(normal.y, len);
  55834. // Matrix
  55835. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55836. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55837. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55838. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55839. var vertexData = new BABYLON.VertexData();
  55840. vertexData.indices = [];
  55841. vertexData.positions = [];
  55842. vertexData.normals = [];
  55843. vertexData.uvs = [];
  55844. var currentVertexDataIndex = 0;
  55845. var extractDecalVector3 = function (indexId) {
  55846. var result = new BABYLON.PositionNormalVertex();
  55847. if (!indices || !positions || !normals) {
  55848. return result;
  55849. }
  55850. var vertexId = indices[indexId];
  55851. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55852. // Send vector to decal local world
  55853. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55854. // Get normal
  55855. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55856. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55857. return result;
  55858. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55859. var clip = function (vertices, axis) {
  55860. if (vertices.length === 0) {
  55861. return vertices;
  55862. }
  55863. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55864. var clipVertices = function (v0, v1) {
  55865. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55866. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55867. };
  55868. var result = new Array();
  55869. for (var index = 0; index < vertices.length; index += 3) {
  55870. var v1Out;
  55871. var v2Out;
  55872. var v3Out;
  55873. var total = 0;
  55874. var nV1 = null;
  55875. var nV2 = null;
  55876. var nV3 = null;
  55877. var nV4 = null;
  55878. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55879. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55880. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55881. v1Out = d1 > 0;
  55882. v2Out = d2 > 0;
  55883. v3Out = d3 > 0;
  55884. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55885. switch (total) {
  55886. case 0:
  55887. result.push(vertices[index]);
  55888. result.push(vertices[index + 1]);
  55889. result.push(vertices[index + 2]);
  55890. break;
  55891. case 1:
  55892. if (v1Out) {
  55893. nV1 = vertices[index + 1];
  55894. nV2 = vertices[index + 2];
  55895. nV3 = clipVertices(vertices[index], nV1);
  55896. nV4 = clipVertices(vertices[index], nV2);
  55897. }
  55898. if (v2Out) {
  55899. nV1 = vertices[index];
  55900. nV2 = vertices[index + 2];
  55901. nV3 = clipVertices(vertices[index + 1], nV1);
  55902. nV4 = clipVertices(vertices[index + 1], nV2);
  55903. result.push(nV3);
  55904. result.push(nV2.clone());
  55905. result.push(nV1.clone());
  55906. result.push(nV2.clone());
  55907. result.push(nV3.clone());
  55908. result.push(nV4);
  55909. break;
  55910. }
  55911. if (v3Out) {
  55912. nV1 = vertices[index];
  55913. nV2 = vertices[index + 1];
  55914. nV3 = clipVertices(vertices[index + 2], nV1);
  55915. nV4 = clipVertices(vertices[index + 2], nV2);
  55916. }
  55917. if (nV1 && nV2 && nV3 && nV4) {
  55918. result.push(nV1.clone());
  55919. result.push(nV2.clone());
  55920. result.push(nV3);
  55921. result.push(nV4);
  55922. result.push(nV3.clone());
  55923. result.push(nV2.clone());
  55924. }
  55925. break;
  55926. case 2:
  55927. if (!v1Out) {
  55928. nV1 = vertices[index].clone();
  55929. nV2 = clipVertices(nV1, vertices[index + 1]);
  55930. nV3 = clipVertices(nV1, vertices[index + 2]);
  55931. result.push(nV1);
  55932. result.push(nV2);
  55933. result.push(nV3);
  55934. }
  55935. if (!v2Out) {
  55936. nV1 = vertices[index + 1].clone();
  55937. nV2 = clipVertices(nV1, vertices[index + 2]);
  55938. nV3 = clipVertices(nV1, vertices[index]);
  55939. result.push(nV1);
  55940. result.push(nV2);
  55941. result.push(nV3);
  55942. }
  55943. if (!v3Out) {
  55944. nV1 = vertices[index + 2].clone();
  55945. nV2 = clipVertices(nV1, vertices[index]);
  55946. nV3 = clipVertices(nV1, vertices[index + 1]);
  55947. result.push(nV1);
  55948. result.push(nV2);
  55949. result.push(nV3);
  55950. }
  55951. break;
  55952. case 3:
  55953. break;
  55954. }
  55955. }
  55956. return result;
  55957. };
  55958. for (var index = 0; index < indices.length; index += 3) {
  55959. var faceVertices = new Array();
  55960. faceVertices.push(extractDecalVector3(index));
  55961. faceVertices.push(extractDecalVector3(index + 1));
  55962. faceVertices.push(extractDecalVector3(index + 2));
  55963. // Clip
  55964. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55965. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55966. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55967. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55968. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55969. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55970. if (faceVertices.length === 0) {
  55971. continue;
  55972. }
  55973. // Add UVs and get back to world
  55974. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55975. var vertex = faceVertices[vIndex];
  55976. //TODO check for Int32Array | Uint32Array | Uint16Array
  55977. vertexData.indices.push(currentVertexDataIndex);
  55978. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55979. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55980. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55981. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55982. currentVertexDataIndex++;
  55983. }
  55984. }
  55985. // Return mesh
  55986. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55987. vertexData.applyToMesh(decal);
  55988. decal.position = position.clone();
  55989. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55990. return decal;
  55991. };
  55992. // Privates
  55993. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55994. // extrusion geometry
  55995. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55996. var tangents = path3D.getTangents();
  55997. var normals = path3D.getNormals();
  55998. var binormals = path3D.getBinormals();
  55999. var distances = path3D.getDistances();
  56000. var angle = 0;
  56001. var returnScale = function () { return scale !== null ? scale : 1; };
  56002. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56003. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56004. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56005. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56006. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56007. for (var i = 0; i < curve.length; i++) {
  56008. var shapePath = new Array();
  56009. var angleStep = rotate(i, distances[i]);
  56010. var scaleRatio = scl(i, distances[i]);
  56011. for (var p = 0; p < shape.length; p++) {
  56012. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56013. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56014. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56015. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56016. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56017. shapePath[p] = rotated;
  56018. }
  56019. shapePaths[index] = shapePath;
  56020. angle += angleStep;
  56021. index++;
  56022. }
  56023. // cap
  56024. var capPath = function (shapePath) {
  56025. var pointCap = Array();
  56026. var barycenter = BABYLON.Vector3.Zero();
  56027. var i;
  56028. for (i = 0; i < shapePath.length; i++) {
  56029. barycenter.addInPlace(shapePath[i]);
  56030. }
  56031. barycenter.scaleInPlace(1.0 / shapePath.length);
  56032. for (i = 0; i < shapePath.length; i++) {
  56033. pointCap.push(barycenter);
  56034. }
  56035. return pointCap;
  56036. };
  56037. switch (cap) {
  56038. case BABYLON.Mesh.NO_CAP:
  56039. break;
  56040. case BABYLON.Mesh.CAP_START:
  56041. shapePaths[0] = capPath(shapePaths[2]);
  56042. shapePaths[1] = shapePaths[2];
  56043. break;
  56044. case BABYLON.Mesh.CAP_END:
  56045. shapePaths[index] = shapePaths[index - 1];
  56046. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56047. break;
  56048. case BABYLON.Mesh.CAP_ALL:
  56049. shapePaths[0] = capPath(shapePaths[2]);
  56050. shapePaths[1] = shapePaths[2];
  56051. shapePaths[index] = shapePaths[index - 1];
  56052. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56053. break;
  56054. default:
  56055. break;
  56056. }
  56057. return shapePaths;
  56058. };
  56059. var path3D;
  56060. var pathArray;
  56061. if (instance) {
  56062. path3D = (instance.path3D).update(curve);
  56063. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56064. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56065. return instance;
  56066. }
  56067. // extruded shape creation
  56068. path3D = new BABYLON.Path3D(curve);
  56069. var newShapePaths = new Array();
  56070. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56071. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56072. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56073. extrudedGeneric.pathArray = pathArray;
  56074. extrudedGeneric.path3D = path3D;
  56075. extrudedGeneric.cap = cap;
  56076. return extrudedGeneric;
  56077. };
  56078. return MeshBuilder;
  56079. }());
  56080. BABYLON.MeshBuilder = MeshBuilder;
  56081. })(BABYLON || (BABYLON = {}));
  56082. //# sourceMappingURL=babylon.meshBuilder.js.map
  56083. var BABYLON;
  56084. (function (BABYLON) {
  56085. /**
  56086. * Draco compression (https://google.github.io/draco/)
  56087. */
  56088. var DracoCompression = /** @class */ (function () {
  56089. /**
  56090. * Constructor
  56091. * @param numWorkers The number of workers for async operations
  56092. */
  56093. function DracoCompression(numWorkers) {
  56094. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56095. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56096. if (!workerBlobUrl || !Worker) {
  56097. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56098. return;
  56099. }
  56100. var workers = new Array(numWorkers);
  56101. for (var i = 0; i < workers.length; i++) {
  56102. var worker = new Worker(workerBlobUrl);
  56103. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56104. workers[i] = worker;
  56105. }
  56106. this._workerPool = new BABYLON.WorkerPool(workers);
  56107. }
  56108. /**
  56109. * Stop all async operations and release resources.
  56110. */
  56111. DracoCompression.prototype.dispose = function () {
  56112. this._workerPool.dispose();
  56113. delete this._workerPool;
  56114. };
  56115. /**
  56116. * Decode Draco compressed mesh data to vertex data.
  56117. * @param data The array buffer view for the Draco compression data
  56118. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56119. * @returns A promise that resolves with the decoded vertex data
  56120. */
  56121. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56122. var _this = this;
  56123. return new Promise(function (resolve, reject) {
  56124. _this._workerPool.push(function (worker, onComplete) {
  56125. var vertexData = new BABYLON.VertexData();
  56126. var onError = function (error) {
  56127. worker.removeEventListener("error", onError);
  56128. worker.removeEventListener("message", onMessage);
  56129. reject(error);
  56130. onComplete();
  56131. };
  56132. var onMessage = function (message) {
  56133. if (message.data === "done") {
  56134. worker.removeEventListener("error", onError);
  56135. worker.removeEventListener("message", onMessage);
  56136. resolve(vertexData);
  56137. onComplete();
  56138. }
  56139. else if (message.data.id === "indices") {
  56140. vertexData.indices = message.data.value;
  56141. }
  56142. else {
  56143. vertexData.set(message.data.value, message.data.id);
  56144. }
  56145. };
  56146. worker.addEventListener("error", onError);
  56147. worker.addEventListener("message", onMessage);
  56148. var dataCopy = new Uint8Array(data.byteLength);
  56149. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56150. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56151. });
  56152. });
  56153. };
  56154. /**
  56155. * The worker function that gets converted to a blob url to pass into a worker.
  56156. */
  56157. DracoCompression._Worker = function () {
  56158. // self is actually a DedicatedWorkerGlobalScope
  56159. var _self = self;
  56160. var decodeMesh = function (data, attributes) {
  56161. var dracoModule = new DracoDecoderModule();
  56162. var buffer = new dracoModule.DecoderBuffer();
  56163. buffer.Init(data, data.byteLength);
  56164. var decoder = new dracoModule.Decoder();
  56165. var geometry;
  56166. var status;
  56167. try {
  56168. var type = decoder.GetEncodedGeometryType(buffer);
  56169. switch (type) {
  56170. case dracoModule.TRIANGULAR_MESH:
  56171. geometry = new dracoModule.Mesh();
  56172. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56173. break;
  56174. case dracoModule.POINT_CLOUD:
  56175. geometry = new dracoModule.PointCloud();
  56176. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56177. break;
  56178. default:
  56179. throw new Error("Invalid geometry type " + type);
  56180. }
  56181. if (!status.ok() || !geometry.ptr) {
  56182. throw new Error(status.error_msg());
  56183. }
  56184. var numPoints = geometry.num_points();
  56185. if (type === dracoModule.TRIANGULAR_MESH) {
  56186. var numFaces = geometry.num_faces();
  56187. var faceIndices = new dracoModule.DracoInt32Array();
  56188. try {
  56189. var indices = new Uint32Array(numFaces * 3);
  56190. for (var i = 0; i < numFaces; i++) {
  56191. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56192. var offset = i * 3;
  56193. indices[offset + 0] = faceIndices.GetValue(0);
  56194. indices[offset + 1] = faceIndices.GetValue(1);
  56195. indices[offset + 2] = faceIndices.GetValue(2);
  56196. }
  56197. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56198. }
  56199. finally {
  56200. dracoModule.destroy(faceIndices);
  56201. }
  56202. }
  56203. for (var kind in attributes) {
  56204. var uniqueId = attributes[kind];
  56205. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56206. var dracoData = new dracoModule.DracoFloat32Array();
  56207. try {
  56208. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56209. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56210. for (var i = 0; i < babylonData.length; i++) {
  56211. babylonData[i] = dracoData.GetValue(i);
  56212. }
  56213. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56214. }
  56215. finally {
  56216. dracoModule.destroy(dracoData);
  56217. }
  56218. }
  56219. }
  56220. finally {
  56221. if (geometry) {
  56222. dracoModule.destroy(geometry);
  56223. }
  56224. dracoModule.destroy(decoder);
  56225. dracoModule.destroy(buffer);
  56226. }
  56227. _self.postMessage("done");
  56228. };
  56229. _self.onmessage = function (event) {
  56230. switch (event.data.id) {
  56231. case "initDecoder": {
  56232. importScripts(event.data.url);
  56233. break;
  56234. }
  56235. case "decodeMesh": {
  56236. decodeMesh(event.data.data, event.data.attributes);
  56237. break;
  56238. }
  56239. }
  56240. };
  56241. };
  56242. DracoCompression._GetDefaultDecoderUrl = function () {
  56243. if (!BABYLON.Tools.IsWindowObjectExist) {
  56244. return null;
  56245. }
  56246. for (var i = 0; i < document.scripts.length; i++) {
  56247. if (document.scripts[i].type === "text/x-draco-decoder") {
  56248. return document.scripts[i].src;
  56249. }
  56250. }
  56251. return null;
  56252. };
  56253. /**
  56254. * Gets the url to the draco decoder if available.
  56255. */
  56256. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56257. return DracoCompression;
  56258. }());
  56259. BABYLON.DracoCompression = DracoCompression;
  56260. })(BABYLON || (BABYLON = {}));
  56261. //# sourceMappingURL=babylon.dracoCompression.js.map
  56262. var BABYLON;
  56263. (function (BABYLON) {
  56264. var AudioEngine = /** @class */ (function () {
  56265. function AudioEngine() {
  56266. this._audioContext = null;
  56267. this._audioContextInitialized = false;
  56268. this.canUseWebAudio = false;
  56269. this.WarnedWebAudioUnsupported = false;
  56270. this.unlocked = false;
  56271. this.isMP3supported = false;
  56272. this.isOGGsupported = false;
  56273. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56274. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56275. this.canUseWebAudio = true;
  56276. }
  56277. var audioElem = document.createElement('audio');
  56278. try {
  56279. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56280. this.isMP3supported = true;
  56281. }
  56282. }
  56283. catch (e) {
  56284. // protect error during capability check.
  56285. }
  56286. try {
  56287. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56288. this.isOGGsupported = true;
  56289. }
  56290. }
  56291. catch (e) {
  56292. // protect error during capability check.
  56293. }
  56294. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56295. this._unlockiOSaudio();
  56296. }
  56297. else {
  56298. this.unlocked = true;
  56299. }
  56300. }
  56301. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56302. get: function () {
  56303. if (!this._audioContextInitialized) {
  56304. this._initializeAudioContext();
  56305. }
  56306. return this._audioContext;
  56307. },
  56308. enumerable: true,
  56309. configurable: true
  56310. });
  56311. AudioEngine.prototype._unlockiOSaudio = function () {
  56312. var _this = this;
  56313. var unlockaudio = function () {
  56314. if (!_this.audioContext) {
  56315. return;
  56316. }
  56317. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56318. var source = _this.audioContext.createBufferSource();
  56319. source.buffer = buffer;
  56320. source.connect(_this.audioContext.destination);
  56321. source.start(0);
  56322. setTimeout(function () {
  56323. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56324. _this.unlocked = true;
  56325. window.removeEventListener('touchend', unlockaudio, false);
  56326. if (_this.onAudioUnlocked) {
  56327. _this.onAudioUnlocked();
  56328. }
  56329. }
  56330. }, 0);
  56331. };
  56332. window.addEventListener('touchend', unlockaudio, false);
  56333. };
  56334. AudioEngine.prototype._initializeAudioContext = function () {
  56335. try {
  56336. if (this.canUseWebAudio) {
  56337. this._audioContext = new AudioContext();
  56338. // create a global volume gain node
  56339. this.masterGain = this._audioContext.createGain();
  56340. this.masterGain.gain.value = 1;
  56341. this.masterGain.connect(this._audioContext.destination);
  56342. this._audioContextInitialized = true;
  56343. }
  56344. }
  56345. catch (e) {
  56346. this.canUseWebAudio = false;
  56347. BABYLON.Tools.Error("Web Audio: " + e.message);
  56348. }
  56349. };
  56350. AudioEngine.prototype.dispose = function () {
  56351. if (this.canUseWebAudio && this._audioContextInitialized) {
  56352. if (this._connectedAnalyser && this._audioContext) {
  56353. this._connectedAnalyser.stopDebugCanvas();
  56354. this._connectedAnalyser.dispose();
  56355. this.masterGain.disconnect();
  56356. this.masterGain.connect(this._audioContext.destination);
  56357. this._connectedAnalyser = null;
  56358. }
  56359. this.masterGain.gain.value = 1;
  56360. }
  56361. this.WarnedWebAudioUnsupported = false;
  56362. };
  56363. AudioEngine.prototype.getGlobalVolume = function () {
  56364. if (this.canUseWebAudio && this._audioContextInitialized) {
  56365. return this.masterGain.gain.value;
  56366. }
  56367. else {
  56368. return -1;
  56369. }
  56370. };
  56371. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56372. if (this.canUseWebAudio && this._audioContextInitialized) {
  56373. this.masterGain.gain.value = newVolume;
  56374. }
  56375. };
  56376. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56377. if (this._connectedAnalyser) {
  56378. this._connectedAnalyser.stopDebugCanvas();
  56379. }
  56380. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56381. this._connectedAnalyser = analyser;
  56382. this.masterGain.disconnect();
  56383. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56384. }
  56385. };
  56386. return AudioEngine;
  56387. }());
  56388. BABYLON.AudioEngine = AudioEngine;
  56389. })(BABYLON || (BABYLON = {}));
  56390. //# sourceMappingURL=babylon.audioEngine.js.map
  56391. var BABYLON;
  56392. (function (BABYLON) {
  56393. var Sound = /** @class */ (function () {
  56394. /**
  56395. * Create a sound and attach it to a scene
  56396. * @param name Name of your sound
  56397. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56398. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56399. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56400. */
  56401. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56402. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56403. var _this = this;
  56404. this.autoplay = false;
  56405. this.loop = false;
  56406. this.useCustomAttenuation = false;
  56407. this.spatialSound = false;
  56408. this.refDistance = 1;
  56409. this.rolloffFactor = 1;
  56410. this.maxDistance = 100;
  56411. this.distanceModel = "linear";
  56412. this._panningModel = "equalpower";
  56413. this._playbackRate = 1;
  56414. this._streaming = false;
  56415. this._startTime = 0;
  56416. this._startOffset = 0;
  56417. this._position = BABYLON.Vector3.Zero();
  56418. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56419. this._volume = 1;
  56420. this._isReadyToPlay = false;
  56421. this.isPlaying = false;
  56422. this.isPaused = false;
  56423. this._isDirectional = false;
  56424. // Used if you'd like to create a directional sound.
  56425. // If not set, the sound will be omnidirectional
  56426. this._coneInnerAngle = 360;
  56427. this._coneOuterAngle = 360;
  56428. this._coneOuterGain = 0;
  56429. this._isOutputConnected = false;
  56430. this._urlType = "Unknown";
  56431. this.name = name;
  56432. this._scene = scene;
  56433. this._readyToPlayCallback = readyToPlayCallback;
  56434. // Default custom attenuation function is a linear attenuation
  56435. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56436. if (currentDistance < maxDistance) {
  56437. return currentVolume * (1 - currentDistance / maxDistance);
  56438. }
  56439. else {
  56440. return 0;
  56441. }
  56442. };
  56443. if (options) {
  56444. this.autoplay = options.autoplay || false;
  56445. this.loop = options.loop || false;
  56446. // if volume === 0, we need another way to check this option
  56447. if (options.volume !== undefined) {
  56448. this._volume = options.volume;
  56449. }
  56450. this.spatialSound = options.spatialSound || false;
  56451. this.maxDistance = options.maxDistance || 100;
  56452. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56453. this.rolloffFactor = options.rolloffFactor || 1;
  56454. this.refDistance = options.refDistance || 1;
  56455. this.distanceModel = options.distanceModel || "linear";
  56456. this._playbackRate = options.playbackRate || 1;
  56457. this._streaming = options.streaming || false;
  56458. }
  56459. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56460. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56461. this._soundGain.gain.value = this._volume;
  56462. this._inputAudioNode = this._soundGain;
  56463. this._ouputAudioNode = this._soundGain;
  56464. if (this.spatialSound) {
  56465. this._createSpatialParameters();
  56466. }
  56467. this._scene.mainSoundTrack.AddSound(this);
  56468. var validParameter = true;
  56469. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56470. if (urlOrArrayBuffer) {
  56471. if (typeof (urlOrArrayBuffer) === "string")
  56472. this._urlType = "String";
  56473. if (Array.isArray(urlOrArrayBuffer))
  56474. this._urlType = "Array";
  56475. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56476. this._urlType = "ArrayBuffer";
  56477. var urls = [];
  56478. var codecSupportedFound = false;
  56479. switch (this._urlType) {
  56480. case "ArrayBuffer":
  56481. if (urlOrArrayBuffer.byteLength > 0) {
  56482. codecSupportedFound = true;
  56483. this._soundLoaded(urlOrArrayBuffer);
  56484. }
  56485. break;
  56486. case "String":
  56487. urls.push(urlOrArrayBuffer);
  56488. case "Array":
  56489. if (urls.length === 0)
  56490. urls = urlOrArrayBuffer;
  56491. // If we found a supported format, we load it immediately and stop the loop
  56492. for (var i = 0; i < urls.length; i++) {
  56493. var url = urls[i];
  56494. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56495. codecSupportedFound = true;
  56496. }
  56497. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56498. codecSupportedFound = true;
  56499. }
  56500. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56501. codecSupportedFound = true;
  56502. }
  56503. if (url.indexOf("blob:") !== -1) {
  56504. codecSupportedFound = true;
  56505. }
  56506. if (codecSupportedFound) {
  56507. // Loading sound using XHR2
  56508. if (!this._streaming) {
  56509. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56510. }
  56511. else {
  56512. this._htmlAudioElement = new Audio(url);
  56513. this._htmlAudioElement.controls = false;
  56514. this._htmlAudioElement.loop = this.loop;
  56515. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56516. this._htmlAudioElement.preload = "auto";
  56517. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56518. _this._isReadyToPlay = true;
  56519. if (_this.autoplay) {
  56520. _this.play();
  56521. }
  56522. if (_this._readyToPlayCallback) {
  56523. _this._readyToPlayCallback();
  56524. }
  56525. });
  56526. document.body.appendChild(this._htmlAudioElement);
  56527. }
  56528. break;
  56529. }
  56530. }
  56531. break;
  56532. default:
  56533. validParameter = false;
  56534. break;
  56535. }
  56536. if (!validParameter) {
  56537. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56538. }
  56539. else {
  56540. if (!codecSupportedFound) {
  56541. this._isReadyToPlay = true;
  56542. // Simulating a ready to play event to avoid breaking code path
  56543. if (this._readyToPlayCallback) {
  56544. window.setTimeout(function () {
  56545. if (_this._readyToPlayCallback) {
  56546. _this._readyToPlayCallback();
  56547. }
  56548. }, 1000);
  56549. }
  56550. }
  56551. }
  56552. }
  56553. }
  56554. else {
  56555. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56556. this._scene.mainSoundTrack.AddSound(this);
  56557. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56558. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56559. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56560. }
  56561. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56562. if (this._readyToPlayCallback) {
  56563. window.setTimeout(function () {
  56564. if (_this._readyToPlayCallback) {
  56565. _this._readyToPlayCallback();
  56566. }
  56567. }, 1000);
  56568. }
  56569. }
  56570. }
  56571. Sound.prototype.dispose = function () {
  56572. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56573. if (this.isPlaying) {
  56574. this.stop();
  56575. }
  56576. this._isReadyToPlay = false;
  56577. if (this.soundTrackId === -1) {
  56578. this._scene.mainSoundTrack.RemoveSound(this);
  56579. }
  56580. else {
  56581. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56582. }
  56583. if (this._soundGain) {
  56584. this._soundGain.disconnect();
  56585. this._soundGain = null;
  56586. }
  56587. if (this._soundPanner) {
  56588. this._soundPanner.disconnect();
  56589. this._soundPanner = null;
  56590. }
  56591. if (this._soundSource) {
  56592. this._soundSource.disconnect();
  56593. this._soundSource = null;
  56594. }
  56595. this._audioBuffer = null;
  56596. if (this._htmlAudioElement) {
  56597. this._htmlAudioElement.pause();
  56598. this._htmlAudioElement.src = "";
  56599. document.body.removeChild(this._htmlAudioElement);
  56600. }
  56601. if (this._connectedMesh && this._registerFunc) {
  56602. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56603. this._connectedMesh = null;
  56604. }
  56605. }
  56606. };
  56607. Sound.prototype.isReady = function () {
  56608. return this._isReadyToPlay;
  56609. };
  56610. Sound.prototype._soundLoaded = function (audioData) {
  56611. var _this = this;
  56612. if (!BABYLON.Engine.audioEngine.audioContext) {
  56613. return;
  56614. }
  56615. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56616. _this._audioBuffer = buffer;
  56617. _this._isReadyToPlay = true;
  56618. if (_this.autoplay) {
  56619. _this.play();
  56620. }
  56621. if (_this._readyToPlayCallback) {
  56622. _this._readyToPlayCallback();
  56623. }
  56624. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56625. };
  56626. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56627. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56628. this._audioBuffer = audioBuffer;
  56629. this._isReadyToPlay = true;
  56630. }
  56631. };
  56632. Sound.prototype.updateOptions = function (options) {
  56633. if (options) {
  56634. this.loop = options.loop || this.loop;
  56635. this.maxDistance = options.maxDistance || this.maxDistance;
  56636. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56637. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56638. this.refDistance = options.refDistance || this.refDistance;
  56639. this.distanceModel = options.distanceModel || this.distanceModel;
  56640. this._playbackRate = options.playbackRate || this._playbackRate;
  56641. this._updateSpatialParameters();
  56642. if (this.isPlaying) {
  56643. if (this._streaming) {
  56644. this._htmlAudioElement.playbackRate = this._playbackRate;
  56645. }
  56646. else {
  56647. if (this._soundSource) {
  56648. this._soundSource.playbackRate.value = this._playbackRate;
  56649. }
  56650. }
  56651. }
  56652. }
  56653. };
  56654. Sound.prototype._createSpatialParameters = function () {
  56655. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56656. if (this._scene.headphone) {
  56657. this._panningModel = "HRTF";
  56658. }
  56659. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56660. this._updateSpatialParameters();
  56661. this._soundPanner.connect(this._ouputAudioNode);
  56662. this._inputAudioNode = this._soundPanner;
  56663. }
  56664. };
  56665. Sound.prototype._updateSpatialParameters = function () {
  56666. if (this.spatialSound && this._soundPanner) {
  56667. if (this.useCustomAttenuation) {
  56668. // Tricks to disable in a way embedded Web Audio attenuation
  56669. this._soundPanner.distanceModel = "linear";
  56670. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56671. this._soundPanner.refDistance = 1;
  56672. this._soundPanner.rolloffFactor = 1;
  56673. this._soundPanner.panningModel = this._panningModel;
  56674. }
  56675. else {
  56676. this._soundPanner.distanceModel = this.distanceModel;
  56677. this._soundPanner.maxDistance = this.maxDistance;
  56678. this._soundPanner.refDistance = this.refDistance;
  56679. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56680. this._soundPanner.panningModel = this._panningModel;
  56681. }
  56682. }
  56683. };
  56684. Sound.prototype.switchPanningModelToHRTF = function () {
  56685. this._panningModel = "HRTF";
  56686. this._switchPanningModel();
  56687. };
  56688. Sound.prototype.switchPanningModelToEqualPower = function () {
  56689. this._panningModel = "equalpower";
  56690. this._switchPanningModel();
  56691. };
  56692. Sound.prototype._switchPanningModel = function () {
  56693. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56694. this._soundPanner.panningModel = this._panningModel;
  56695. }
  56696. };
  56697. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56698. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56699. if (this._isOutputConnected) {
  56700. this._ouputAudioNode.disconnect();
  56701. }
  56702. this._ouputAudioNode.connect(soundTrackAudioNode);
  56703. this._isOutputConnected = true;
  56704. }
  56705. };
  56706. /**
  56707. * Transform this sound into a directional source
  56708. * @param coneInnerAngle Size of the inner cone in degree
  56709. * @param coneOuterAngle Size of the outer cone in degree
  56710. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56711. */
  56712. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56713. if (coneOuterAngle < coneInnerAngle) {
  56714. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56715. return;
  56716. }
  56717. this._coneInnerAngle = coneInnerAngle;
  56718. this._coneOuterAngle = coneOuterAngle;
  56719. this._coneOuterGain = coneOuterGain;
  56720. this._isDirectional = true;
  56721. if (this.isPlaying && this.loop) {
  56722. this.stop();
  56723. this.play();
  56724. }
  56725. };
  56726. Sound.prototype.setPosition = function (newPosition) {
  56727. this._position = newPosition;
  56728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56729. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56730. }
  56731. };
  56732. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56733. this._localDirection = newLocalDirection;
  56734. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56735. this._updateDirection();
  56736. }
  56737. };
  56738. Sound.prototype._updateDirection = function () {
  56739. if (!this._connectedMesh || !this._soundPanner) {
  56740. return;
  56741. }
  56742. var mat = this._connectedMesh.getWorldMatrix();
  56743. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56744. direction.normalize();
  56745. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56746. };
  56747. Sound.prototype.updateDistanceFromListener = function () {
  56748. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56749. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56750. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56751. }
  56752. };
  56753. Sound.prototype.setAttenuationFunction = function (callback) {
  56754. this._customAttenuationFunction = callback;
  56755. };
  56756. /**
  56757. * Play the sound
  56758. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56759. * @param offset (optional) Start the sound setting it at a specific time
  56760. */
  56761. Sound.prototype.play = function (time, offset) {
  56762. var _this = this;
  56763. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56764. try {
  56765. if (this._startOffset < 0) {
  56766. time = -this._startOffset;
  56767. this._startOffset = 0;
  56768. }
  56769. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56770. if (!this._soundSource || !this._streamingSource) {
  56771. if (this.spatialSound && this._soundPanner) {
  56772. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56773. if (this._isDirectional) {
  56774. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56775. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56776. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56777. if (this._connectedMesh) {
  56778. this._updateDirection();
  56779. }
  56780. else {
  56781. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56782. }
  56783. }
  56784. }
  56785. }
  56786. if (this._streaming) {
  56787. if (!this._streamingSource) {
  56788. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56789. this._htmlAudioElement.onended = function () { _this._onended(); };
  56790. this._htmlAudioElement.playbackRate = this._playbackRate;
  56791. }
  56792. this._streamingSource.disconnect();
  56793. this._streamingSource.connect(this._inputAudioNode);
  56794. this._htmlAudioElement.play();
  56795. }
  56796. else {
  56797. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56798. this._soundSource.buffer = this._audioBuffer;
  56799. this._soundSource.connect(this._inputAudioNode);
  56800. this._soundSource.loop = this.loop;
  56801. this._soundSource.playbackRate.value = this._playbackRate;
  56802. this._soundSource.onended = function () { _this._onended(); };
  56803. if (this._soundSource.buffer) {
  56804. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56805. }
  56806. }
  56807. this._startTime = startTime;
  56808. this.isPlaying = true;
  56809. this.isPaused = false;
  56810. }
  56811. catch (ex) {
  56812. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56813. }
  56814. }
  56815. };
  56816. Sound.prototype._onended = function () {
  56817. this.isPlaying = false;
  56818. if (this.onended) {
  56819. this.onended();
  56820. }
  56821. };
  56822. /**
  56823. * Stop the sound
  56824. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56825. */
  56826. Sound.prototype.stop = function (time) {
  56827. if (this.isPlaying) {
  56828. if (this._streaming) {
  56829. this._htmlAudioElement.pause();
  56830. // Test needed for Firefox or it will generate an Invalid State Error
  56831. if (this._htmlAudioElement.currentTime > 0) {
  56832. this._htmlAudioElement.currentTime = 0;
  56833. }
  56834. }
  56835. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56836. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56837. this._soundSource.stop(stopTime);
  56838. this._soundSource.onended = function () { };
  56839. if (!this.isPaused) {
  56840. this._startOffset = 0;
  56841. }
  56842. }
  56843. this.isPlaying = false;
  56844. }
  56845. };
  56846. Sound.prototype.pause = function () {
  56847. if (this.isPlaying) {
  56848. this.isPaused = true;
  56849. if (this._streaming) {
  56850. this._htmlAudioElement.pause();
  56851. }
  56852. else if (BABYLON.Engine.audioEngine.audioContext) {
  56853. this.stop(0);
  56854. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56855. }
  56856. }
  56857. };
  56858. Sound.prototype.setVolume = function (newVolume, time) {
  56859. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56860. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56861. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56862. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56863. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56864. }
  56865. else {
  56866. this._soundGain.gain.value = newVolume;
  56867. }
  56868. }
  56869. this._volume = newVolume;
  56870. };
  56871. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56872. this._playbackRate = newPlaybackRate;
  56873. if (this.isPlaying) {
  56874. if (this._streaming) {
  56875. this._htmlAudioElement.playbackRate = this._playbackRate;
  56876. }
  56877. else if (this._soundSource) {
  56878. this._soundSource.playbackRate.value = this._playbackRate;
  56879. }
  56880. }
  56881. };
  56882. Sound.prototype.getVolume = function () {
  56883. return this._volume;
  56884. };
  56885. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56886. var _this = this;
  56887. if (this._connectedMesh && this._registerFunc) {
  56888. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56889. this._registerFunc = null;
  56890. }
  56891. this._connectedMesh = meshToConnectTo;
  56892. if (!this.spatialSound) {
  56893. this.spatialSound = true;
  56894. this._createSpatialParameters();
  56895. if (this.isPlaying && this.loop) {
  56896. this.stop();
  56897. this.play();
  56898. }
  56899. }
  56900. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56901. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56902. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56903. };
  56904. Sound.prototype.detachFromMesh = function () {
  56905. if (this._connectedMesh && this._registerFunc) {
  56906. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56907. this._registerFunc = null;
  56908. this._connectedMesh = null;
  56909. }
  56910. };
  56911. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56912. if (!node.getBoundingInfo) {
  56913. return;
  56914. }
  56915. var mesh = node;
  56916. var boundingInfo = mesh.getBoundingInfo();
  56917. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56918. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56919. this._updateDirection();
  56920. }
  56921. };
  56922. Sound.prototype.clone = function () {
  56923. var _this = this;
  56924. if (!this._streaming) {
  56925. var setBufferAndRun = function () {
  56926. if (_this._isReadyToPlay) {
  56927. clonedSound._audioBuffer = _this.getAudioBuffer();
  56928. clonedSound._isReadyToPlay = true;
  56929. if (clonedSound.autoplay) {
  56930. clonedSound.play();
  56931. }
  56932. }
  56933. else {
  56934. window.setTimeout(setBufferAndRun, 300);
  56935. }
  56936. };
  56937. var currentOptions = {
  56938. autoplay: this.autoplay, loop: this.loop,
  56939. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56940. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56941. refDistance: this.refDistance, distanceModel: this.distanceModel
  56942. };
  56943. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56944. if (this.useCustomAttenuation) {
  56945. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56946. }
  56947. clonedSound.setPosition(this._position);
  56948. clonedSound.setPlaybackRate(this._playbackRate);
  56949. setBufferAndRun();
  56950. return clonedSound;
  56951. }
  56952. else {
  56953. return null;
  56954. }
  56955. };
  56956. Sound.prototype.getAudioBuffer = function () {
  56957. return this._audioBuffer;
  56958. };
  56959. Sound.prototype.serialize = function () {
  56960. var serializationObject = {
  56961. name: this.name,
  56962. url: this.name,
  56963. autoplay: this.autoplay,
  56964. loop: this.loop,
  56965. volume: this._volume,
  56966. spatialSound: this.spatialSound,
  56967. maxDistance: this.maxDistance,
  56968. rolloffFactor: this.rolloffFactor,
  56969. refDistance: this.refDistance,
  56970. distanceModel: this.distanceModel,
  56971. playbackRate: this._playbackRate,
  56972. panningModel: this._panningModel,
  56973. soundTrackId: this.soundTrackId
  56974. };
  56975. if (this.spatialSound) {
  56976. if (this._connectedMesh)
  56977. serializationObject.connectedMeshId = this._connectedMesh.id;
  56978. serializationObject.position = this._position.asArray();
  56979. serializationObject.refDistance = this.refDistance;
  56980. serializationObject.distanceModel = this.distanceModel;
  56981. serializationObject.isDirectional = this._isDirectional;
  56982. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56983. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56984. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56985. serializationObject.coneOuterGain = this._coneOuterGain;
  56986. }
  56987. return serializationObject;
  56988. };
  56989. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56990. var soundName = parsedSound.name;
  56991. var soundUrl;
  56992. if (parsedSound.url) {
  56993. soundUrl = rootUrl + parsedSound.url;
  56994. }
  56995. else {
  56996. soundUrl = rootUrl + soundName;
  56997. }
  56998. var options = {
  56999. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57000. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57001. rolloffFactor: parsedSound.rolloffFactor,
  57002. refDistance: parsedSound.refDistance,
  57003. distanceModel: parsedSound.distanceModel,
  57004. playbackRate: parsedSound.playbackRate
  57005. };
  57006. var newSound;
  57007. if (!sourceSound) {
  57008. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57009. scene._addPendingData(newSound);
  57010. }
  57011. else {
  57012. var setBufferAndRun = function () {
  57013. if (sourceSound._isReadyToPlay) {
  57014. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57015. newSound._isReadyToPlay = true;
  57016. if (newSound.autoplay) {
  57017. newSound.play();
  57018. }
  57019. }
  57020. else {
  57021. window.setTimeout(setBufferAndRun, 300);
  57022. }
  57023. };
  57024. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57025. setBufferAndRun();
  57026. }
  57027. if (parsedSound.position) {
  57028. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57029. newSound.setPosition(soundPosition);
  57030. }
  57031. if (parsedSound.isDirectional) {
  57032. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57033. if (parsedSound.localDirectionToMesh) {
  57034. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57035. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57036. }
  57037. }
  57038. if (parsedSound.connectedMeshId) {
  57039. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57040. if (connectedMesh) {
  57041. newSound.attachToMesh(connectedMesh);
  57042. }
  57043. }
  57044. return newSound;
  57045. };
  57046. return Sound;
  57047. }());
  57048. BABYLON.Sound = Sound;
  57049. })(BABYLON || (BABYLON = {}));
  57050. //# sourceMappingURL=babylon.sound.js.map
  57051. var BABYLON;
  57052. (function (BABYLON) {
  57053. var SoundTrack = /** @class */ (function () {
  57054. function SoundTrack(scene, options) {
  57055. this.id = -1;
  57056. this._isMainTrack = false;
  57057. this._isInitialized = false;
  57058. this._scene = scene;
  57059. this.soundCollection = new Array();
  57060. this._options = options;
  57061. if (!this._isMainTrack) {
  57062. this._scene.soundTracks.push(this);
  57063. this.id = this._scene.soundTracks.length - 1;
  57064. }
  57065. }
  57066. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57067. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57068. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57069. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57070. if (this._options) {
  57071. if (this._options.volume) {
  57072. this._outputAudioNode.gain.value = this._options.volume;
  57073. }
  57074. if (this._options.mainTrack) {
  57075. this._isMainTrack = this._options.mainTrack;
  57076. }
  57077. }
  57078. this._isInitialized = true;
  57079. }
  57080. };
  57081. SoundTrack.prototype.dispose = function () {
  57082. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57083. if (this._connectedAnalyser) {
  57084. this._connectedAnalyser.stopDebugCanvas();
  57085. }
  57086. while (this.soundCollection.length) {
  57087. this.soundCollection[0].dispose();
  57088. }
  57089. if (this._outputAudioNode) {
  57090. this._outputAudioNode.disconnect();
  57091. }
  57092. this._outputAudioNode = null;
  57093. }
  57094. };
  57095. SoundTrack.prototype.AddSound = function (sound) {
  57096. if (!this._isInitialized) {
  57097. this._initializeSoundTrackAudioGraph();
  57098. }
  57099. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57100. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57101. }
  57102. if (sound.soundTrackId) {
  57103. if (sound.soundTrackId === -1) {
  57104. this._scene.mainSoundTrack.RemoveSound(sound);
  57105. }
  57106. else {
  57107. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57108. }
  57109. }
  57110. this.soundCollection.push(sound);
  57111. sound.soundTrackId = this.id;
  57112. };
  57113. SoundTrack.prototype.RemoveSound = function (sound) {
  57114. var index = this.soundCollection.indexOf(sound);
  57115. if (index !== -1) {
  57116. this.soundCollection.splice(index, 1);
  57117. }
  57118. };
  57119. SoundTrack.prototype.setVolume = function (newVolume) {
  57120. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57121. this._outputAudioNode.gain.value = newVolume;
  57122. }
  57123. };
  57124. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57125. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57126. for (var i = 0; i < this.soundCollection.length; i++) {
  57127. this.soundCollection[i].switchPanningModelToHRTF();
  57128. }
  57129. }
  57130. };
  57131. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57132. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57133. for (var i = 0; i < this.soundCollection.length; i++) {
  57134. this.soundCollection[i].switchPanningModelToEqualPower();
  57135. }
  57136. }
  57137. };
  57138. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57139. if (this._connectedAnalyser) {
  57140. this._connectedAnalyser.stopDebugCanvas();
  57141. }
  57142. this._connectedAnalyser = analyser;
  57143. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57144. this._outputAudioNode.disconnect();
  57145. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57146. }
  57147. };
  57148. return SoundTrack;
  57149. }());
  57150. BABYLON.SoundTrack = SoundTrack;
  57151. })(BABYLON || (BABYLON = {}));
  57152. //# sourceMappingURL=babylon.soundtrack.js.map
  57153. var BABYLON;
  57154. (function (BABYLON) {
  57155. var Analyser = /** @class */ (function () {
  57156. function Analyser(scene) {
  57157. this.SMOOTHING = 0.75;
  57158. this.FFT_SIZE = 512;
  57159. this.BARGRAPHAMPLITUDE = 256;
  57160. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57161. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57162. this._scene = scene;
  57163. this._audioEngine = BABYLON.Engine.audioEngine;
  57164. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57165. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57166. this._webAudioAnalyser.minDecibels = -140;
  57167. this._webAudioAnalyser.maxDecibels = 0;
  57168. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57169. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57170. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57171. }
  57172. }
  57173. Analyser.prototype.getFrequencyBinCount = function () {
  57174. if (this._audioEngine.canUseWebAudio) {
  57175. return this._webAudioAnalyser.frequencyBinCount;
  57176. }
  57177. else {
  57178. return 0;
  57179. }
  57180. };
  57181. Analyser.prototype.getByteFrequencyData = function () {
  57182. if (this._audioEngine.canUseWebAudio) {
  57183. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57184. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57185. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57186. }
  57187. return this._byteFreqs;
  57188. };
  57189. Analyser.prototype.getByteTimeDomainData = function () {
  57190. if (this._audioEngine.canUseWebAudio) {
  57191. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57192. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57193. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57194. }
  57195. return this._byteTime;
  57196. };
  57197. Analyser.prototype.getFloatFrequencyData = function () {
  57198. if (this._audioEngine.canUseWebAudio) {
  57199. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57200. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57201. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57202. }
  57203. return this._floatFreqs;
  57204. };
  57205. Analyser.prototype.drawDebugCanvas = function () {
  57206. var _this = this;
  57207. if (this._audioEngine.canUseWebAudio) {
  57208. if (!this._debugCanvas) {
  57209. this._debugCanvas = document.createElement("canvas");
  57210. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57211. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57212. this._debugCanvas.style.position = "absolute";
  57213. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57214. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57215. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57216. document.body.appendChild(this._debugCanvas);
  57217. this._registerFunc = function () {
  57218. _this.drawDebugCanvas();
  57219. };
  57220. this._scene.registerBeforeRender(this._registerFunc);
  57221. }
  57222. if (this._registerFunc && this._debugCanvasContext) {
  57223. var workingArray = this.getByteFrequencyData();
  57224. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57225. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57226. // Draw the frequency domain chart.
  57227. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57228. var value = workingArray[i];
  57229. var percent = value / this.BARGRAPHAMPLITUDE;
  57230. var height = this.DEBUGCANVASSIZE.height * percent;
  57231. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57232. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57233. var hue = i / this.getFrequencyBinCount() * 360;
  57234. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57235. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57236. }
  57237. }
  57238. }
  57239. };
  57240. Analyser.prototype.stopDebugCanvas = function () {
  57241. if (this._debugCanvas) {
  57242. if (this._registerFunc) {
  57243. this._scene.unregisterBeforeRender(this._registerFunc);
  57244. this._registerFunc = null;
  57245. }
  57246. document.body.removeChild(this._debugCanvas);
  57247. this._debugCanvas = null;
  57248. this._debugCanvasContext = null;
  57249. }
  57250. };
  57251. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57252. if (this._audioEngine.canUseWebAudio) {
  57253. inputAudioNode.connect(this._webAudioAnalyser);
  57254. this._webAudioAnalyser.connect(outputAudioNode);
  57255. }
  57256. };
  57257. Analyser.prototype.dispose = function () {
  57258. if (this._audioEngine.canUseWebAudio) {
  57259. this._webAudioAnalyser.disconnect();
  57260. }
  57261. };
  57262. return Analyser;
  57263. }());
  57264. BABYLON.Analyser = Analyser;
  57265. })(BABYLON || (BABYLON = {}));
  57266. //# sourceMappingURL=babylon.analyser.js.map
  57267. var BABYLON;
  57268. (function (BABYLON) {
  57269. var CubeTexture = /** @class */ (function (_super) {
  57270. __extends(CubeTexture, _super);
  57271. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57272. if (extensions === void 0) { extensions = null; }
  57273. if (noMipmap === void 0) { noMipmap = false; }
  57274. if (files === void 0) { files = null; }
  57275. if (onLoad === void 0) { onLoad = null; }
  57276. if (onError === void 0) { onError = null; }
  57277. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57278. if (prefiltered === void 0) { prefiltered = false; }
  57279. if (forcedExtension === void 0) { forcedExtension = null; }
  57280. var _this = _super.call(this, scene) || this;
  57281. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57282. /**
  57283. * Gets or sets the center of the bounding box associated with the cube texture
  57284. * It must define where the camera used to render the texture was set
  57285. */
  57286. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57287. _this.name = rootUrl;
  57288. _this.url = rootUrl;
  57289. _this._noMipmap = noMipmap;
  57290. _this.hasAlpha = false;
  57291. _this._format = format;
  57292. _this._prefiltered = prefiltered;
  57293. _this.isCube = true;
  57294. _this._textureMatrix = BABYLON.Matrix.Identity();
  57295. if (prefiltered) {
  57296. _this.gammaSpace = false;
  57297. }
  57298. if (!rootUrl && !files) {
  57299. return _this;
  57300. }
  57301. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57302. var lastDot = rootUrl.lastIndexOf(".");
  57303. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57304. var isDDS = (extension === ".dds");
  57305. if (!files) {
  57306. if (!isDDS && !extensions) {
  57307. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57308. }
  57309. files = [];
  57310. if (extensions) {
  57311. for (var index = 0; index < extensions.length; index++) {
  57312. files.push(rootUrl + extensions[index]);
  57313. }
  57314. }
  57315. }
  57316. _this._files = files;
  57317. if (!_this._texture) {
  57318. if (!scene.useDelayedTextureLoading) {
  57319. if (prefiltered) {
  57320. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57321. }
  57322. else {
  57323. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57324. }
  57325. }
  57326. else {
  57327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57328. }
  57329. }
  57330. else if (onLoad) {
  57331. if (_this._texture.isReady) {
  57332. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57333. }
  57334. else {
  57335. _this._texture.onLoadedObservable.add(onLoad);
  57336. }
  57337. }
  57338. return _this;
  57339. }
  57340. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57341. get: function () {
  57342. return this._boundingBoxSize;
  57343. },
  57344. /**
  57345. * Gets or sets the size of the bounding box associated with the cube texture
  57346. * When defined, the cubemap will switch to local mode
  57347. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57348. * @example https://www.babylonjs-playground.com/#RNASML
  57349. */
  57350. set: function (value) {
  57351. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57352. return;
  57353. }
  57354. this._boundingBoxSize = value;
  57355. var scene = this.getScene();
  57356. if (scene) {
  57357. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57358. }
  57359. },
  57360. enumerable: true,
  57361. configurable: true
  57362. });
  57363. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57364. var rootUrlKey = "";
  57365. files.forEach(function (url) { return rootUrlKey += url; });
  57366. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57367. };
  57368. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57369. if (forcedExtension === void 0) { forcedExtension = null; }
  57370. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57371. };
  57372. // Methods
  57373. CubeTexture.prototype.delayLoad = function () {
  57374. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57375. return;
  57376. }
  57377. var scene = this.getScene();
  57378. if (!scene) {
  57379. return;
  57380. }
  57381. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57382. this._texture = this._getFromCache(this.url, this._noMipmap);
  57383. if (!this._texture) {
  57384. if (this._prefiltered) {
  57385. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57386. }
  57387. else {
  57388. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57389. }
  57390. }
  57391. };
  57392. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57393. return this._textureMatrix;
  57394. };
  57395. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57396. this._textureMatrix = value;
  57397. };
  57398. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57399. var texture = BABYLON.SerializationHelper.Parse(function () {
  57400. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57401. }, parsedTexture, scene);
  57402. // Local Cubemaps
  57403. if (parsedTexture.boundingBoxPosition) {
  57404. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57405. }
  57406. if (parsedTexture.boundingBoxSize) {
  57407. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57408. }
  57409. // Animations
  57410. if (parsedTexture.animations) {
  57411. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57412. var parsedAnimation = parsedTexture.animations[animationIndex];
  57413. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57414. }
  57415. }
  57416. return texture;
  57417. };
  57418. CubeTexture.prototype.clone = function () {
  57419. var _this = this;
  57420. return BABYLON.SerializationHelper.Clone(function () {
  57421. var scene = _this.getScene();
  57422. if (!scene) {
  57423. return _this;
  57424. }
  57425. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57426. }, this);
  57427. };
  57428. return CubeTexture;
  57429. }(BABYLON.BaseTexture));
  57430. BABYLON.CubeTexture = CubeTexture;
  57431. })(BABYLON || (BABYLON = {}));
  57432. //# sourceMappingURL=babylon.cubeTexture.js.map
  57433. var BABYLON;
  57434. (function (BABYLON) {
  57435. var RenderTargetTexture = /** @class */ (function (_super) {
  57436. __extends(RenderTargetTexture, _super);
  57437. /**
  57438. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57439. * or used a shadow, depth texture...
  57440. * @param name The friendly name of the texture
  57441. * @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)
  57442. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57443. * @param generateMipMaps True if mip maps need to be generated after render.
  57444. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57445. * @param type The type of the buffer in the RTT (int, half float, float...)
  57446. * @param isCube True if a cube texture needs to be created
  57447. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57448. * @param generateDepthBuffer True to generate a depth buffer
  57449. * @param generateStencilBuffer True to generate a stencil buffer
  57450. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57451. */
  57452. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57453. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57454. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57455. if (isCube === void 0) { isCube = false; }
  57456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57457. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57458. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57459. if (isMulti === void 0) { isMulti = false; }
  57460. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57461. _this.isCube = isCube;
  57462. /**
  57463. * Use this list to define the list of mesh you want to render.
  57464. */
  57465. _this.renderList = new Array();
  57466. _this.renderParticles = true;
  57467. _this.renderSprites = false;
  57468. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57469. _this.ignoreCameraViewport = false;
  57470. // Events
  57471. /**
  57472. * An event triggered when the texture is unbind.
  57473. * @type {BABYLON.Observable}
  57474. */
  57475. _this.onBeforeBindObservable = new BABYLON.Observable();
  57476. /**
  57477. * An event triggered when the texture is unbind.
  57478. * @type {BABYLON.Observable}
  57479. */
  57480. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57481. /**
  57482. * An event triggered before rendering the texture
  57483. * @type {BABYLON.Observable}
  57484. */
  57485. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57486. /**
  57487. * An event triggered after rendering the texture
  57488. * @type {BABYLON.Observable}
  57489. */
  57490. _this.onAfterRenderObservable = new BABYLON.Observable();
  57491. /**
  57492. * An event triggered after the texture clear
  57493. * @type {BABYLON.Observable}
  57494. */
  57495. _this.onClearObservable = new BABYLON.Observable();
  57496. _this._currentRefreshId = -1;
  57497. _this._refreshRate = 1;
  57498. _this._samples = 1;
  57499. /**
  57500. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57501. * It must define where the camera used to render the texture is set
  57502. */
  57503. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57504. scene = _this.getScene();
  57505. if (!scene) {
  57506. return _this;
  57507. }
  57508. _this._engine = scene.getEngine();
  57509. _this.name = name;
  57510. _this.isRenderTarget = true;
  57511. _this._initialSizeParameter = size;
  57512. _this._processSizeParameter(size);
  57513. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57514. });
  57515. _this._generateMipMaps = generateMipMaps ? true : false;
  57516. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57517. // Rendering groups
  57518. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57519. if (isMulti) {
  57520. return _this;
  57521. }
  57522. _this._renderTargetOptions = {
  57523. generateMipMaps: generateMipMaps,
  57524. type: type,
  57525. samplingMode: samplingMode,
  57526. generateDepthBuffer: generateDepthBuffer,
  57527. generateStencilBuffer: generateStencilBuffer
  57528. };
  57529. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57530. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57531. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57532. }
  57533. if (isCube) {
  57534. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57535. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57536. _this._textureMatrix = BABYLON.Matrix.Identity();
  57537. }
  57538. else {
  57539. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57540. }
  57541. return _this;
  57542. }
  57543. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57544. get: function () {
  57545. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57546. },
  57547. enumerable: true,
  57548. configurable: true
  57549. });
  57550. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57551. get: function () {
  57552. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57553. },
  57554. enumerable: true,
  57555. configurable: true
  57556. });
  57557. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57558. get: function () {
  57559. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57560. },
  57561. enumerable: true,
  57562. configurable: true
  57563. });
  57564. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57565. set: function (callback) {
  57566. if (this._onAfterUnbindObserver) {
  57567. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57568. }
  57569. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57570. },
  57571. enumerable: true,
  57572. configurable: true
  57573. });
  57574. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57575. set: function (callback) {
  57576. if (this._onBeforeRenderObserver) {
  57577. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57578. }
  57579. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57580. },
  57581. enumerable: true,
  57582. configurable: true
  57583. });
  57584. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57585. set: function (callback) {
  57586. if (this._onAfterRenderObserver) {
  57587. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57588. }
  57589. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57590. },
  57591. enumerable: true,
  57592. configurable: true
  57593. });
  57594. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57595. set: function (callback) {
  57596. if (this._onClearObserver) {
  57597. this.onClearObservable.remove(this._onClearObserver);
  57598. }
  57599. this._onClearObserver = this.onClearObservable.add(callback);
  57600. },
  57601. enumerable: true,
  57602. configurable: true
  57603. });
  57604. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57605. get: function () {
  57606. return this._renderTargetOptions;
  57607. },
  57608. enumerable: true,
  57609. configurable: true
  57610. });
  57611. RenderTargetTexture.prototype._onRatioRescale = function () {
  57612. if (this._sizeRatio) {
  57613. this.resize(this._initialSizeParameter);
  57614. }
  57615. };
  57616. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57617. get: function () {
  57618. return this._boundingBoxSize;
  57619. },
  57620. /**
  57621. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57622. * When defined, the cubemap will switch to local mode
  57623. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57624. * @example https://www.babylonjs-playground.com/#RNASML
  57625. */
  57626. set: function (value) {
  57627. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57628. return;
  57629. }
  57630. this._boundingBoxSize = value;
  57631. var scene = this.getScene();
  57632. if (scene) {
  57633. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57634. }
  57635. },
  57636. enumerable: true,
  57637. configurable: true
  57638. });
  57639. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57640. if (size.ratio) {
  57641. this._sizeRatio = size.ratio;
  57642. this._size = {
  57643. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57644. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57645. };
  57646. }
  57647. else {
  57648. this._size = size;
  57649. }
  57650. };
  57651. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57652. get: function () {
  57653. return this._samples;
  57654. },
  57655. set: function (value) {
  57656. if (this._samples === value) {
  57657. return;
  57658. }
  57659. var scene = this.getScene();
  57660. if (!scene) {
  57661. return;
  57662. }
  57663. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57664. },
  57665. enumerable: true,
  57666. configurable: true
  57667. });
  57668. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57669. this._currentRefreshId = -1;
  57670. };
  57671. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57672. get: function () {
  57673. return this._refreshRate;
  57674. },
  57675. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57676. set: function (value) {
  57677. this._refreshRate = value;
  57678. this.resetRefreshCounter();
  57679. },
  57680. enumerable: true,
  57681. configurable: true
  57682. });
  57683. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57684. if (!this._postProcessManager) {
  57685. var scene = this.getScene();
  57686. if (!scene) {
  57687. return;
  57688. }
  57689. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57690. this._postProcesses = new Array();
  57691. }
  57692. this._postProcesses.push(postProcess);
  57693. this._postProcesses[0].autoClear = false;
  57694. };
  57695. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57696. if (!this._postProcesses) {
  57697. return;
  57698. }
  57699. if (dispose) {
  57700. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57701. var postProcess = _a[_i];
  57702. postProcess.dispose();
  57703. }
  57704. }
  57705. this._postProcesses = [];
  57706. };
  57707. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57708. if (!this._postProcesses) {
  57709. return;
  57710. }
  57711. var index = this._postProcesses.indexOf(postProcess);
  57712. if (index === -1) {
  57713. return;
  57714. }
  57715. this._postProcesses.splice(index, 1);
  57716. if (this._postProcesses.length > 0) {
  57717. this._postProcesses[0].autoClear = false;
  57718. }
  57719. };
  57720. RenderTargetTexture.prototype._shouldRender = function () {
  57721. if (this._currentRefreshId === -1) {
  57722. this._currentRefreshId = 1;
  57723. return true;
  57724. }
  57725. if (this.refreshRate === this._currentRefreshId) {
  57726. this._currentRefreshId = 1;
  57727. return true;
  57728. }
  57729. this._currentRefreshId++;
  57730. return false;
  57731. };
  57732. RenderTargetTexture.prototype.getRenderSize = function () {
  57733. if (this._size.width) {
  57734. return this._size.width;
  57735. }
  57736. return this._size;
  57737. };
  57738. RenderTargetTexture.prototype.getRenderWidth = function () {
  57739. if (this._size.width) {
  57740. return this._size.width;
  57741. }
  57742. return this._size;
  57743. };
  57744. RenderTargetTexture.prototype.getRenderHeight = function () {
  57745. if (this._size.width) {
  57746. return this._size.height;
  57747. }
  57748. return this._size;
  57749. };
  57750. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57751. get: function () {
  57752. return true;
  57753. },
  57754. enumerable: true,
  57755. configurable: true
  57756. });
  57757. RenderTargetTexture.prototype.scale = function (ratio) {
  57758. var newSize = this.getRenderSize() * ratio;
  57759. this.resize(newSize);
  57760. };
  57761. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57762. if (this.isCube) {
  57763. return this._textureMatrix;
  57764. }
  57765. return _super.prototype.getReflectionTextureMatrix.call(this);
  57766. };
  57767. RenderTargetTexture.prototype.resize = function (size) {
  57768. this.releaseInternalTexture();
  57769. var scene = this.getScene();
  57770. if (!scene) {
  57771. return;
  57772. }
  57773. this._processSizeParameter(size);
  57774. if (this.isCube) {
  57775. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57776. }
  57777. else {
  57778. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57779. }
  57780. };
  57781. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57782. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57783. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57784. var scene = this.getScene();
  57785. if (!scene) {
  57786. return;
  57787. }
  57788. var engine = scene.getEngine();
  57789. if (this.useCameraPostProcesses !== undefined) {
  57790. useCameraPostProcess = this.useCameraPostProcesses;
  57791. }
  57792. if (this._waitingRenderList) {
  57793. this.renderList = [];
  57794. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57795. var id = this._waitingRenderList[index];
  57796. var mesh_1 = scene.getMeshByID(id);
  57797. if (mesh_1) {
  57798. this.renderList.push(mesh_1);
  57799. }
  57800. }
  57801. delete this._waitingRenderList;
  57802. }
  57803. // Is predicate defined?
  57804. if (this.renderListPredicate) {
  57805. if (this.renderList) {
  57806. this.renderList.splice(0); // Clear previous renderList
  57807. }
  57808. else {
  57809. this.renderList = [];
  57810. }
  57811. var scene = this.getScene();
  57812. if (!scene) {
  57813. return;
  57814. }
  57815. var sceneMeshes = scene.meshes;
  57816. for (var index = 0; index < sceneMeshes.length; index++) {
  57817. var mesh = sceneMeshes[index];
  57818. if (this.renderListPredicate(mesh)) {
  57819. this.renderList.push(mesh);
  57820. }
  57821. }
  57822. }
  57823. this.onBeforeBindObservable.notifyObservers(this);
  57824. // Set custom projection.
  57825. // Needs to be before binding to prevent changing the aspect ratio.
  57826. var camera;
  57827. if (this.activeCamera) {
  57828. camera = this.activeCamera;
  57829. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57830. if (this.activeCamera !== scene.activeCamera) {
  57831. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57832. }
  57833. }
  57834. else {
  57835. camera = scene.activeCamera;
  57836. if (camera) {
  57837. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57838. }
  57839. }
  57840. // Prepare renderingManager
  57841. this._renderingManager.reset();
  57842. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57843. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57844. var sceneRenderId = scene.getRenderId();
  57845. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57846. var mesh = currentRenderList[meshIndex];
  57847. if (mesh) {
  57848. if (!mesh.isReady(this.refreshRate === 0)) {
  57849. this.resetRefreshCounter();
  57850. continue;
  57851. }
  57852. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57853. var isMasked = void 0;
  57854. if (!this.renderList && camera) {
  57855. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57856. }
  57857. else {
  57858. isMasked = false;
  57859. }
  57860. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57861. mesh._activate(sceneRenderId);
  57862. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57863. var subMesh = mesh.subMeshes[subIndex];
  57864. scene._activeIndices.addCount(subMesh.indexCount, false);
  57865. this._renderingManager.dispatch(subMesh, mesh);
  57866. }
  57867. }
  57868. }
  57869. }
  57870. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57871. var particleSystem = scene.particleSystems[particleIndex];
  57872. var emitter = particleSystem.emitter;
  57873. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57874. continue;
  57875. }
  57876. if (currentRenderList.indexOf(emitter) >= 0) {
  57877. this._renderingManager.dispatchParticles(particleSystem);
  57878. }
  57879. }
  57880. if (this.isCube) {
  57881. for (var face = 0; face < 6; face++) {
  57882. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57883. scene.incrementRenderId();
  57884. scene.resetCachedMaterial();
  57885. }
  57886. }
  57887. else {
  57888. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57889. }
  57890. this.onAfterUnbindObservable.notifyObservers(this);
  57891. if (scene.activeCamera) {
  57892. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57893. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57894. }
  57895. engine.setViewport(scene.activeCamera.viewport);
  57896. }
  57897. scene.resetCachedMaterial();
  57898. };
  57899. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57900. var minimum = 128;
  57901. var x = renderDimension * scale;
  57902. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57903. // Ensure we don't exceed the render dimension (while staying POT)
  57904. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57905. };
  57906. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57907. var _this = this;
  57908. if (!this._texture) {
  57909. return;
  57910. }
  57911. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57912. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57913. });
  57914. };
  57915. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57916. var scene = this.getScene();
  57917. if (!scene) {
  57918. return;
  57919. }
  57920. var engine = scene.getEngine();
  57921. if (!this._texture) {
  57922. return;
  57923. }
  57924. // Bind
  57925. if (this._postProcessManager) {
  57926. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57927. }
  57928. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57929. if (this._texture) {
  57930. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57931. }
  57932. }
  57933. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57934. // Clear
  57935. if (this.onClearObservable.hasObservers()) {
  57936. this.onClearObservable.notifyObservers(engine);
  57937. }
  57938. else {
  57939. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57940. }
  57941. if (!this._doNotChangeAspectRatio) {
  57942. scene.updateTransformMatrix(true);
  57943. }
  57944. // Render
  57945. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57946. if (this._postProcessManager) {
  57947. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57948. }
  57949. else if (useCameraPostProcess) {
  57950. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57951. }
  57952. if (!this._doNotChangeAspectRatio) {
  57953. scene.updateTransformMatrix(true);
  57954. }
  57955. // Dump ?
  57956. if (dumpForDebug) {
  57957. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57958. }
  57959. // Unbind
  57960. if (!this.isCube || faceIndex === 5) {
  57961. if (this.isCube) {
  57962. if (faceIndex === 5) {
  57963. engine.generateMipMapsForCubemap(this._texture);
  57964. }
  57965. }
  57966. this.unbindFrameBuffer(engine, faceIndex);
  57967. }
  57968. else {
  57969. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57970. }
  57971. };
  57972. /**
  57973. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57974. * This allowed control for front to back rendering or reversly depending of the special needs.
  57975. *
  57976. * @param renderingGroupId The rendering group id corresponding to its index
  57977. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57978. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57979. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57980. */
  57981. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57982. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57983. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57984. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57985. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57986. };
  57987. /**
  57988. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57989. *
  57990. * @param renderingGroupId The rendering group id corresponding to its index
  57991. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57992. */
  57993. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57994. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57995. };
  57996. RenderTargetTexture.prototype.clone = function () {
  57997. var textureSize = this.getSize();
  57998. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  57999. // Base texture
  58000. newTexture.hasAlpha = this.hasAlpha;
  58001. newTexture.level = this.level;
  58002. // RenderTarget Texture
  58003. newTexture.coordinatesMode = this.coordinatesMode;
  58004. if (this.renderList) {
  58005. newTexture.renderList = this.renderList.slice(0);
  58006. }
  58007. return newTexture;
  58008. };
  58009. RenderTargetTexture.prototype.serialize = function () {
  58010. if (!this.name) {
  58011. return null;
  58012. }
  58013. var serializationObject = _super.prototype.serialize.call(this);
  58014. serializationObject.renderTargetSize = this.getRenderSize();
  58015. serializationObject.renderList = [];
  58016. if (this.renderList) {
  58017. for (var index = 0; index < this.renderList.length; index++) {
  58018. serializationObject.renderList.push(this.renderList[index].id);
  58019. }
  58020. }
  58021. return serializationObject;
  58022. };
  58023. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58024. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58025. var objBuffer = this.getInternalTexture();
  58026. var scene = this.getScene();
  58027. if (objBuffer && scene) {
  58028. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58029. }
  58030. };
  58031. RenderTargetTexture.prototype.dispose = function () {
  58032. if (this._postProcessManager) {
  58033. this._postProcessManager.dispose();
  58034. this._postProcessManager = null;
  58035. }
  58036. this.clearPostProcesses(true);
  58037. if (this._resizeObserver) {
  58038. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58039. this._resizeObserver = null;
  58040. }
  58041. this.renderList = null;
  58042. // Remove from custom render targets
  58043. var scene = this.getScene();
  58044. if (!scene) {
  58045. return;
  58046. }
  58047. var index = scene.customRenderTargets.indexOf(this);
  58048. if (index >= 0) {
  58049. scene.customRenderTargets.splice(index, 1);
  58050. }
  58051. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58052. var camera = _a[_i];
  58053. index = camera.customRenderTargets.indexOf(this);
  58054. if (index >= 0) {
  58055. camera.customRenderTargets.splice(index, 1);
  58056. }
  58057. }
  58058. _super.prototype.dispose.call(this);
  58059. };
  58060. RenderTargetTexture.prototype._rebuild = function () {
  58061. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58062. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58063. }
  58064. if (this._postProcessManager) {
  58065. this._postProcessManager._rebuild();
  58066. }
  58067. };
  58068. /**
  58069. * Clear the info related to rendering groups preventing retention point in material dispose.
  58070. */
  58071. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58072. if (this._renderingManager) {
  58073. this._renderingManager.freeRenderingGroups();
  58074. }
  58075. };
  58076. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58077. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58078. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58079. return RenderTargetTexture;
  58080. }(BABYLON.Texture));
  58081. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58082. })(BABYLON || (BABYLON = {}));
  58083. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58084. var BABYLON;
  58085. (function (BABYLON) {
  58086. ;
  58087. var MultiRenderTarget = /** @class */ (function (_super) {
  58088. __extends(MultiRenderTarget, _super);
  58089. function MultiRenderTarget(name, size, count, scene, options) {
  58090. var _this = this;
  58091. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58092. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58093. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58094. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58095. _this._engine = scene.getEngine();
  58096. if (!_this.isSupported) {
  58097. _this.dispose();
  58098. return;
  58099. }
  58100. var types = [];
  58101. var samplingModes = [];
  58102. for (var i = 0; i < count; i++) {
  58103. if (options && options.types && options.types[i] !== undefined) {
  58104. types.push(options.types[i]);
  58105. }
  58106. else {
  58107. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58108. }
  58109. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58110. samplingModes.push(options.samplingModes[i]);
  58111. }
  58112. else {
  58113. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58114. }
  58115. }
  58116. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58117. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58118. _this._size = size;
  58119. _this._multiRenderTargetOptions = {
  58120. samplingModes: samplingModes,
  58121. generateMipMaps: generateMipMaps,
  58122. generateDepthBuffer: generateDepthBuffer,
  58123. generateStencilBuffer: generateStencilBuffer,
  58124. generateDepthTexture: generateDepthTexture,
  58125. types: types,
  58126. textureCount: count
  58127. };
  58128. _this._createInternalTextures();
  58129. _this._createTextures();
  58130. return _this;
  58131. }
  58132. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58133. get: function () {
  58134. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58135. },
  58136. enumerable: true,
  58137. configurable: true
  58138. });
  58139. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58140. get: function () {
  58141. return this._textures;
  58142. },
  58143. enumerable: true,
  58144. configurable: true
  58145. });
  58146. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58147. get: function () {
  58148. return this._textures[this._textures.length - 1];
  58149. },
  58150. enumerable: true,
  58151. configurable: true
  58152. });
  58153. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58154. set: function (wrap) {
  58155. if (this._textures) {
  58156. for (var i = 0; i < this._textures.length; i++) {
  58157. this._textures[i].wrapU = wrap;
  58158. }
  58159. }
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58165. set: function (wrap) {
  58166. if (this._textures) {
  58167. for (var i = 0; i < this._textures.length; i++) {
  58168. this._textures[i].wrapV = wrap;
  58169. }
  58170. }
  58171. },
  58172. enumerable: true,
  58173. configurable: true
  58174. });
  58175. MultiRenderTarget.prototype._rebuild = function () {
  58176. this.releaseInternalTextures();
  58177. this._createInternalTextures();
  58178. for (var i = 0; i < this._internalTextures.length; i++) {
  58179. var texture = this._textures[i];
  58180. texture._texture = this._internalTextures[i];
  58181. }
  58182. // Keeps references to frame buffer and stencil/depth buffer
  58183. this._texture = this._internalTextures[0];
  58184. };
  58185. MultiRenderTarget.prototype._createInternalTextures = function () {
  58186. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58187. };
  58188. MultiRenderTarget.prototype._createTextures = function () {
  58189. this._textures = [];
  58190. for (var i = 0; i < this._internalTextures.length; i++) {
  58191. var texture = new BABYLON.Texture(null, this.getScene());
  58192. texture._texture = this._internalTextures[i];
  58193. this._textures.push(texture);
  58194. }
  58195. // Keeps references to frame buffer and stencil/depth buffer
  58196. this._texture = this._internalTextures[0];
  58197. };
  58198. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58199. get: function () {
  58200. return this._samples;
  58201. },
  58202. set: function (value) {
  58203. if (this._samples === value) {
  58204. return;
  58205. }
  58206. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58207. },
  58208. enumerable: true,
  58209. configurable: true
  58210. });
  58211. MultiRenderTarget.prototype.resize = function (size) {
  58212. this.releaseInternalTextures();
  58213. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58214. this._createInternalTextures();
  58215. };
  58216. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58217. var _this = this;
  58218. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58219. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58220. });
  58221. };
  58222. MultiRenderTarget.prototype.dispose = function () {
  58223. this.releaseInternalTextures();
  58224. _super.prototype.dispose.call(this);
  58225. };
  58226. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58227. if (!this._internalTextures) {
  58228. return;
  58229. }
  58230. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58231. if (this._internalTextures[i] !== undefined) {
  58232. this._internalTextures[i].dispose();
  58233. this._internalTextures.splice(i, 1);
  58234. }
  58235. }
  58236. };
  58237. return MultiRenderTarget;
  58238. }(BABYLON.RenderTargetTexture));
  58239. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58240. })(BABYLON || (BABYLON = {}));
  58241. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58242. var BABYLON;
  58243. (function (BABYLON) {
  58244. var MirrorTexture = /** @class */ (function (_super) {
  58245. __extends(MirrorTexture, _super);
  58246. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58247. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58248. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58249. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58250. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58251. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58252. _this._transformMatrix = BABYLON.Matrix.Zero();
  58253. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58254. _this._adaptiveBlurKernel = 0;
  58255. _this._blurKernelX = 0;
  58256. _this._blurKernelY = 0;
  58257. _this._blurRatio = 1.0;
  58258. _this.ignoreCameraViewport = true;
  58259. _this.onBeforeRenderObservable.add(function () {
  58260. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58261. _this._savedViewMatrix = scene.getViewMatrix();
  58262. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58263. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58264. scene.clipPlane = _this.mirrorPlane;
  58265. scene.getEngine().cullBackFaces = false;
  58266. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58267. });
  58268. _this.onAfterRenderObservable.add(function () {
  58269. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58270. scene.getEngine().cullBackFaces = true;
  58271. scene._mirroredCameraPosition = null;
  58272. delete scene.clipPlane;
  58273. });
  58274. return _this;
  58275. }
  58276. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58277. get: function () {
  58278. return this._blurRatio;
  58279. },
  58280. set: function (value) {
  58281. if (this._blurRatio === value) {
  58282. return;
  58283. }
  58284. this._blurRatio = value;
  58285. this._preparePostProcesses();
  58286. },
  58287. enumerable: true,
  58288. configurable: true
  58289. });
  58290. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58291. set: function (value) {
  58292. this._adaptiveBlurKernel = value;
  58293. this._autoComputeBlurKernel();
  58294. },
  58295. enumerable: true,
  58296. configurable: true
  58297. });
  58298. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58299. set: function (value) {
  58300. this.blurKernelX = value;
  58301. this.blurKernelY = value;
  58302. },
  58303. enumerable: true,
  58304. configurable: true
  58305. });
  58306. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58307. get: function () {
  58308. return this._blurKernelX;
  58309. },
  58310. set: function (value) {
  58311. if (this._blurKernelX === value) {
  58312. return;
  58313. }
  58314. this._blurKernelX = value;
  58315. this._preparePostProcesses();
  58316. },
  58317. enumerable: true,
  58318. configurable: true
  58319. });
  58320. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58321. get: function () {
  58322. return this._blurKernelY;
  58323. },
  58324. set: function (value) {
  58325. if (this._blurKernelY === value) {
  58326. return;
  58327. }
  58328. this._blurKernelY = value;
  58329. this._preparePostProcesses();
  58330. },
  58331. enumerable: true,
  58332. configurable: true
  58333. });
  58334. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58335. var engine = this.getScene().getEngine();
  58336. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58337. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58338. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58339. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58340. };
  58341. MirrorTexture.prototype._onRatioRescale = function () {
  58342. if (this._sizeRatio) {
  58343. this.resize(this._initialSizeParameter);
  58344. if (!this._adaptiveBlurKernel) {
  58345. this._preparePostProcesses();
  58346. }
  58347. }
  58348. if (this._adaptiveBlurKernel) {
  58349. this._autoComputeBlurKernel();
  58350. }
  58351. };
  58352. MirrorTexture.prototype._preparePostProcesses = function () {
  58353. this.clearPostProcesses(true);
  58354. if (this._blurKernelX && this._blurKernelY) {
  58355. var engine = this.getScene().getEngine();
  58356. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58357. 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);
  58358. this._blurX.autoClear = false;
  58359. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58360. this._blurX.inputTexture = this._texture;
  58361. }
  58362. else {
  58363. this._blurX.alwaysForcePOT = true;
  58364. }
  58365. 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);
  58366. this._blurY.autoClear = false;
  58367. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58368. this.addPostProcess(this._blurX);
  58369. this.addPostProcess(this._blurY);
  58370. }
  58371. else {
  58372. if (this._blurY) {
  58373. this.removePostProcess(this._blurY);
  58374. this._blurY.dispose();
  58375. this._blurY = null;
  58376. }
  58377. if (this._blurX) {
  58378. this.removePostProcess(this._blurX);
  58379. this._blurX.dispose();
  58380. this._blurX = null;
  58381. }
  58382. }
  58383. };
  58384. MirrorTexture.prototype.clone = function () {
  58385. var scene = this.getScene();
  58386. if (!scene) {
  58387. return this;
  58388. }
  58389. var textureSize = this.getSize();
  58390. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58391. // Base texture
  58392. newTexture.hasAlpha = this.hasAlpha;
  58393. newTexture.level = this.level;
  58394. // Mirror Texture
  58395. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58396. if (this.renderList) {
  58397. newTexture.renderList = this.renderList.slice(0);
  58398. }
  58399. return newTexture;
  58400. };
  58401. MirrorTexture.prototype.serialize = function () {
  58402. if (!this.name) {
  58403. return null;
  58404. }
  58405. var serializationObject = _super.prototype.serialize.call(this);
  58406. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58407. return serializationObject;
  58408. };
  58409. return MirrorTexture;
  58410. }(BABYLON.RenderTargetTexture));
  58411. BABYLON.MirrorTexture = MirrorTexture;
  58412. })(BABYLON || (BABYLON = {}));
  58413. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58414. var BABYLON;
  58415. (function (BABYLON) {
  58416. /**
  58417. * Creates a refraction texture used by refraction channel of the standard material.
  58418. * @param name the texture name
  58419. * @param size size of the underlying texture
  58420. * @param scene root scene
  58421. */
  58422. var RefractionTexture = /** @class */ (function (_super) {
  58423. __extends(RefractionTexture, _super);
  58424. function RefractionTexture(name, size, scene, generateMipMaps) {
  58425. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58426. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58427. _this.depth = 2.0;
  58428. _this.onBeforeRenderObservable.add(function () {
  58429. scene.clipPlane = _this.refractionPlane;
  58430. });
  58431. _this.onAfterRenderObservable.add(function () {
  58432. delete scene.clipPlane;
  58433. });
  58434. return _this;
  58435. }
  58436. RefractionTexture.prototype.clone = function () {
  58437. var scene = this.getScene();
  58438. if (!scene) {
  58439. return this;
  58440. }
  58441. var textureSize = this.getSize();
  58442. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58443. // Base texture
  58444. newTexture.hasAlpha = this.hasAlpha;
  58445. newTexture.level = this.level;
  58446. // Refraction Texture
  58447. newTexture.refractionPlane = this.refractionPlane.clone();
  58448. if (this.renderList) {
  58449. newTexture.renderList = this.renderList.slice(0);
  58450. }
  58451. newTexture.depth = this.depth;
  58452. return newTexture;
  58453. };
  58454. RefractionTexture.prototype.serialize = function () {
  58455. if (!this.name) {
  58456. return null;
  58457. }
  58458. var serializationObject = _super.prototype.serialize.call(this);
  58459. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58460. serializationObject.depth = this.depth;
  58461. return serializationObject;
  58462. };
  58463. return RefractionTexture;
  58464. }(BABYLON.RenderTargetTexture));
  58465. BABYLON.RefractionTexture = RefractionTexture;
  58466. })(BABYLON || (BABYLON = {}));
  58467. //# sourceMappingURL=babylon.refractionTexture.js.map
  58468. var BABYLON;
  58469. (function (BABYLON) {
  58470. var DynamicTexture = /** @class */ (function (_super) {
  58471. __extends(DynamicTexture, _super);
  58472. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58473. if (scene === void 0) { scene = null; }
  58474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58475. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58476. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58477. _this.name = name;
  58478. _this._engine = _this.getScene().getEngine();
  58479. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58480. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58481. _this._generateMipMaps = generateMipMaps;
  58482. if (options.getContext) {
  58483. _this._canvas = options;
  58484. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58485. }
  58486. else {
  58487. _this._canvas = document.createElement("canvas");
  58488. if (options.width) {
  58489. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58490. }
  58491. else {
  58492. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58493. }
  58494. }
  58495. var textureSize = _this.getSize();
  58496. _this._canvas.width = textureSize.width;
  58497. _this._canvas.height = textureSize.height;
  58498. _this._context = _this._canvas.getContext("2d");
  58499. return _this;
  58500. }
  58501. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58502. get: function () {
  58503. return true;
  58504. },
  58505. enumerable: true,
  58506. configurable: true
  58507. });
  58508. DynamicTexture.prototype._recreate = function (textureSize) {
  58509. this._canvas.width = textureSize.width;
  58510. this._canvas.height = textureSize.height;
  58511. this.releaseInternalTexture();
  58512. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58513. };
  58514. DynamicTexture.prototype.scale = function (ratio) {
  58515. var textureSize = this.getSize();
  58516. textureSize.width *= ratio;
  58517. textureSize.height *= ratio;
  58518. this._recreate(textureSize);
  58519. };
  58520. DynamicTexture.prototype.scaleTo = function (width, height) {
  58521. var textureSize = this.getSize();
  58522. textureSize.width = width;
  58523. textureSize.height = height;
  58524. this._recreate(textureSize);
  58525. };
  58526. DynamicTexture.prototype.getContext = function () {
  58527. return this._context;
  58528. };
  58529. DynamicTexture.prototype.clear = function () {
  58530. var size = this.getSize();
  58531. this._context.fillRect(0, 0, size.width, size.height);
  58532. };
  58533. DynamicTexture.prototype.update = function (invertY) {
  58534. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58535. };
  58536. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58537. if (update === void 0) { update = true; }
  58538. var size = this.getSize();
  58539. if (clearColor) {
  58540. this._context.fillStyle = clearColor;
  58541. this._context.fillRect(0, 0, size.width, size.height);
  58542. }
  58543. this._context.font = font;
  58544. if (x === null || x === undefined) {
  58545. var textSize = this._context.measureText(text);
  58546. x = (size.width - textSize.width) / 2;
  58547. }
  58548. if (y === null || y === undefined) {
  58549. var fontSize = parseInt((font.replace(/\D/g, '')));
  58550. ;
  58551. y = (size.height / 2) + (fontSize / 3.65);
  58552. }
  58553. this._context.fillStyle = color;
  58554. this._context.fillText(text, x, y);
  58555. if (update) {
  58556. this.update(invertY);
  58557. }
  58558. };
  58559. DynamicTexture.prototype.clone = function () {
  58560. var scene = this.getScene();
  58561. if (!scene) {
  58562. return this;
  58563. }
  58564. var textureSize = this.getSize();
  58565. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58566. // Base texture
  58567. newTexture.hasAlpha = this.hasAlpha;
  58568. newTexture.level = this.level;
  58569. // Dynamic Texture
  58570. newTexture.wrapU = this.wrapU;
  58571. newTexture.wrapV = this.wrapV;
  58572. return newTexture;
  58573. };
  58574. DynamicTexture.prototype._rebuild = function () {
  58575. this.update();
  58576. };
  58577. return DynamicTexture;
  58578. }(BABYLON.Texture));
  58579. BABYLON.DynamicTexture = DynamicTexture;
  58580. })(BABYLON || (BABYLON = {}));
  58581. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58582. var BABYLON;
  58583. (function (BABYLON) {
  58584. var VideoTexture = /** @class */ (function (_super) {
  58585. __extends(VideoTexture, _super);
  58586. /**
  58587. * Creates a video texture.
  58588. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58589. * @param {string | null} name optional name, will detect from video source, if not defined
  58590. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58591. * @param {BABYLON.Scene} scene is obviously the current scene.
  58592. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58593. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58594. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58595. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58596. */
  58597. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58598. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58599. if (invertY === void 0) { invertY = false; }
  58600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58601. if (settings === void 0) { settings = {
  58602. autoPlay: true,
  58603. loop: true,
  58604. autoUpdateTexture: true,
  58605. }; }
  58606. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58607. _this._createInternalTexture = function () {
  58608. if (_this._texture != null) {
  58609. return;
  58610. }
  58611. if (!_this._engine.needPOTTextures ||
  58612. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58613. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58614. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58615. }
  58616. else {
  58617. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58618. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58619. _this._generateMipMaps = false;
  58620. }
  58621. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58622. _this._texture.isReady = true;
  58623. _this._updateInternalTexture();
  58624. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58625. _this.onLoadObservable.notifyObservers(_this);
  58626. }
  58627. };
  58628. _this.reset = function () {
  58629. if (_this._texture == null) {
  58630. return;
  58631. }
  58632. _this._texture.dispose();
  58633. _this._texture = null;
  58634. };
  58635. _this._updateInternalTexture = function (e) {
  58636. if (_this._texture == null || !_this._texture.isReady) {
  58637. return;
  58638. }
  58639. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58640. return;
  58641. }
  58642. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58643. };
  58644. _this._engine = _this.getScene().getEngine();
  58645. _this._generateMipMaps = generateMipMaps;
  58646. _this._samplingMode = samplingMode;
  58647. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58648. _this.name = name || _this._getName(src);
  58649. _this.video = _this._getVideo(src);
  58650. if (settings.autoPlay !== undefined) {
  58651. _this.video.autoplay = settings.autoPlay;
  58652. }
  58653. if (settings.loop !== undefined) {
  58654. _this.video.loop = settings.loop;
  58655. }
  58656. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58657. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58658. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58659. _this.video.addEventListener("emptied", _this.reset);
  58660. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58661. _this._createInternalTexture();
  58662. }
  58663. return _this;
  58664. }
  58665. VideoTexture.prototype._getName = function (src) {
  58666. if (src instanceof HTMLVideoElement) {
  58667. return src.currentSrc;
  58668. }
  58669. if (typeof src === "object") {
  58670. return src.toString();
  58671. }
  58672. return src;
  58673. };
  58674. ;
  58675. VideoTexture.prototype._getVideo = function (src) {
  58676. if (src instanceof HTMLVideoElement) {
  58677. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58678. return src;
  58679. }
  58680. var video = document.createElement("video");
  58681. if (typeof src === "string") {
  58682. BABYLON.Tools.SetCorsBehavior(src, video);
  58683. video.src = src;
  58684. }
  58685. else {
  58686. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58687. src.forEach(function (url) {
  58688. var source = document.createElement("source");
  58689. source.src = url;
  58690. video.appendChild(source);
  58691. });
  58692. }
  58693. return video;
  58694. };
  58695. ;
  58696. /**
  58697. * Internal method to initiate `update`.
  58698. */
  58699. VideoTexture.prototype._rebuild = function () {
  58700. this.update();
  58701. };
  58702. /**
  58703. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58704. */
  58705. VideoTexture.prototype.update = function () {
  58706. if (!this.autoUpdateTexture) {
  58707. // Expecting user to call `updateTexture` manually
  58708. return;
  58709. }
  58710. this.updateTexture(true);
  58711. };
  58712. /**
  58713. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58714. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58715. */
  58716. VideoTexture.prototype.updateTexture = function (isVisible) {
  58717. if (!isVisible) {
  58718. return;
  58719. }
  58720. if (this.video.paused) {
  58721. return;
  58722. }
  58723. this._updateInternalTexture();
  58724. };
  58725. /**
  58726. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58727. * @param url New url.
  58728. */
  58729. VideoTexture.prototype.updateURL = function (url) {
  58730. this.video.src = url;
  58731. };
  58732. VideoTexture.prototype.dispose = function () {
  58733. _super.prototype.dispose.call(this);
  58734. this.video.removeEventListener("canplay", this._createInternalTexture);
  58735. this.video.removeEventListener("paused", this._updateInternalTexture);
  58736. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58737. this.video.removeEventListener("emptied", this.reset);
  58738. this.video.pause();
  58739. };
  58740. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58741. var video = document.createElement("video");
  58742. var constraintsDeviceId;
  58743. if (constraints && constraints.deviceId) {
  58744. constraintsDeviceId = {
  58745. exact: constraints.deviceId,
  58746. };
  58747. }
  58748. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58749. if (navigator.mediaDevices) {
  58750. navigator.mediaDevices.getUserMedia({ video: constraints })
  58751. .then(function (stream) {
  58752. if (video.mozSrcObject !== undefined) {
  58753. // hack for Firefox < 19
  58754. video.mozSrcObject = stream;
  58755. }
  58756. else {
  58757. video.srcObject = stream;
  58758. }
  58759. var onPlaying = function () {
  58760. if (onReady) {
  58761. onReady(new VideoTexture("video", video, scene, true, true));
  58762. }
  58763. video.removeEventListener("playing", onPlaying);
  58764. };
  58765. video.addEventListener("playing", onPlaying);
  58766. video.play();
  58767. })
  58768. .catch(function (err) {
  58769. BABYLON.Tools.Error(err.name);
  58770. });
  58771. }
  58772. else {
  58773. navigator.getUserMedia =
  58774. navigator.getUserMedia ||
  58775. navigator.webkitGetUserMedia ||
  58776. navigator.mozGetUserMedia ||
  58777. navigator.msGetUserMedia;
  58778. if (navigator.getUserMedia) {
  58779. navigator.getUserMedia({
  58780. video: {
  58781. deviceId: constraintsDeviceId,
  58782. width: {
  58783. min: (constraints && constraints.minWidth) || 256,
  58784. max: (constraints && constraints.maxWidth) || 640,
  58785. },
  58786. height: {
  58787. min: (constraints && constraints.minHeight) || 256,
  58788. max: (constraints && constraints.maxHeight) || 480,
  58789. },
  58790. },
  58791. }, function (stream) {
  58792. if (video.mozSrcObject !== undefined) {
  58793. // hack for Firefox < 19
  58794. video.mozSrcObject = stream;
  58795. }
  58796. else {
  58797. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58798. }
  58799. video.play();
  58800. if (onReady) {
  58801. onReady(new VideoTexture("video", video, scene, true, true));
  58802. }
  58803. }, function (e) {
  58804. BABYLON.Tools.Error(e.name);
  58805. });
  58806. }
  58807. }
  58808. };
  58809. return VideoTexture;
  58810. }(BABYLON.Texture));
  58811. BABYLON.VideoTexture = VideoTexture;
  58812. })(BABYLON || (BABYLON = {}));
  58813. //# sourceMappingURL=babylon.videoTexture.js.map
  58814. var BABYLON;
  58815. (function (BABYLON) {
  58816. var RawTexture = /** @class */ (function (_super) {
  58817. __extends(RawTexture, _super);
  58818. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58819. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58820. if (invertY === void 0) { invertY = false; }
  58821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58822. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58823. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58824. _this.format = format;
  58825. _this._engine = scene.getEngine();
  58826. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58827. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58828. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58829. return _this;
  58830. }
  58831. RawTexture.prototype.update = function (data) {
  58832. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58833. };
  58834. // Statics
  58835. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58837. if (invertY === void 0) { invertY = false; }
  58838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58839. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58840. };
  58841. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58842. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58843. if (invertY === void 0) { invertY = false; }
  58844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58845. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58846. };
  58847. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58848. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58849. if (invertY === void 0) { invertY = false; }
  58850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58851. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58852. };
  58853. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58854. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58855. if (invertY === void 0) { invertY = false; }
  58856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58857. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58858. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58859. };
  58860. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58861. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58862. if (invertY === void 0) { invertY = false; }
  58863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58864. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58865. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58866. };
  58867. return RawTexture;
  58868. }(BABYLON.Texture));
  58869. BABYLON.RawTexture = RawTexture;
  58870. })(BABYLON || (BABYLON = {}));
  58871. //# sourceMappingURL=babylon.rawTexture.js.map
  58872. var BABYLON;
  58873. (function (BABYLON) {
  58874. /**
  58875. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58876. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58877. */
  58878. var PostProcess = /** @class */ (function () {
  58879. /**
  58880. * Creates a new instance of @see PostProcess
  58881. * @param name The name of the PostProcess.
  58882. * @param fragmentUrl The url of the fragment shader to be used.
  58883. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58884. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58885. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58886. * @param camera The camera to apply the render pass to.
  58887. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58888. * @param engine The engine which the post process will be applied. (default: current engine)
  58889. * @param reusable If the post process can be reused on the same frame. (default: false)
  58890. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58891. * @param textureType Type of textures used when performing the post process. (default: 0)
  58892. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58893. * @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
  58894. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58895. */
  58896. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58898. if (defines === void 0) { defines = null; }
  58899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58900. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58901. if (blockCompilation === void 0) { blockCompilation = false; }
  58902. this.name = name;
  58903. /**
  58904. * Width of the texture to apply the post process on
  58905. */
  58906. this.width = -1;
  58907. /**
  58908. * Height of the texture to apply the post process on
  58909. */
  58910. this.height = -1;
  58911. /**
  58912. * If the buffer needs to be cleared before applying the post process. (default: true)
  58913. * Should be set to false if shader will overwrite all previous pixels.
  58914. */
  58915. this.autoClear = true;
  58916. /**
  58917. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58918. */
  58919. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58920. /**
  58921. * Animations to be used for the post processing
  58922. */
  58923. this.animations = new Array();
  58924. /**
  58925. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58926. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58927. */
  58928. this.enablePixelPerfectMode = false;
  58929. /**
  58930. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58931. */
  58932. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58933. /**
  58934. * Force textures to be a power of two (default: false)
  58935. */
  58936. this.alwaysForcePOT = false;
  58937. /**
  58938. * Number of sample textures (default: 1)
  58939. */
  58940. this.samples = 1;
  58941. /**
  58942. * Modify the scale of the post process to be the same as the viewport (default: false)
  58943. */
  58944. this.adaptScaleToCurrentViewport = false;
  58945. this._reusable = false;
  58946. /**
  58947. * Smart array of input and output textures for the post process.
  58948. */
  58949. this._textures = new BABYLON.SmartArray(2);
  58950. /**
  58951. * The index in _textures that corresponds to the output texture.
  58952. */
  58953. this._currentRenderTextureInd = 0;
  58954. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58955. this._texelSize = BABYLON.Vector2.Zero();
  58956. // Events
  58957. /**
  58958. * An event triggered when the postprocess is activated.
  58959. * @type {BABYLON.Observable}
  58960. */
  58961. this.onActivateObservable = new BABYLON.Observable();
  58962. /**
  58963. * An event triggered when the postprocess changes its size.
  58964. * @type {BABYLON.Observable}
  58965. */
  58966. this.onSizeChangedObservable = new BABYLON.Observable();
  58967. /**
  58968. * An event triggered when the postprocess applies its effect.
  58969. * @type {BABYLON.Observable}
  58970. */
  58971. this.onApplyObservable = new BABYLON.Observable();
  58972. /**
  58973. * An event triggered before rendering the postprocess
  58974. * @type {BABYLON.Observable}
  58975. */
  58976. this.onBeforeRenderObservable = new BABYLON.Observable();
  58977. /**
  58978. * An event triggered after rendering the postprocess
  58979. * @type {BABYLON.Observable}
  58980. */
  58981. this.onAfterRenderObservable = new BABYLON.Observable();
  58982. if (camera != null) {
  58983. this._camera = camera;
  58984. this._scene = camera.getScene();
  58985. camera.attachPostProcess(this);
  58986. this._engine = this._scene.getEngine();
  58987. this._scene.postProcesses.push(this);
  58988. }
  58989. else if (engine) {
  58990. this._engine = engine;
  58991. this._engine.postProcesses.push(this);
  58992. }
  58993. this._options = options;
  58994. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58995. this._reusable = reusable || false;
  58996. this._textureType = textureType;
  58997. this._samplers = samplers || [];
  58998. this._samplers.push("textureSampler");
  58999. this._fragmentUrl = fragmentUrl;
  59000. this._vertexUrl = vertexUrl;
  59001. this._parameters = parameters || [];
  59002. this._parameters.push("scale");
  59003. this._indexParameters = indexParameters;
  59004. if (!blockCompilation) {
  59005. this.updateEffect(defines);
  59006. }
  59007. }
  59008. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59009. /**
  59010. * A function that is added to the onActivateObservable
  59011. */
  59012. set: function (callback) {
  59013. if (this._onActivateObserver) {
  59014. this.onActivateObservable.remove(this._onActivateObserver);
  59015. }
  59016. if (callback) {
  59017. this._onActivateObserver = this.onActivateObservable.add(callback);
  59018. }
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59024. /**
  59025. * A function that is added to the onSizeChangedObservable
  59026. */
  59027. set: function (callback) {
  59028. if (this._onSizeChangedObserver) {
  59029. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59030. }
  59031. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. Object.defineProperty(PostProcess.prototype, "onApply", {
  59037. /**
  59038. * A function that is added to the onApplyObservable
  59039. */
  59040. set: function (callback) {
  59041. if (this._onApplyObserver) {
  59042. this.onApplyObservable.remove(this._onApplyObserver);
  59043. }
  59044. this._onApplyObserver = this.onApplyObservable.add(callback);
  59045. },
  59046. enumerable: true,
  59047. configurable: true
  59048. });
  59049. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59050. /**
  59051. * A function that is added to the onBeforeRenderObservable
  59052. */
  59053. set: function (callback) {
  59054. if (this._onBeforeRenderObserver) {
  59055. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59056. }
  59057. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59063. /**
  59064. * A function that is added to the onAfterRenderObservable
  59065. */
  59066. set: function (callback) {
  59067. if (this._onAfterRenderObserver) {
  59068. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59069. }
  59070. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59071. },
  59072. enumerable: true,
  59073. configurable: true
  59074. });
  59075. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59076. /**
  59077. * 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
  59078. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59079. */
  59080. get: function () {
  59081. return this._textures.data[this._currentRenderTextureInd];
  59082. },
  59083. set: function (value) {
  59084. this._forcedOutputTexture = value;
  59085. },
  59086. enumerable: true,
  59087. configurable: true
  59088. });
  59089. /**
  59090. * Gets the camera which post process is applied to.
  59091. * @returns The camera the post process is applied to.
  59092. */
  59093. PostProcess.prototype.getCamera = function () {
  59094. return this._camera;
  59095. };
  59096. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59097. /**
  59098. * Gets the texel size of the postprocess.
  59099. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59100. */
  59101. get: function () {
  59102. if (this._shareOutputWithPostProcess) {
  59103. return this._shareOutputWithPostProcess.texelSize;
  59104. }
  59105. if (this._forcedOutputTexture) {
  59106. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59107. }
  59108. return this._texelSize;
  59109. },
  59110. enumerable: true,
  59111. configurable: true
  59112. });
  59113. /**
  59114. * Gets the engine which this post process belongs to.
  59115. * @returns The engine the post process was enabled with.
  59116. */
  59117. PostProcess.prototype.getEngine = function () {
  59118. return this._engine;
  59119. };
  59120. /**
  59121. * The effect that is created when initializing the post process.
  59122. * @returns The created effect corrisponding the the postprocess.
  59123. */
  59124. PostProcess.prototype.getEffect = function () {
  59125. return this._effect;
  59126. };
  59127. /**
  59128. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59129. * @param postProcess The post process to share the output with.
  59130. * @returns This post process.
  59131. */
  59132. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59133. this._disposeTextures();
  59134. this._shareOutputWithPostProcess = postProcess;
  59135. return this;
  59136. };
  59137. /**
  59138. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59139. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59140. */
  59141. PostProcess.prototype.useOwnOutput = function () {
  59142. if (this._textures.length == 0) {
  59143. this._textures = new BABYLON.SmartArray(2);
  59144. }
  59145. this._shareOutputWithPostProcess = null;
  59146. };
  59147. /**
  59148. * Updates the effect with the current post process compile time values and recompiles the shader.
  59149. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59150. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59151. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59152. * @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
  59153. * @param onCompiled Called when the shader has been compiled.
  59154. * @param onError Called if there is an error when compiling a shader.
  59155. */
  59156. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59157. if (defines === void 0) { defines = null; }
  59158. if (uniforms === void 0) { uniforms = null; }
  59159. if (samplers === void 0) { samplers = null; }
  59160. 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);
  59161. };
  59162. /**
  59163. * The post process is reusable if it can be used multiple times within one frame.
  59164. * @returns If the post process is reusable
  59165. */
  59166. PostProcess.prototype.isReusable = function () {
  59167. return this._reusable;
  59168. };
  59169. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59170. PostProcess.prototype.markTextureDirty = function () {
  59171. this.width = -1;
  59172. };
  59173. /**
  59174. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59175. * 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.
  59176. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59177. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59178. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59179. */
  59180. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59181. var _this = this;
  59182. if (sourceTexture === void 0) { sourceTexture = null; }
  59183. camera = camera || this._camera;
  59184. var scene = camera.getScene();
  59185. var engine = scene.getEngine();
  59186. var maxSize = engine.getCaps().maxTextureSize;
  59187. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59188. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59189. // 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
  59190. var webVRCamera = camera.parent;
  59191. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59192. requiredWidth /= 2;
  59193. }
  59194. var desiredWidth = (this._options.width || requiredWidth);
  59195. var desiredHeight = this._options.height || requiredHeight;
  59196. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59197. if (this.adaptScaleToCurrentViewport) {
  59198. var currentViewport = engine.currentViewport;
  59199. if (currentViewport) {
  59200. desiredWidth *= currentViewport.width;
  59201. desiredHeight *= currentViewport.height;
  59202. }
  59203. }
  59204. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59205. if (!this._options.width) {
  59206. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59207. }
  59208. if (!this._options.height) {
  59209. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59210. }
  59211. }
  59212. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59213. if (this._textures.length > 0) {
  59214. for (var i = 0; i < this._textures.length; i++) {
  59215. this._engine._releaseTexture(this._textures.data[i]);
  59216. }
  59217. this._textures.reset();
  59218. }
  59219. this.width = desiredWidth;
  59220. this.height = desiredHeight;
  59221. var textureSize = { width: this.width, height: this.height };
  59222. var textureOptions = {
  59223. generateMipMaps: false,
  59224. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59225. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59226. samplingMode: this.renderTargetSamplingMode,
  59227. type: this._textureType
  59228. };
  59229. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59230. if (this._reusable) {
  59231. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59232. }
  59233. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59234. this.onSizeChangedObservable.notifyObservers(this);
  59235. }
  59236. this._textures.forEach(function (texture) {
  59237. if (texture.samples !== _this.samples) {
  59238. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59239. }
  59240. });
  59241. }
  59242. var target;
  59243. if (this._shareOutputWithPostProcess) {
  59244. target = this._shareOutputWithPostProcess.inputTexture;
  59245. }
  59246. else if (this._forcedOutputTexture) {
  59247. target = this._forcedOutputTexture;
  59248. this.width = this._forcedOutputTexture.width;
  59249. this.height = this._forcedOutputTexture.height;
  59250. }
  59251. else {
  59252. target = this.inputTexture;
  59253. }
  59254. // Bind the input of this post process to be used as the output of the previous post process.
  59255. if (this.enablePixelPerfectMode) {
  59256. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59257. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59258. }
  59259. else {
  59260. this._scaleRatio.copyFromFloats(1, 1);
  59261. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59262. }
  59263. this.onActivateObservable.notifyObservers(camera);
  59264. // Clear
  59265. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59266. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59267. }
  59268. if (this._reusable) {
  59269. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59270. }
  59271. };
  59272. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59273. /**
  59274. * If the post process is supported.
  59275. */
  59276. get: function () {
  59277. return this._effect.isSupported;
  59278. },
  59279. enumerable: true,
  59280. configurable: true
  59281. });
  59282. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59283. /**
  59284. * The aspect ratio of the output texture.
  59285. */
  59286. get: function () {
  59287. if (this._shareOutputWithPostProcess) {
  59288. return this._shareOutputWithPostProcess.aspectRatio;
  59289. }
  59290. if (this._forcedOutputTexture) {
  59291. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59292. }
  59293. return this.width / this.height;
  59294. },
  59295. enumerable: true,
  59296. configurable: true
  59297. });
  59298. /**
  59299. * Get a value indicating if the post-process is ready to be used
  59300. * @returns true if the post-process is ready (shader is compiled)
  59301. */
  59302. PostProcess.prototype.isReady = function () {
  59303. return this._effect && this._effect.isReady();
  59304. };
  59305. /**
  59306. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59307. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59308. */
  59309. PostProcess.prototype.apply = function () {
  59310. // Check
  59311. if (!this._effect || !this._effect.isReady())
  59312. return null;
  59313. // States
  59314. this._engine.enableEffect(this._effect);
  59315. this._engine.setState(false);
  59316. this._engine.setDepthBuffer(false);
  59317. this._engine.setDepthWrite(false);
  59318. // Alpha
  59319. this._engine.setAlphaMode(this.alphaMode);
  59320. if (this.alphaConstants) {
  59321. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59322. }
  59323. // Bind the output texture of the preivous post process as the input to this post process.
  59324. var source;
  59325. if (this._shareOutputWithPostProcess) {
  59326. source = this._shareOutputWithPostProcess.inputTexture;
  59327. }
  59328. else if (this._forcedOutputTexture) {
  59329. source = this._forcedOutputTexture;
  59330. }
  59331. else {
  59332. source = this.inputTexture;
  59333. }
  59334. this._effect._bindTexture("textureSampler", source);
  59335. // Parameters
  59336. this._effect.setVector2("scale", this._scaleRatio);
  59337. this.onApplyObservable.notifyObservers(this._effect);
  59338. return this._effect;
  59339. };
  59340. PostProcess.prototype._disposeTextures = function () {
  59341. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59342. return;
  59343. }
  59344. if (this._textures.length > 0) {
  59345. for (var i = 0; i < this._textures.length; i++) {
  59346. this._engine._releaseTexture(this._textures.data[i]);
  59347. }
  59348. }
  59349. this._textures.dispose();
  59350. };
  59351. /**
  59352. * Disposes the post process.
  59353. * @param camera The camera to dispose the post process on.
  59354. */
  59355. PostProcess.prototype.dispose = function (camera) {
  59356. camera = camera || this._camera;
  59357. this._disposeTextures();
  59358. if (this._scene) {
  59359. var index_1 = this._scene.postProcesses.indexOf(this);
  59360. if (index_1 !== -1) {
  59361. this._scene.postProcesses.splice(index_1, 1);
  59362. }
  59363. }
  59364. else {
  59365. var index_2 = this._engine.postProcesses.indexOf(this);
  59366. if (index_2 !== -1) {
  59367. this._engine.postProcesses.splice(index_2, 1);
  59368. }
  59369. }
  59370. if (!camera) {
  59371. return;
  59372. }
  59373. camera.detachPostProcess(this);
  59374. var index = camera._postProcesses.indexOf(this);
  59375. if (index === 0 && camera._postProcesses.length > 0) {
  59376. var firstPostProcess = this._camera._getFirstPostProcess();
  59377. if (firstPostProcess) {
  59378. firstPostProcess.markTextureDirty();
  59379. }
  59380. }
  59381. this.onActivateObservable.clear();
  59382. this.onAfterRenderObservable.clear();
  59383. this.onApplyObservable.clear();
  59384. this.onBeforeRenderObservable.clear();
  59385. this.onSizeChangedObservable.clear();
  59386. };
  59387. return PostProcess;
  59388. }());
  59389. BABYLON.PostProcess = PostProcess;
  59390. })(BABYLON || (BABYLON = {}));
  59391. //# sourceMappingURL=babylon.postProcess.js.map
  59392. var BABYLON;
  59393. (function (BABYLON) {
  59394. var PassPostProcess = /** @class */ (function (_super) {
  59395. __extends(PassPostProcess, _super);
  59396. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  59397. if (camera === void 0) { camera = null; }
  59398. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59399. if (blockCompilation === void 0) { blockCompilation = false; }
  59400. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  59401. }
  59402. return PassPostProcess;
  59403. }(BABYLON.PostProcess));
  59404. BABYLON.PassPostProcess = PassPostProcess;
  59405. })(BABYLON || (BABYLON = {}));
  59406. //# sourceMappingURL=babylon.passPostProcess.js.map
  59407. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59408. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59409. s = arguments[i];
  59410. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59411. t[p] = s[p];
  59412. }
  59413. return t;
  59414. };
  59415. var BABYLON;
  59416. (function (BABYLON) {
  59417. /**
  59418. * Default implementation of @see IShadowGenerator.
  59419. * This is the main object responsible of generating shadows in the framework.
  59420. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59421. */
  59422. var ShadowGenerator = /** @class */ (function () {
  59423. /**
  59424. * Creates a ShadowGenerator object.
  59425. * A ShadowGenerator is the required tool to use the shadows.
  59426. * Each light casting shadows needs to use its own ShadowGenerator.
  59427. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59428. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59429. * @param light The light object generating the shadows.
  59430. * @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.
  59431. */
  59432. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59433. this._bias = 0.00005;
  59434. this._blurBoxOffset = 1;
  59435. this._blurScale = 2;
  59436. this._blurKernel = 1;
  59437. this._useKernelBlur = false;
  59438. this._filter = ShadowGenerator.FILTER_NONE;
  59439. this._darkness = 0;
  59440. this._transparencyShadow = false;
  59441. /**
  59442. * Controls the extent to which the shadows fade out at the edge of the frustum
  59443. * Used only by directionals and spots
  59444. */
  59445. this.frustumEdgeFalloff = 0;
  59446. /**
  59447. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59448. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59449. * It might on the other hand introduce peter panning.
  59450. */
  59451. this.forceBackFacesOnly = false;
  59452. this._lightDirection = BABYLON.Vector3.Zero();
  59453. this._viewMatrix = BABYLON.Matrix.Zero();
  59454. this._projectionMatrix = BABYLON.Matrix.Zero();
  59455. this._transformMatrix = BABYLON.Matrix.Zero();
  59456. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59457. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59458. this._currentFaceIndex = 0;
  59459. this._currentFaceIndexCache = 0;
  59460. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59461. this._mapSize = mapSize;
  59462. this._light = light;
  59463. this._scene = light.getScene();
  59464. light._shadowGenerator = this;
  59465. // Texture type fallback from float to int if not supported.
  59466. var caps = this._scene.getEngine().getCaps();
  59467. if (!useFullFloatFirst) {
  59468. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59469. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59470. }
  59471. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59472. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59473. }
  59474. else {
  59475. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59476. }
  59477. }
  59478. else {
  59479. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59480. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59481. }
  59482. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59483. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59484. }
  59485. else {
  59486. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59487. }
  59488. }
  59489. this._initializeGenerator();
  59490. }
  59491. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59492. /**
  59493. * Shadow generator mode None: no filtering applied.
  59494. */
  59495. get: function () {
  59496. return ShadowGenerator._FILTER_NONE;
  59497. },
  59498. enumerable: true,
  59499. configurable: true
  59500. });
  59501. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59502. /**
  59503. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59504. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59505. */
  59506. get: function () {
  59507. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59508. },
  59509. enumerable: true,
  59510. configurable: true
  59511. });
  59512. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59513. /**
  59514. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59515. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59516. */
  59517. get: function () {
  59518. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59519. },
  59520. enumerable: true,
  59521. configurable: true
  59522. });
  59523. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59524. /**
  59525. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59526. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59527. */
  59528. get: function () {
  59529. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59530. },
  59531. enumerable: true,
  59532. configurable: true
  59533. });
  59534. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59535. /**
  59536. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59537. * edge artifacts on steep falloff.
  59538. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59539. */
  59540. get: function () {
  59541. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59542. },
  59543. enumerable: true,
  59544. configurable: true
  59545. });
  59546. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59547. /**
  59548. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59549. * edge artifacts on steep falloff.
  59550. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59551. */
  59552. get: function () {
  59553. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59554. },
  59555. enumerable: true,
  59556. configurable: true
  59557. });
  59558. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59559. /**
  59560. * Gets the bias: offset applied on the depth preventing acnea.
  59561. */
  59562. get: function () {
  59563. return this._bias;
  59564. },
  59565. /**
  59566. * Sets the bias: offset applied on the depth preventing acnea.
  59567. */
  59568. set: function (bias) {
  59569. this._bias = bias;
  59570. },
  59571. enumerable: true,
  59572. configurable: true
  59573. });
  59574. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59575. /**
  59576. * Gets the blur box offset: offset applied during the blur pass.
  59577. * Only usefull if useKernelBlur = false
  59578. */
  59579. get: function () {
  59580. return this._blurBoxOffset;
  59581. },
  59582. /**
  59583. * Sets the blur box offset: offset applied during the blur pass.
  59584. * Only usefull if useKernelBlur = false
  59585. */
  59586. set: function (value) {
  59587. if (this._blurBoxOffset === value) {
  59588. return;
  59589. }
  59590. this._blurBoxOffset = value;
  59591. this._disposeBlurPostProcesses();
  59592. },
  59593. enumerable: true,
  59594. configurable: true
  59595. });
  59596. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59597. /**
  59598. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59599. * 2 means half of the size.
  59600. */
  59601. get: function () {
  59602. return this._blurScale;
  59603. },
  59604. /**
  59605. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59606. * 2 means half of the size.
  59607. */
  59608. set: function (value) {
  59609. if (this._blurScale === value) {
  59610. return;
  59611. }
  59612. this._blurScale = value;
  59613. this._disposeBlurPostProcesses();
  59614. },
  59615. enumerable: true,
  59616. configurable: true
  59617. });
  59618. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59619. /**
  59620. * Gets the blur kernel: kernel size of the blur pass.
  59621. * Only usefull if useKernelBlur = true
  59622. */
  59623. get: function () {
  59624. return this._blurKernel;
  59625. },
  59626. /**
  59627. * Sets the blur kernel: kernel size of the blur pass.
  59628. * Only usefull if useKernelBlur = true
  59629. */
  59630. set: function (value) {
  59631. if (this._blurKernel === value) {
  59632. return;
  59633. }
  59634. this._blurKernel = value;
  59635. this._disposeBlurPostProcesses();
  59636. },
  59637. enumerable: true,
  59638. configurable: true
  59639. });
  59640. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59641. /**
  59642. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59643. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59644. */
  59645. get: function () {
  59646. return this._useKernelBlur;
  59647. },
  59648. /**
  59649. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59650. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59651. */
  59652. set: function (value) {
  59653. if (this._useKernelBlur === value) {
  59654. return;
  59655. }
  59656. this._useKernelBlur = value;
  59657. this._disposeBlurPostProcesses();
  59658. },
  59659. enumerable: true,
  59660. configurable: true
  59661. });
  59662. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59663. /**
  59664. * Gets the depth scale used in ESM mode.
  59665. */
  59666. get: function () {
  59667. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59668. },
  59669. /**
  59670. * Sets the depth scale used in ESM mode.
  59671. * This can override the scale stored on the light.
  59672. */
  59673. set: function (value) {
  59674. this._depthScale = value;
  59675. },
  59676. enumerable: true,
  59677. configurable: true
  59678. });
  59679. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59680. /**
  59681. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59682. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59683. */
  59684. get: function () {
  59685. return this._filter;
  59686. },
  59687. /**
  59688. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59689. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59690. */
  59691. set: function (value) {
  59692. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59693. if (this._light.needCube()) {
  59694. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59695. this.useExponentialShadowMap = true;
  59696. return;
  59697. }
  59698. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59699. this.useCloseExponentialShadowMap = true;
  59700. return;
  59701. }
  59702. }
  59703. if (this._filter === value) {
  59704. return;
  59705. }
  59706. this._filter = value;
  59707. this._disposeBlurPostProcesses();
  59708. this._applyFilterValues();
  59709. this._light._markMeshesAsLightDirty();
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59715. /**
  59716. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59717. */
  59718. get: function () {
  59719. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59720. },
  59721. /**
  59722. * Sets the current filter to Poisson Sampling aka PCF.
  59723. */
  59724. set: function (value) {
  59725. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59726. return;
  59727. }
  59728. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59729. },
  59730. enumerable: true,
  59731. configurable: true
  59732. });
  59733. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59734. /**
  59735. * Gets if the current filter is set to VSM.
  59736. * DEPRECATED. Should use useExponentialShadowMap instead.
  59737. */
  59738. get: function () {
  59739. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59740. return this.useExponentialShadowMap;
  59741. },
  59742. /**
  59743. * Sets the current filter is to VSM.
  59744. * DEPRECATED. Should use useExponentialShadowMap instead.
  59745. */
  59746. set: function (value) {
  59747. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59748. this.useExponentialShadowMap = value;
  59749. },
  59750. enumerable: true,
  59751. configurable: true
  59752. });
  59753. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59754. /**
  59755. * Gets if the current filter is set to blurred VSM.
  59756. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59757. */
  59758. get: function () {
  59759. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59760. return this.useBlurExponentialShadowMap;
  59761. },
  59762. /**
  59763. * Sets the current filter is to blurred VSM.
  59764. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59765. */
  59766. set: function (value) {
  59767. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59768. this.useBlurExponentialShadowMap = value;
  59769. },
  59770. enumerable: true,
  59771. configurable: true
  59772. });
  59773. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59774. /**
  59775. * Gets if the current filter is set to ESM.
  59776. */
  59777. get: function () {
  59778. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59779. },
  59780. /**
  59781. * Sets the current filter is to ESM.
  59782. */
  59783. set: function (value) {
  59784. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59785. return;
  59786. }
  59787. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59788. },
  59789. enumerable: true,
  59790. configurable: true
  59791. });
  59792. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59793. /**
  59794. * Gets if the current filter is set to filtered ESM.
  59795. */
  59796. get: function () {
  59797. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59798. },
  59799. /**
  59800. * Gets if the current filter is set to filtered ESM.
  59801. */
  59802. set: function (value) {
  59803. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59804. return;
  59805. }
  59806. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59812. /**
  59813. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59814. * exponential to prevent steep falloff artifacts).
  59815. */
  59816. get: function () {
  59817. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59818. },
  59819. /**
  59820. * Sets the current filter to "close ESM" (using the inverse of the
  59821. * exponential to prevent steep falloff artifacts).
  59822. */
  59823. set: function (value) {
  59824. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59825. return;
  59826. }
  59827. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59833. /**
  59834. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59835. * exponential to prevent steep falloff artifacts).
  59836. */
  59837. get: function () {
  59838. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59839. },
  59840. /**
  59841. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59842. * exponential to prevent steep falloff artifacts).
  59843. */
  59844. set: function (value) {
  59845. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59846. return;
  59847. }
  59848. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59849. },
  59850. enumerable: true,
  59851. configurable: true
  59852. });
  59853. /**
  59854. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59855. * 0 means strongest and 1 would means no shadow.
  59856. * @returns the darkness.
  59857. */
  59858. ShadowGenerator.prototype.getDarkness = function () {
  59859. return this._darkness;
  59860. };
  59861. /**
  59862. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59863. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59864. * @returns the shadow generator allowing fluent coding.
  59865. */
  59866. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59867. if (darkness >= 1.0)
  59868. this._darkness = 1.0;
  59869. else if (darkness <= 0.0)
  59870. this._darkness = 0.0;
  59871. else
  59872. this._darkness = darkness;
  59873. return this;
  59874. };
  59875. /**
  59876. * Sets the ability to have transparent shadow (boolean).
  59877. * @param transparent True if transparent else False
  59878. * @returns the shadow generator allowing fluent coding
  59879. */
  59880. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59881. this._transparencyShadow = transparent;
  59882. return this;
  59883. };
  59884. /**
  59885. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59886. * @returns The render target texture if present otherwise, null
  59887. */
  59888. ShadowGenerator.prototype.getShadowMap = function () {
  59889. return this._shadowMap;
  59890. };
  59891. /**
  59892. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59893. * @returns The render target texture if the shadow map is present otherwise, null
  59894. */
  59895. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59896. if (this._shadowMap2) {
  59897. return this._shadowMap2;
  59898. }
  59899. return this._shadowMap;
  59900. };
  59901. /**
  59902. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59903. * @param mesh Mesh to add
  59904. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59905. * @returns the Shadow Generator itself
  59906. */
  59907. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59908. if (includeDescendants === void 0) { includeDescendants = true; }
  59909. if (!this._shadowMap) {
  59910. return this;
  59911. }
  59912. if (!this._shadowMap.renderList) {
  59913. this._shadowMap.renderList = [];
  59914. }
  59915. this._shadowMap.renderList.push(mesh);
  59916. if (includeDescendants) {
  59917. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59918. }
  59919. return this;
  59920. var _a;
  59921. };
  59922. /**
  59923. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59924. * @param mesh Mesh to remove
  59925. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59926. * @returns the Shadow Generator itself
  59927. */
  59928. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59929. if (includeDescendants === void 0) { includeDescendants = true; }
  59930. if (!this._shadowMap || !this._shadowMap.renderList) {
  59931. return this;
  59932. }
  59933. var index = this._shadowMap.renderList.indexOf(mesh);
  59934. if (index !== -1) {
  59935. this._shadowMap.renderList.splice(index, 1);
  59936. }
  59937. if (includeDescendants) {
  59938. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59939. var child = _a[_i];
  59940. this.removeShadowCaster(child);
  59941. }
  59942. }
  59943. return this;
  59944. };
  59945. /**
  59946. * Returns the associated light object.
  59947. * @returns the light generating the shadow
  59948. */
  59949. ShadowGenerator.prototype.getLight = function () {
  59950. return this._light;
  59951. };
  59952. ShadowGenerator.prototype._initializeGenerator = function () {
  59953. this._light._markMeshesAsLightDirty();
  59954. this._initializeShadowMap();
  59955. };
  59956. ShadowGenerator.prototype._initializeShadowMap = function () {
  59957. var _this = this;
  59958. // Render target
  59959. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59960. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59961. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59962. this._shadowMap.anisotropicFilteringLevel = 1;
  59963. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59964. this._shadowMap.renderParticles = false;
  59965. this._shadowMap.ignoreCameraViewport = true;
  59966. // Record Face Index before render.
  59967. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59968. _this._currentFaceIndex = faceIndex;
  59969. });
  59970. // Custom render function.
  59971. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59972. // Blur if required afer render.
  59973. this._shadowMap.onAfterUnbindObservable.add(function () {
  59974. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59975. return;
  59976. }
  59977. var shadowMap = _this.getShadowMapForRendering();
  59978. if (shadowMap) {
  59979. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59980. }
  59981. });
  59982. // Clear according to the chosen filter.
  59983. var zero = new BABYLON.Color4(0, 0, 0, 0);
  59984. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59985. this._shadowMap.onClearObservable.add(function (engine) {
  59986. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59987. engine.clear(zero, true, true, true);
  59988. }
  59989. else {
  59990. engine.clear(one, true, true, true);
  59991. }
  59992. });
  59993. };
  59994. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59995. var _this = this;
  59996. var engine = this._scene.getEngine();
  59997. var targetSize = this._mapSize / this.blurScale;
  59998. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59999. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60000. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60001. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60002. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60003. }
  60004. if (this.useKernelBlur) {
  60005. 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);
  60006. this._kernelBlurXPostprocess.width = targetSize;
  60007. this._kernelBlurXPostprocess.height = targetSize;
  60008. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60009. effect.setTexture("textureSampler", _this._shadowMap);
  60010. });
  60011. 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);
  60012. this._kernelBlurXPostprocess.autoClear = false;
  60013. this._kernelBlurYPostprocess.autoClear = false;
  60014. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60015. this._kernelBlurXPostprocess.packedFloat = true;
  60016. this._kernelBlurYPostprocess.packedFloat = true;
  60017. }
  60018. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60019. }
  60020. else {
  60021. 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);
  60022. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60023. effect.setFloat2("screenSize", targetSize, targetSize);
  60024. effect.setTexture("textureSampler", _this._shadowMap);
  60025. });
  60026. this._boxBlurPostprocess.autoClear = false;
  60027. this._blurPostProcesses = [this._boxBlurPostprocess];
  60028. }
  60029. };
  60030. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60031. var index;
  60032. var engine = this._scene.getEngine();
  60033. if (depthOnlySubMeshes.length) {
  60034. engine.setColorWrite(false);
  60035. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60036. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60037. }
  60038. engine.setColorWrite(true);
  60039. }
  60040. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60041. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60042. }
  60043. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60044. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60045. }
  60046. if (this._transparencyShadow) {
  60047. for (index = 0; index < transparentSubMeshes.length; index++) {
  60048. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60049. }
  60050. }
  60051. };
  60052. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60053. var _this = this;
  60054. var mesh = subMesh.getRenderingMesh();
  60055. var scene = this._scene;
  60056. var engine = scene.getEngine();
  60057. var material = subMesh.getMaterial();
  60058. if (!material) {
  60059. return;
  60060. }
  60061. // Culling
  60062. engine.setState(material.backFaceCulling);
  60063. // Managing instances
  60064. var batch = mesh._getInstancesRenderList(subMesh._id);
  60065. if (batch.mustReturn) {
  60066. return;
  60067. }
  60068. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60069. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60070. engine.enableEffect(this._effect);
  60071. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60072. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60073. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60074. this._effect.setVector3("lightPosition", this.getLight().position);
  60075. if (scene.activeCamera) {
  60076. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60077. }
  60078. // Alpha test
  60079. if (material && material.needAlphaTesting()) {
  60080. var alphaTexture = material.getAlphaTestTexture();
  60081. if (alphaTexture) {
  60082. this._effect.setTexture("diffuseSampler", alphaTexture);
  60083. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60084. }
  60085. }
  60086. // Bones
  60087. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60088. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60089. }
  60090. if (this.forceBackFacesOnly) {
  60091. engine.setState(true, 0, false, true);
  60092. }
  60093. // Draw
  60094. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60095. if (this.forceBackFacesOnly) {
  60096. engine.setState(true, 0, false, false);
  60097. }
  60098. }
  60099. else {
  60100. // Need to reset refresh rate of the shadowMap
  60101. if (this._shadowMap) {
  60102. this._shadowMap.resetRefreshCounter();
  60103. }
  60104. }
  60105. };
  60106. ShadowGenerator.prototype._applyFilterValues = function () {
  60107. if (!this._shadowMap) {
  60108. return;
  60109. }
  60110. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60111. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60112. }
  60113. else {
  60114. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60115. }
  60116. };
  60117. /**
  60118. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60119. * @param onCompiled Callback triggered at the and of the effects compilation
  60120. * @param options Sets of optional options forcing the compilation with different modes
  60121. */
  60122. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60123. var _this = this;
  60124. var localOptions = __assign({ useInstances: false }, options);
  60125. var shadowMap = this.getShadowMap();
  60126. if (!shadowMap) {
  60127. if (onCompiled) {
  60128. onCompiled(this);
  60129. }
  60130. return;
  60131. }
  60132. var renderList = shadowMap.renderList;
  60133. if (!renderList) {
  60134. if (onCompiled) {
  60135. onCompiled(this);
  60136. }
  60137. return;
  60138. }
  60139. var subMeshes = new Array();
  60140. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60141. var mesh = renderList_1[_i];
  60142. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60143. }
  60144. if (subMeshes.length === 0) {
  60145. if (onCompiled) {
  60146. onCompiled(this);
  60147. }
  60148. return;
  60149. }
  60150. var currentIndex = 0;
  60151. var checkReady = function () {
  60152. if (!_this._scene || !_this._scene.getEngine()) {
  60153. return;
  60154. }
  60155. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60156. currentIndex++;
  60157. if (currentIndex >= subMeshes.length) {
  60158. if (onCompiled) {
  60159. onCompiled(_this);
  60160. }
  60161. return;
  60162. }
  60163. }
  60164. setTimeout(checkReady, 16);
  60165. };
  60166. checkReady();
  60167. };
  60168. /**
  60169. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60170. * @param options Sets of optional options forcing the compilation with different modes
  60171. * @returns A promise that resolves when the compilation completes
  60172. */
  60173. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60174. var _this = this;
  60175. return new Promise(function (resolve) {
  60176. _this.forceCompilation(function () {
  60177. resolve();
  60178. }, options);
  60179. });
  60180. };
  60181. /**
  60182. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60183. * @param subMesh The submesh we want to render in the shadow map
  60184. * @param useInstances Defines wether will draw in the map using instances
  60185. * @returns true if ready otherwise, false
  60186. */
  60187. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60188. var defines = [];
  60189. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60190. defines.push("#define FLOAT");
  60191. }
  60192. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60193. defines.push("#define ESM");
  60194. }
  60195. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60196. var mesh = subMesh.getMesh();
  60197. var material = subMesh.getMaterial();
  60198. // Alpha test
  60199. if (material && material.needAlphaTesting()) {
  60200. var alphaTexture = material.getAlphaTestTexture();
  60201. if (alphaTexture) {
  60202. defines.push("#define ALPHATEST");
  60203. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60204. attribs.push(BABYLON.VertexBuffer.UVKind);
  60205. defines.push("#define UV1");
  60206. }
  60207. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60208. if (alphaTexture.coordinatesIndex === 1) {
  60209. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60210. defines.push("#define UV2");
  60211. }
  60212. }
  60213. }
  60214. }
  60215. // Bones
  60216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60219. if (mesh.numBoneInfluencers > 4) {
  60220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60222. }
  60223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60224. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60225. }
  60226. else {
  60227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60228. }
  60229. // Instances
  60230. if (useInstances) {
  60231. defines.push("#define INSTANCES");
  60232. attribs.push("world0");
  60233. attribs.push("world1");
  60234. attribs.push("world2");
  60235. attribs.push("world3");
  60236. }
  60237. // Get correct effect
  60238. var join = defines.join("\n");
  60239. if (this._cachedDefines !== join) {
  60240. this._cachedDefines = join;
  60241. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60242. }
  60243. if (!this._effect.isReady()) {
  60244. return false;
  60245. }
  60246. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60247. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60248. this._initializeBlurRTTAndPostProcesses();
  60249. }
  60250. }
  60251. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60252. return false;
  60253. }
  60254. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60255. return false;
  60256. }
  60257. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60258. return false;
  60259. }
  60260. return true;
  60261. };
  60262. /**
  60263. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60264. * @param defines Defines of the material we want to update
  60265. * @param lightIndex Index of the light in the enabled light list of the material
  60266. */
  60267. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60268. var scene = this._scene;
  60269. var light = this._light;
  60270. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60271. return;
  60272. }
  60273. defines["SHADOW" + lightIndex] = true;
  60274. if (this.usePoissonSampling) {
  60275. defines["SHADOWPCF" + lightIndex] = true;
  60276. }
  60277. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60278. defines["SHADOWESM" + lightIndex] = true;
  60279. }
  60280. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60281. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60282. }
  60283. if (light.needCube()) {
  60284. defines["SHADOWCUBE" + lightIndex] = true;
  60285. }
  60286. };
  60287. /**
  60288. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60289. * defined in the generator but impacting the effect).
  60290. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60291. * @param effect The effect we are binfing the information for
  60292. */
  60293. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60294. var light = this._light;
  60295. var scene = this._scene;
  60296. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60297. return;
  60298. }
  60299. var camera = scene.activeCamera;
  60300. if (!camera) {
  60301. return;
  60302. }
  60303. var shadowMap = this.getShadowMap();
  60304. if (!shadowMap) {
  60305. return;
  60306. }
  60307. if (!light.needCube()) {
  60308. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60309. }
  60310. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60311. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60312. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60313. };
  60314. /**
  60315. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60316. * (eq to shadow prjection matrix * light transform matrix)
  60317. * @returns The transform matrix used to create the shadow map
  60318. */
  60319. ShadowGenerator.prototype.getTransformMatrix = function () {
  60320. var scene = this._scene;
  60321. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60322. return this._transformMatrix;
  60323. }
  60324. this._currentRenderID = scene.getRenderId();
  60325. this._currentFaceIndexCache = this._currentFaceIndex;
  60326. var lightPosition = this._light.position;
  60327. if (this._light.computeTransformedInformation()) {
  60328. lightPosition = this._light.transformedPosition;
  60329. }
  60330. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60331. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60332. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60333. }
  60334. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60335. this._cachedPosition.copyFrom(lightPosition);
  60336. this._cachedDirection.copyFrom(this._lightDirection);
  60337. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60338. var shadowMap = this.getShadowMap();
  60339. if (shadowMap) {
  60340. var renderList = shadowMap.renderList;
  60341. if (renderList) {
  60342. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60343. }
  60344. }
  60345. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60346. }
  60347. return this._transformMatrix;
  60348. };
  60349. /**
  60350. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60351. * Cube and 2D textures for instance.
  60352. */
  60353. ShadowGenerator.prototype.recreateShadowMap = function () {
  60354. var shadowMap = this._shadowMap;
  60355. if (!shadowMap) {
  60356. return;
  60357. }
  60358. // Track render list.
  60359. var renderList = shadowMap.renderList;
  60360. // Clean up existing data.
  60361. this._disposeRTTandPostProcesses();
  60362. // Reinitializes.
  60363. this._initializeGenerator();
  60364. // Reaffect the filter to ensure a correct fallback if necessary.
  60365. this.filter = this.filter;
  60366. // Reaffect the filter.
  60367. this._applyFilterValues();
  60368. // Reaffect Render List.
  60369. this._shadowMap.renderList = renderList;
  60370. };
  60371. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60372. if (this._shadowMap2) {
  60373. this._shadowMap2.dispose();
  60374. this._shadowMap2 = null;
  60375. }
  60376. if (this._boxBlurPostprocess) {
  60377. this._boxBlurPostprocess.dispose();
  60378. this._boxBlurPostprocess = null;
  60379. }
  60380. if (this._kernelBlurXPostprocess) {
  60381. this._kernelBlurXPostprocess.dispose();
  60382. this._kernelBlurXPostprocess = null;
  60383. }
  60384. if (this._kernelBlurYPostprocess) {
  60385. this._kernelBlurYPostprocess.dispose();
  60386. this._kernelBlurYPostprocess = null;
  60387. }
  60388. this._blurPostProcesses = [];
  60389. };
  60390. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60391. if (this._shadowMap) {
  60392. this._shadowMap.dispose();
  60393. this._shadowMap = null;
  60394. }
  60395. this._disposeBlurPostProcesses();
  60396. };
  60397. /**
  60398. * Disposes the ShadowGenerator.
  60399. * Returns nothing.
  60400. */
  60401. ShadowGenerator.prototype.dispose = function () {
  60402. this._disposeRTTandPostProcesses();
  60403. if (this._light) {
  60404. this._light._shadowGenerator = null;
  60405. this._light._markMeshesAsLightDirty();
  60406. }
  60407. };
  60408. /**
  60409. * Serializes the shadow generator setup to a json object.
  60410. * @returns The serialized JSON object
  60411. */
  60412. ShadowGenerator.prototype.serialize = function () {
  60413. var serializationObject = {};
  60414. var shadowMap = this.getShadowMap();
  60415. if (!shadowMap) {
  60416. return serializationObject;
  60417. }
  60418. serializationObject.lightId = this._light.id;
  60419. serializationObject.mapSize = shadowMap.getRenderSize();
  60420. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60421. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60422. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60423. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60424. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60425. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60426. serializationObject.depthScale = this.depthScale;
  60427. serializationObject.darkness = this.getDarkness();
  60428. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60429. serializationObject.blurKernel = this.blurKernel;
  60430. serializationObject.blurScale = this.blurScale;
  60431. serializationObject.useKernelBlur = this.useKernelBlur;
  60432. serializationObject.transparencyShadow = this._transparencyShadow;
  60433. serializationObject.renderList = [];
  60434. if (shadowMap.renderList) {
  60435. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60436. var mesh = shadowMap.renderList[meshIndex];
  60437. serializationObject.renderList.push(mesh.id);
  60438. }
  60439. }
  60440. return serializationObject;
  60441. };
  60442. /**
  60443. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60444. * @param parsedShadowGenerator The JSON object to parse
  60445. * @param scene The scene to create the shadow map for
  60446. * @returns The parsed shadow generator
  60447. */
  60448. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60449. //casting to point light, as light is missing the position attr and typescript complains.
  60450. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60451. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60452. var shadowMap = shadowGenerator.getShadowMap();
  60453. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60454. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60455. meshes.forEach(function (mesh) {
  60456. if (!shadowMap) {
  60457. return;
  60458. }
  60459. if (!shadowMap.renderList) {
  60460. shadowMap.renderList = [];
  60461. }
  60462. shadowMap.renderList.push(mesh);
  60463. });
  60464. }
  60465. if (parsedShadowGenerator.usePoissonSampling) {
  60466. shadowGenerator.usePoissonSampling = true;
  60467. }
  60468. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60469. shadowGenerator.useExponentialShadowMap = true;
  60470. }
  60471. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60472. shadowGenerator.useBlurExponentialShadowMap = true;
  60473. }
  60474. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60475. shadowGenerator.useCloseExponentialShadowMap = true;
  60476. }
  60477. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60478. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60479. }
  60480. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60481. shadowGenerator.useExponentialShadowMap = true;
  60482. }
  60483. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60484. shadowGenerator.useBlurExponentialShadowMap = true;
  60485. }
  60486. if (parsedShadowGenerator.depthScale) {
  60487. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60488. }
  60489. if (parsedShadowGenerator.blurScale) {
  60490. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60491. }
  60492. if (parsedShadowGenerator.blurBoxOffset) {
  60493. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60494. }
  60495. if (parsedShadowGenerator.useKernelBlur) {
  60496. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60497. }
  60498. if (parsedShadowGenerator.blurKernel) {
  60499. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60500. }
  60501. if (parsedShadowGenerator.bias !== undefined) {
  60502. shadowGenerator.bias = parsedShadowGenerator.bias;
  60503. }
  60504. if (parsedShadowGenerator.darkness) {
  60505. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60506. }
  60507. if (parsedShadowGenerator.transparencyShadow) {
  60508. shadowGenerator.setTransparencyShadow(true);
  60509. }
  60510. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60511. return shadowGenerator;
  60512. };
  60513. ShadowGenerator._FILTER_NONE = 0;
  60514. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60515. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60516. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60517. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60518. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60519. return ShadowGenerator;
  60520. }());
  60521. BABYLON.ShadowGenerator = ShadowGenerator;
  60522. })(BABYLON || (BABYLON = {}));
  60523. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60524. var BABYLON;
  60525. (function (BABYLON) {
  60526. var DefaultLoadingScreen = /** @class */ (function () {
  60527. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60528. if (_loadingText === void 0) { _loadingText = ""; }
  60529. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60530. var _this = this;
  60531. this._renderingCanvas = _renderingCanvas;
  60532. this._loadingText = _loadingText;
  60533. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60534. // Resize
  60535. this._resizeLoadingUI = function () {
  60536. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60537. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60538. if (!_this._loadingDiv) {
  60539. return;
  60540. }
  60541. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60542. _this._loadingDiv.style.left = canvasRect.left + "px";
  60543. _this._loadingDiv.style.top = canvasRect.top + "px";
  60544. _this._loadingDiv.style.width = canvasRect.width + "px";
  60545. _this._loadingDiv.style.height = canvasRect.height + "px";
  60546. };
  60547. }
  60548. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60549. if (this._loadingDiv) {
  60550. // Do not add a loading screen if there is already one
  60551. return;
  60552. }
  60553. this._loadingDiv = document.createElement("div");
  60554. this._loadingDiv.id = "babylonjsLoadingDiv";
  60555. this._loadingDiv.style.opacity = "0";
  60556. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60557. this._loadingDiv.style.pointerEvents = "none";
  60558. // Loading text
  60559. this._loadingTextDiv = document.createElement("div");
  60560. this._loadingTextDiv.style.position = "absolute";
  60561. this._loadingTextDiv.style.left = "0";
  60562. this._loadingTextDiv.style.top = "50%";
  60563. this._loadingTextDiv.style.marginTop = "80px";
  60564. this._loadingTextDiv.style.width = "100%";
  60565. this._loadingTextDiv.style.height = "20px";
  60566. this._loadingTextDiv.style.fontFamily = "Arial";
  60567. this._loadingTextDiv.style.fontSize = "14px";
  60568. this._loadingTextDiv.style.color = "white";
  60569. this._loadingTextDiv.style.textAlign = "center";
  60570. this._loadingTextDiv.innerHTML = "Loading";
  60571. this._loadingDiv.appendChild(this._loadingTextDiv);
  60572. //set the predefined text
  60573. this._loadingTextDiv.innerHTML = this._loadingText;
  60574. // Generating keyframes
  60575. var style = document.createElement('style');
  60576. style.type = 'text/css';
  60577. 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 }";
  60578. style.innerHTML = keyFrames;
  60579. document.getElementsByTagName('head')[0].appendChild(style);
  60580. // Loading img
  60581. var imgBack = new Image();
  60582. 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";
  60583. imgBack.style.position = "absolute";
  60584. imgBack.style.left = "50%";
  60585. imgBack.style.top = "50%";
  60586. imgBack.style.marginLeft = "-60px";
  60587. imgBack.style.marginTop = "-60px";
  60588. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60589. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60590. imgBack.style.transformOrigin = "50% 50%";
  60591. imgBack.style.webkitTransformOrigin = "50% 50%";
  60592. this._loadingDiv.appendChild(imgBack);
  60593. this._resizeLoadingUI();
  60594. window.addEventListener("resize", this._resizeLoadingUI);
  60595. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60596. document.body.appendChild(this._loadingDiv);
  60597. this._loadingDiv.style.opacity = "1";
  60598. };
  60599. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60600. var _this = this;
  60601. if (!this._loadingDiv) {
  60602. return;
  60603. }
  60604. var onTransitionEnd = function () {
  60605. if (!_this._loadingDiv) {
  60606. return;
  60607. }
  60608. document.body.removeChild(_this._loadingDiv);
  60609. window.removeEventListener("resize", _this._resizeLoadingUI);
  60610. _this._loadingDiv = null;
  60611. };
  60612. this._loadingDiv.style.opacity = "0";
  60613. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60614. };
  60615. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60616. set: function (text) {
  60617. this._loadingText = text;
  60618. if (this._loadingTextDiv) {
  60619. this._loadingTextDiv.innerHTML = this._loadingText;
  60620. }
  60621. },
  60622. enumerable: true,
  60623. configurable: true
  60624. });
  60625. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60626. get: function () {
  60627. return this._loadingDivBackgroundColor;
  60628. },
  60629. set: function (color) {
  60630. this._loadingDivBackgroundColor = color;
  60631. if (!this._loadingDiv) {
  60632. return;
  60633. }
  60634. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60635. },
  60636. enumerable: true,
  60637. configurable: true
  60638. });
  60639. return DefaultLoadingScreen;
  60640. }());
  60641. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60642. })(BABYLON || (BABYLON = {}));
  60643. //# sourceMappingURL=babylon.loadingScreen.js.map
  60644. var BABYLON;
  60645. (function (BABYLON) {
  60646. var SceneLoaderProgressEvent = /** @class */ (function () {
  60647. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60648. this.lengthComputable = lengthComputable;
  60649. this.loaded = loaded;
  60650. this.total = total;
  60651. }
  60652. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60653. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60654. };
  60655. return SceneLoaderProgressEvent;
  60656. }());
  60657. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60658. var SceneLoader = /** @class */ (function () {
  60659. function SceneLoader() {
  60660. }
  60661. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60662. get: function () {
  60663. return 0;
  60664. },
  60665. enumerable: true,
  60666. configurable: true
  60667. });
  60668. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60669. get: function () {
  60670. return 1;
  60671. },
  60672. enumerable: true,
  60673. configurable: true
  60674. });
  60675. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60676. get: function () {
  60677. return 2;
  60678. },
  60679. enumerable: true,
  60680. configurable: true
  60681. });
  60682. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60683. get: function () {
  60684. return 3;
  60685. },
  60686. enumerable: true,
  60687. configurable: true
  60688. });
  60689. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60690. get: function () {
  60691. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60692. },
  60693. set: function (value) {
  60694. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60695. },
  60696. enumerable: true,
  60697. configurable: true
  60698. });
  60699. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60700. get: function () {
  60701. return SceneLoader._ShowLoadingScreen;
  60702. },
  60703. set: function (value) {
  60704. SceneLoader._ShowLoadingScreen = value;
  60705. },
  60706. enumerable: true,
  60707. configurable: true
  60708. });
  60709. Object.defineProperty(SceneLoader, "loggingLevel", {
  60710. get: function () {
  60711. return SceneLoader._loggingLevel;
  60712. },
  60713. set: function (value) {
  60714. SceneLoader._loggingLevel = value;
  60715. },
  60716. enumerable: true,
  60717. configurable: true
  60718. });
  60719. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60720. get: function () {
  60721. return SceneLoader._CleanBoneMatrixWeights;
  60722. },
  60723. set: function (value) {
  60724. SceneLoader._CleanBoneMatrixWeights = value;
  60725. },
  60726. enumerable: true,
  60727. configurable: true
  60728. });
  60729. SceneLoader._getDefaultPlugin = function () {
  60730. return SceneLoader._registeredPlugins[".babylon"];
  60731. };
  60732. SceneLoader._getPluginForExtension = function (extension) {
  60733. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60734. if (registeredPlugin) {
  60735. return registeredPlugin;
  60736. }
  60737. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60738. return SceneLoader._getDefaultPlugin();
  60739. };
  60740. SceneLoader._getPluginForDirectLoad = function (data) {
  60741. for (var extension in SceneLoader._registeredPlugins) {
  60742. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60743. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60744. return SceneLoader._registeredPlugins[extension];
  60745. }
  60746. }
  60747. return SceneLoader._getDefaultPlugin();
  60748. };
  60749. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60750. if (sceneFilename.name) {
  60751. sceneFilename = sceneFilename.name;
  60752. }
  60753. var queryStringPosition = sceneFilename.indexOf("?");
  60754. if (queryStringPosition !== -1) {
  60755. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60756. }
  60757. var dotPosition = sceneFilename.lastIndexOf(".");
  60758. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60759. return SceneLoader._getPluginForExtension(extension);
  60760. };
  60761. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60762. SceneLoader._getDirectLoad = function (sceneFilename) {
  60763. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60764. return sceneFilename.substr(5);
  60765. }
  60766. return null;
  60767. };
  60768. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60769. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60770. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60771. var plugin;
  60772. if (registeredPlugin.plugin.createPlugin) {
  60773. plugin = registeredPlugin.plugin.createPlugin();
  60774. }
  60775. else {
  60776. plugin = registeredPlugin.plugin;
  60777. }
  60778. var useArrayBuffer = registeredPlugin.isBinary;
  60779. var database;
  60780. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60781. var dataCallback = function (data, responseURL) {
  60782. if (scene.isDisposed) {
  60783. onError("Scene has been disposed");
  60784. return;
  60785. }
  60786. scene.database = database;
  60787. onSuccess(plugin, data, responseURL);
  60788. };
  60789. var request = null;
  60790. var pluginDisposed = false;
  60791. var onDisposeObservable = plugin.onDisposeObservable;
  60792. if (onDisposeObservable) {
  60793. onDisposeObservable.add(function () {
  60794. pluginDisposed = true;
  60795. if (request) {
  60796. request.abort();
  60797. request = null;
  60798. }
  60799. onDispose();
  60800. });
  60801. }
  60802. var manifestChecked = function () {
  60803. if (pluginDisposed) {
  60804. return;
  60805. }
  60806. var url = rootUrl + sceneFilename;
  60807. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60808. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60809. } : undefined, database, useArrayBuffer, function (request, exception) {
  60810. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60811. });
  60812. };
  60813. if (directLoad) {
  60814. dataCallback(directLoad);
  60815. return plugin;
  60816. }
  60817. if (rootUrl.indexOf("file:") === -1) {
  60818. if (scene.getEngine().enableOfflineSupport) {
  60819. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60820. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60821. }
  60822. else {
  60823. manifestChecked();
  60824. }
  60825. }
  60826. else {
  60827. var fileOrString = sceneFilename;
  60828. if (fileOrString.name) {
  60829. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60830. }
  60831. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60832. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60833. }
  60834. else {
  60835. onError("Unable to find file named " + sceneFilename);
  60836. }
  60837. }
  60838. return plugin;
  60839. };
  60840. // Public functions
  60841. SceneLoader.GetPluginForExtension = function (extension) {
  60842. return SceneLoader._getPluginForExtension(extension).plugin;
  60843. };
  60844. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60845. return !!SceneLoader._registeredPlugins[extension];
  60846. };
  60847. SceneLoader.RegisterPlugin = function (plugin) {
  60848. if (typeof plugin.extensions === "string") {
  60849. var extension = plugin.extensions;
  60850. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60851. plugin: plugin,
  60852. isBinary: false
  60853. };
  60854. }
  60855. else {
  60856. var extensions = plugin.extensions;
  60857. Object.keys(extensions).forEach(function (extension) {
  60858. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60859. plugin: plugin,
  60860. isBinary: extensions[extension].isBinary
  60861. };
  60862. });
  60863. }
  60864. };
  60865. /**
  60866. * Import meshes into a scene
  60867. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60868. * @param rootUrl a string that defines the root url for scene and resources
  60869. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60870. * @param scene the instance of BABYLON.Scene to append to
  60871. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60872. * @param onProgress a callback with a progress event for each file being loaded
  60873. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60874. * @param pluginExtension the extension used to determine the plugin
  60875. * @returns The loaded plugin
  60876. */
  60877. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60878. if (onSuccess === void 0) { onSuccess = null; }
  60879. if (onProgress === void 0) { onProgress = null; }
  60880. if (onError === void 0) { onError = null; }
  60881. if (pluginExtension === void 0) { pluginExtension = null; }
  60882. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60883. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60884. return null;
  60885. }
  60886. var loadingToken = {};
  60887. scene._addPendingData(loadingToken);
  60888. var disposeHandler = function () {
  60889. scene._removePendingData(loadingToken);
  60890. };
  60891. var errorHandler = function (message, exception) {
  60892. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60893. if (onError) {
  60894. onError(scene, errorMessage, exception);
  60895. }
  60896. else {
  60897. BABYLON.Tools.Error(errorMessage);
  60898. // should the exception be thrown?
  60899. }
  60900. disposeHandler();
  60901. };
  60902. var progressHandler = onProgress ? function (event) {
  60903. try {
  60904. onProgress(event);
  60905. }
  60906. catch (e) {
  60907. errorHandler("Error in onProgress callback", e);
  60908. }
  60909. } : undefined;
  60910. var successHandler = function (meshes, particleSystems, skeletons) {
  60911. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60912. if (onSuccess) {
  60913. try {
  60914. onSuccess(meshes, particleSystems, skeletons);
  60915. }
  60916. catch (e) {
  60917. errorHandler("Error in onSuccess callback", e);
  60918. }
  60919. }
  60920. scene._removePendingData(loadingToken);
  60921. };
  60922. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60923. if (plugin.rewriteRootURL) {
  60924. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60925. }
  60926. if (sceneFilename === "") {
  60927. if (sceneFilename === "") {
  60928. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60929. }
  60930. }
  60931. if (plugin.importMesh) {
  60932. var syncedPlugin = plugin;
  60933. var meshes = new Array();
  60934. var particleSystems = new Array();
  60935. var skeletons = new Array();
  60936. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60937. return;
  60938. }
  60939. scene.loadingPluginName = plugin.name;
  60940. successHandler(meshes, particleSystems, skeletons);
  60941. }
  60942. else {
  60943. var asyncedPlugin = plugin;
  60944. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60945. scene.loadingPluginName = plugin.name;
  60946. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60947. }).catch(function (error) {
  60948. errorHandler(error.message, error);
  60949. });
  60950. }
  60951. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60952. };
  60953. /**
  60954. * Import meshes into a scene
  60955. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60956. * @param rootUrl a string that defines the root url for scene and resources
  60957. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60958. * @param scene the instance of BABYLON.Scene to append to
  60959. * @param onProgress a callback with a progress event for each file being loaded
  60960. * @param pluginExtension the extension used to determine the plugin
  60961. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60962. */
  60963. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60964. if (onProgress === void 0) { onProgress = null; }
  60965. if (pluginExtension === void 0) { pluginExtension = null; }
  60966. return new Promise(function (resolve, reject) {
  60967. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60968. resolve({
  60969. meshes: meshes,
  60970. particleSystems: particleSystems,
  60971. skeletons: skeletons
  60972. });
  60973. }, onProgress, function (scene, message, exception) {
  60974. reject(exception || new Error(message));
  60975. });
  60976. });
  60977. };
  60978. /**
  60979. * Load a scene
  60980. * @param rootUrl a string that defines the root url for scene and resources
  60981. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60982. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60983. * @param onSuccess a callback with the scene when import succeeds
  60984. * @param onProgress a callback with a progress event for each file being loaded
  60985. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60986. * @param pluginExtension the extension used to determine the plugin
  60987. * @returns The loaded plugin
  60988. */
  60989. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60990. if (onSuccess === void 0) { onSuccess = null; }
  60991. if (onProgress === void 0) { onProgress = null; }
  60992. if (onError === void 0) { onError = null; }
  60993. if (pluginExtension === void 0) { pluginExtension = null; }
  60994. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60995. };
  60996. /**
  60997. * Load a scene
  60998. * @param rootUrl a string that defines the root url for scene and resources
  60999. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61000. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61001. * @param onProgress a callback with a progress event for each file being loaded
  61002. * @param pluginExtension the extension used to determine the plugin
  61003. * @returns The loaded scene
  61004. */
  61005. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61006. if (onProgress === void 0) { onProgress = null; }
  61007. if (pluginExtension === void 0) { pluginExtension = null; }
  61008. return new Promise(function (resolve, reject) {
  61009. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61010. resolve(scene);
  61011. }, onProgress, function (scene, message, exception) {
  61012. reject(exception || new Error(message));
  61013. }, pluginExtension);
  61014. });
  61015. };
  61016. /**
  61017. * Append a scene
  61018. * @param rootUrl a string that defines the root url for scene and resources
  61019. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61020. * @param scene is the instance of BABYLON.Scene to append to
  61021. * @param onSuccess a callback with the scene when import succeeds
  61022. * @param onProgress a callback with a progress event for each file being loaded
  61023. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61024. * @param pluginExtension the extension used to determine the plugin
  61025. * @returns The loaded plugin
  61026. */
  61027. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61028. if (onSuccess === void 0) { onSuccess = null; }
  61029. if (onProgress === void 0) { onProgress = null; }
  61030. if (onError === void 0) { onError = null; }
  61031. if (pluginExtension === void 0) { pluginExtension = null; }
  61032. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61033. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61034. return null;
  61035. }
  61036. if (SceneLoader.ShowLoadingScreen) {
  61037. scene.getEngine().displayLoadingUI();
  61038. }
  61039. var loadingToken = {};
  61040. scene._addPendingData(loadingToken);
  61041. var disposeHandler = function () {
  61042. scene._removePendingData(loadingToken);
  61043. scene.getEngine().hideLoadingUI();
  61044. };
  61045. var errorHandler = function (message, exception) {
  61046. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61047. if (onError) {
  61048. onError(scene, errorMessage, exception);
  61049. }
  61050. else {
  61051. BABYLON.Tools.Error(errorMessage);
  61052. // should the exception be thrown?
  61053. }
  61054. disposeHandler();
  61055. };
  61056. var progressHandler = onProgress ? function (event) {
  61057. try {
  61058. onProgress(event);
  61059. }
  61060. catch (e) {
  61061. errorHandler("Error in onProgress callback", e);
  61062. }
  61063. } : undefined;
  61064. var successHandler = function () {
  61065. if (onSuccess) {
  61066. try {
  61067. onSuccess(scene);
  61068. }
  61069. catch (e) {
  61070. errorHandler("Error in onSuccess callback", e);
  61071. }
  61072. }
  61073. scene._removePendingData(loadingToken);
  61074. };
  61075. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61076. if (sceneFilename === "") {
  61077. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61078. }
  61079. if (plugin.load) {
  61080. var syncedPlugin = plugin;
  61081. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61082. return;
  61083. }
  61084. scene.loadingPluginName = plugin.name;
  61085. successHandler();
  61086. }
  61087. else {
  61088. var asyncedPlugin = plugin;
  61089. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61090. scene.loadingPluginName = plugin.name;
  61091. successHandler();
  61092. }).catch(function (error) {
  61093. errorHandler(error.message, error);
  61094. });
  61095. }
  61096. if (SceneLoader.ShowLoadingScreen) {
  61097. scene.executeWhenReady(function () {
  61098. scene.getEngine().hideLoadingUI();
  61099. });
  61100. }
  61101. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61102. };
  61103. /**
  61104. * Append a scene
  61105. * @param rootUrl a string that defines the root url for scene and resources
  61106. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61107. * @param scene is the instance of BABYLON.Scene to append to
  61108. * @param onProgress a callback with a progress event for each file being loaded
  61109. * @param pluginExtension the extension used to determine the plugin
  61110. * @returns The given scene
  61111. */
  61112. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61113. if (onProgress === void 0) { onProgress = null; }
  61114. if (pluginExtension === void 0) { pluginExtension = null; }
  61115. return new Promise(function (resolve, reject) {
  61116. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61117. resolve(scene);
  61118. }, onProgress, function (scene, message, exception) {
  61119. reject(exception || new Error(message));
  61120. }, pluginExtension);
  61121. });
  61122. };
  61123. /**
  61124. * Load a scene into an asset container
  61125. * @param rootUrl a string that defines the root url for scene and resources
  61126. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61127. * @param scene is the instance of BABYLON.Scene to append to
  61128. * @param onSuccess a callback with the scene when import succeeds
  61129. * @param onProgress a callback with a progress event for each file being loaded
  61130. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61131. * @param pluginExtension the extension used to determine the plugin
  61132. * @returns The loaded plugin
  61133. */
  61134. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61135. if (onSuccess === void 0) { onSuccess = null; }
  61136. if (onProgress === void 0) { onProgress = null; }
  61137. if (onError === void 0) { onError = null; }
  61138. if (pluginExtension === void 0) { pluginExtension = null; }
  61139. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61140. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61141. return null;
  61142. }
  61143. var loadingToken = {};
  61144. scene._addPendingData(loadingToken);
  61145. var disposeHandler = function () {
  61146. scene._removePendingData(loadingToken);
  61147. };
  61148. var errorHandler = function (message, exception) {
  61149. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61150. if (onError) {
  61151. onError(scene, errorMessage, exception);
  61152. }
  61153. else {
  61154. BABYLON.Tools.Error(errorMessage);
  61155. // should the exception be thrown?
  61156. }
  61157. disposeHandler();
  61158. };
  61159. var progressHandler = onProgress ? function (event) {
  61160. try {
  61161. onProgress(event);
  61162. }
  61163. catch (e) {
  61164. errorHandler("Error in onProgress callback", e);
  61165. }
  61166. } : undefined;
  61167. var successHandler = function (assets) {
  61168. if (onSuccess) {
  61169. try {
  61170. onSuccess(assets);
  61171. }
  61172. catch (e) {
  61173. errorHandler("Error in onSuccess callback", e);
  61174. }
  61175. }
  61176. scene._removePendingData(loadingToken);
  61177. };
  61178. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61179. if (plugin.loadAssetContainer) {
  61180. var syncedPlugin = plugin;
  61181. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61182. if (!assetContainer) {
  61183. return;
  61184. }
  61185. scene.loadingPluginName = plugin.name;
  61186. successHandler(assetContainer);
  61187. }
  61188. else if (plugin.loadAssetContainerAsync) {
  61189. var asyncedPlugin = plugin;
  61190. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61191. scene.loadingPluginName = plugin.name;
  61192. successHandler(assetContainer);
  61193. }).catch(function (error) {
  61194. errorHandler(error.message, error);
  61195. });
  61196. }
  61197. else {
  61198. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61199. }
  61200. if (SceneLoader.ShowLoadingScreen) {
  61201. scene.executeWhenReady(function () {
  61202. scene.getEngine().hideLoadingUI();
  61203. });
  61204. }
  61205. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61206. };
  61207. /**
  61208. * Load a scene into an asset container
  61209. * @param rootUrl a string that defines the root url for scene and resources
  61210. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61211. * @param scene is the instance of BABYLON.Scene to append to
  61212. * @param onProgress a callback with a progress event for each file being loaded
  61213. * @param pluginExtension the extension used to determine the plugin
  61214. * @returns The loaded asset container
  61215. */
  61216. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61217. if (onProgress === void 0) { onProgress = null; }
  61218. if (pluginExtension === void 0) { pluginExtension = null; }
  61219. return new Promise(function (resolve, reject) {
  61220. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61221. resolve(assetContainer);
  61222. }, onProgress, function (scene, message, exception) {
  61223. reject(exception || new Error(message));
  61224. }, pluginExtension);
  61225. });
  61226. };
  61227. // Flags
  61228. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61229. SceneLoader._ShowLoadingScreen = true;
  61230. SceneLoader._CleanBoneMatrixWeights = false;
  61231. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61232. // Members
  61233. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61234. SceneLoader._registeredPlugins = {};
  61235. return SceneLoader;
  61236. }());
  61237. BABYLON.SceneLoader = SceneLoader;
  61238. ;
  61239. })(BABYLON || (BABYLON = {}));
  61240. //# sourceMappingURL=babylon.sceneLoader.js.map
  61241. var BABYLON;
  61242. (function (BABYLON) {
  61243. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61244. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61245. var parsedMaterial = parsedData.materials[index];
  61246. if (parsedMaterial.id === id) {
  61247. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61248. }
  61249. }
  61250. return null;
  61251. };
  61252. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61253. for (var i in names) {
  61254. if (mesh.name === names[i]) {
  61255. hierarchyIds.push(mesh.id);
  61256. return true;
  61257. }
  61258. }
  61259. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61260. hierarchyIds.push(mesh.id);
  61261. return true;
  61262. }
  61263. return false;
  61264. };
  61265. var logOperation = function (operation, producer) {
  61266. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61267. };
  61268. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61269. if (addToScene === void 0) { addToScene = false; }
  61270. var container = new BABYLON.AssetContainer(scene);
  61271. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61272. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61273. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61274. // and avoid problems with multiple concurrent .babylon loads.
  61275. var log = "importScene has failed JSON parse";
  61276. try {
  61277. var parsedData = JSON.parse(data);
  61278. log = "";
  61279. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61280. var index;
  61281. var cache;
  61282. // Lights
  61283. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61284. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61285. var parsedLight = parsedData.lights[index];
  61286. var light = BABYLON.Light.Parse(parsedLight, scene);
  61287. if (light) {
  61288. container.lights.push(light);
  61289. log += (index === 0 ? "\n\tLights:" : "");
  61290. log += "\n\t\t" + light.toString(fullDetails);
  61291. }
  61292. }
  61293. }
  61294. // Animations
  61295. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61296. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61297. var parsedAnimation = parsedData.animations[index];
  61298. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61299. scene.animations.push(animation);
  61300. container.animations.push(animation);
  61301. log += (index === 0 ? "\n\tAnimations:" : "");
  61302. log += "\n\t\t" + animation.toString(fullDetails);
  61303. }
  61304. }
  61305. // Materials
  61306. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61307. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61308. var parsedMaterial = parsedData.materials[index];
  61309. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61310. container.materials.push(mat);
  61311. log += (index === 0 ? "\n\tMaterials:" : "");
  61312. log += "\n\t\t" + mat.toString(fullDetails);
  61313. }
  61314. }
  61315. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61316. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61317. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61318. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61319. container.multiMaterials.push(mmat);
  61320. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61321. log += "\n\t\t" + mmat.toString(fullDetails);
  61322. }
  61323. }
  61324. // Morph targets
  61325. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61326. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61327. var managerData = _a[_i];
  61328. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61329. }
  61330. }
  61331. // Skeletons
  61332. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61333. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61334. var parsedSkeleton = parsedData.skeletons[index];
  61335. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61336. container.skeletons.push(skeleton);
  61337. log += (index === 0 ? "\n\tSkeletons:" : "");
  61338. log += "\n\t\t" + skeleton.toString(fullDetails);
  61339. }
  61340. }
  61341. // Geometries
  61342. var geometries = parsedData.geometries;
  61343. if (geometries !== undefined && geometries !== null) {
  61344. var addedGeometry = new Array();
  61345. // Boxes
  61346. var boxes = geometries.boxes;
  61347. if (boxes !== undefined && boxes !== null) {
  61348. for (index = 0, cache = boxes.length; index < cache; index++) {
  61349. var parsedBox = boxes[index];
  61350. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61351. }
  61352. }
  61353. // Spheres
  61354. var spheres = geometries.spheres;
  61355. if (spheres !== undefined && spheres !== null) {
  61356. for (index = 0, cache = spheres.length; index < cache; index++) {
  61357. var parsedSphere = spheres[index];
  61358. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61359. }
  61360. }
  61361. // Cylinders
  61362. var cylinders = geometries.cylinders;
  61363. if (cylinders !== undefined && cylinders !== null) {
  61364. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61365. var parsedCylinder = cylinders[index];
  61366. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61367. }
  61368. }
  61369. // Toruses
  61370. var toruses = geometries.toruses;
  61371. if (toruses !== undefined && toruses !== null) {
  61372. for (index = 0, cache = toruses.length; index < cache; index++) {
  61373. var parsedTorus = toruses[index];
  61374. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61375. }
  61376. }
  61377. // Grounds
  61378. var grounds = geometries.grounds;
  61379. if (grounds !== undefined && grounds !== null) {
  61380. for (index = 0, cache = grounds.length; index < cache; index++) {
  61381. var parsedGround = grounds[index];
  61382. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61383. }
  61384. }
  61385. // Planes
  61386. var planes = geometries.planes;
  61387. if (planes !== undefined && planes !== null) {
  61388. for (index = 0, cache = planes.length; index < cache; index++) {
  61389. var parsedPlane = planes[index];
  61390. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61391. }
  61392. }
  61393. // TorusKnots
  61394. var torusKnots = geometries.torusKnots;
  61395. if (torusKnots !== undefined && torusKnots !== null) {
  61396. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61397. var parsedTorusKnot = torusKnots[index];
  61398. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61399. }
  61400. }
  61401. // VertexData
  61402. var vertexData = geometries.vertexData;
  61403. if (vertexData !== undefined && vertexData !== null) {
  61404. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61405. var parsedVertexData = vertexData[index];
  61406. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61407. }
  61408. }
  61409. addedGeometry.forEach(function (g) {
  61410. if (g) {
  61411. container.geometries.push(g);
  61412. }
  61413. });
  61414. }
  61415. // Transform nodes
  61416. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61417. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61418. var parsedTransformNode = parsedData.transformNodes[index];
  61419. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61420. container.transformNodes.push(node);
  61421. }
  61422. }
  61423. // Meshes
  61424. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61425. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61426. var parsedMesh = parsedData.meshes[index];
  61427. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61428. container.meshes.push(mesh);
  61429. log += (index === 0 ? "\n\tMeshes:" : "");
  61430. log += "\n\t\t" + mesh.toString(fullDetails);
  61431. }
  61432. }
  61433. // Cameras
  61434. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61435. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61436. var parsedCamera = parsedData.cameras[index];
  61437. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61438. container.cameras.push(camera);
  61439. log += (index === 0 ? "\n\tCameras:" : "");
  61440. log += "\n\t\t" + camera.toString(fullDetails);
  61441. }
  61442. }
  61443. // Browsing all the graph to connect the dots
  61444. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61445. var camera = scene.cameras[index];
  61446. if (camera._waitingParentId) {
  61447. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61448. camera._waitingParentId = null;
  61449. }
  61450. }
  61451. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61452. var light_1 = scene.lights[index];
  61453. if (light_1 && light_1._waitingParentId) {
  61454. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61455. light_1._waitingParentId = null;
  61456. }
  61457. }
  61458. // Sounds
  61459. // TODO: add sound
  61460. var loadedSounds = [];
  61461. var loadedSound;
  61462. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61463. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61464. var parsedSound = parsedData.sounds[index];
  61465. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61466. if (!parsedSound.url)
  61467. parsedSound.url = parsedSound.name;
  61468. if (!loadedSounds[parsedSound.url]) {
  61469. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61470. loadedSounds[parsedSound.url] = loadedSound;
  61471. container.sounds.push(loadedSound);
  61472. }
  61473. else {
  61474. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61475. }
  61476. }
  61477. else {
  61478. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61479. }
  61480. }
  61481. }
  61482. loadedSounds = [];
  61483. // Connect parents & children and parse actions
  61484. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61485. var transformNode = scene.transformNodes[index];
  61486. if (transformNode._waitingParentId) {
  61487. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61488. transformNode._waitingParentId = null;
  61489. }
  61490. }
  61491. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61492. var mesh = scene.meshes[index];
  61493. if (mesh._waitingParentId) {
  61494. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61495. mesh._waitingParentId = null;
  61496. }
  61497. if (mesh._waitingActions) {
  61498. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61499. mesh._waitingActions = null;
  61500. }
  61501. }
  61502. // freeze world matrix application
  61503. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61504. var currentMesh = scene.meshes[index];
  61505. if (currentMesh._waitingFreezeWorldMatrix) {
  61506. currentMesh.freezeWorldMatrix();
  61507. currentMesh._waitingFreezeWorldMatrix = null;
  61508. }
  61509. else {
  61510. currentMesh.computeWorldMatrix(true);
  61511. }
  61512. }
  61513. // Particles Systems
  61514. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61515. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61516. var parsedParticleSystem = parsedData.particleSystems[index];
  61517. if (parsedParticleSystem.activeParticleCount) {
  61518. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61519. container.particleSystems.push(ps);
  61520. }
  61521. else {
  61522. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61523. container.particleSystems.push(ps);
  61524. }
  61525. }
  61526. }
  61527. // Lens flares
  61528. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61529. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61530. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61531. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61532. container.lensFlareSystems.push(lf);
  61533. }
  61534. }
  61535. // Shadows
  61536. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61537. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61538. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61539. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61540. container.shadowGenerators.push(sg);
  61541. }
  61542. }
  61543. // Lights exclusions / inclusions
  61544. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61545. var light_2 = scene.lights[index];
  61546. // Excluded check
  61547. if (light_2._excludedMeshesIds.length > 0) {
  61548. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61549. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61550. if (excludedMesh) {
  61551. light_2.excludedMeshes.push(excludedMesh);
  61552. }
  61553. }
  61554. light_2._excludedMeshesIds = [];
  61555. }
  61556. // Included check
  61557. if (light_2._includedOnlyMeshesIds.length > 0) {
  61558. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61559. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61560. if (includedOnlyMesh) {
  61561. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61562. }
  61563. }
  61564. light_2._includedOnlyMeshesIds = [];
  61565. }
  61566. }
  61567. // Actions (scene)
  61568. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61569. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61570. }
  61571. if (!addToScene) {
  61572. container.removeAllFromScene();
  61573. }
  61574. }
  61575. catch (err) {
  61576. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61577. if (onError) {
  61578. onError(msg, err);
  61579. }
  61580. else {
  61581. BABYLON.Tools.Log(msg);
  61582. throw err;
  61583. }
  61584. }
  61585. finally {
  61586. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61587. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61588. }
  61589. }
  61590. return container;
  61591. };
  61592. BABYLON.SceneLoader.RegisterPlugin({
  61593. name: "babylon.js",
  61594. extensions: ".babylon",
  61595. canDirectLoad: function (data) {
  61596. if (data.indexOf("babylon") !== -1) {
  61597. return true;
  61598. }
  61599. return false;
  61600. },
  61601. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61602. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61603. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61604. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61605. // and avoid problems with multiple concurrent .babylon loads.
  61606. var log = "importMesh has failed JSON parse";
  61607. try {
  61608. var parsedData = JSON.parse(data);
  61609. log = "";
  61610. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61611. if (!meshesNames) {
  61612. meshesNames = null;
  61613. }
  61614. else if (!Array.isArray(meshesNames)) {
  61615. meshesNames = [meshesNames];
  61616. }
  61617. var hierarchyIds = new Array();
  61618. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61619. var loadedSkeletonsIds = [];
  61620. var loadedMaterialsIds = [];
  61621. var index;
  61622. var cache;
  61623. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61624. var parsedMesh = parsedData.meshes[index];
  61625. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61626. if (meshesNames !== null) {
  61627. // Remove found mesh name from list.
  61628. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61629. }
  61630. //Geometry?
  61631. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61632. //does the file contain geometries?
  61633. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61634. //find the correct geometry and add it to the scene
  61635. var found = false;
  61636. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61637. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61638. return;
  61639. }
  61640. else {
  61641. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61642. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61643. switch (geometryType) {
  61644. case "boxes":
  61645. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61646. break;
  61647. case "spheres":
  61648. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61649. break;
  61650. case "cylinders":
  61651. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61652. break;
  61653. case "toruses":
  61654. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61655. break;
  61656. case "grounds":
  61657. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61658. break;
  61659. case "planes":
  61660. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61661. break;
  61662. case "torusKnots":
  61663. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61664. break;
  61665. case "vertexData":
  61666. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61667. break;
  61668. }
  61669. found = true;
  61670. }
  61671. });
  61672. }
  61673. });
  61674. if (found === false) {
  61675. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61676. }
  61677. }
  61678. }
  61679. // Material ?
  61680. if (parsedMesh.materialId) {
  61681. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61682. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61683. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61684. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61685. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61686. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61687. var subMatId = parsedMultiMaterial.materials[matIndex];
  61688. loadedMaterialsIds.push(subMatId);
  61689. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61690. if (mat) {
  61691. log += "\n\tMaterial " + mat.toString(fullDetails);
  61692. }
  61693. }
  61694. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61695. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61696. if (mmat) {
  61697. materialFound = true;
  61698. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61699. }
  61700. break;
  61701. }
  61702. }
  61703. }
  61704. if (materialFound === false) {
  61705. loadedMaterialsIds.push(parsedMesh.materialId);
  61706. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61707. if (!mat) {
  61708. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61709. }
  61710. else {
  61711. log += "\n\tMaterial " + mat.toString(fullDetails);
  61712. }
  61713. }
  61714. }
  61715. // Skeleton ?
  61716. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61717. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61718. if (skeletonAlreadyLoaded === false) {
  61719. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61720. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61721. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61722. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61723. skeletons.push(skeleton);
  61724. loadedSkeletonsIds.push(parsedSkeleton.id);
  61725. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61726. }
  61727. }
  61728. }
  61729. }
  61730. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61731. meshes.push(mesh);
  61732. log += "\n\tMesh " + mesh.toString(fullDetails);
  61733. }
  61734. }
  61735. // Connecting parents
  61736. var currentMesh;
  61737. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61738. currentMesh = scene.meshes[index];
  61739. if (currentMesh._waitingParentId) {
  61740. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61741. currentMesh._waitingParentId = null;
  61742. }
  61743. }
  61744. // freeze and compute world matrix application
  61745. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61746. currentMesh = scene.meshes[index];
  61747. if (currentMesh._waitingFreezeWorldMatrix) {
  61748. currentMesh.freezeWorldMatrix();
  61749. currentMesh._waitingFreezeWorldMatrix = null;
  61750. }
  61751. else {
  61752. currentMesh.computeWorldMatrix(true);
  61753. }
  61754. }
  61755. }
  61756. // Particles
  61757. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61758. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61759. var parsedParticleSystem = parsedData.particleSystems[index];
  61760. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61761. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61762. }
  61763. }
  61764. }
  61765. return true;
  61766. }
  61767. catch (err) {
  61768. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61769. if (onError) {
  61770. onError(msg, err);
  61771. }
  61772. else {
  61773. BABYLON.Tools.Log(msg);
  61774. throw err;
  61775. }
  61776. }
  61777. finally {
  61778. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61779. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61780. }
  61781. }
  61782. return false;
  61783. },
  61784. load: function (scene, data, rootUrl, onError) {
  61785. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61786. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61787. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61788. // and avoid problems with multiple concurrent .babylon loads.
  61789. var log = "importScene has failed JSON parse";
  61790. try {
  61791. var parsedData = JSON.parse(data);
  61792. log = "";
  61793. // Scene
  61794. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61795. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61796. }
  61797. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61798. scene.autoClear = parsedData.autoClear;
  61799. }
  61800. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61801. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61802. }
  61803. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61804. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61805. }
  61806. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61807. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61808. }
  61809. // Fog
  61810. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61811. scene.fogMode = parsedData.fogMode;
  61812. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61813. scene.fogStart = parsedData.fogStart;
  61814. scene.fogEnd = parsedData.fogEnd;
  61815. scene.fogDensity = parsedData.fogDensity;
  61816. log += "\tFog mode for scene: ";
  61817. switch (scene.fogMode) {
  61818. // getters not compiling, so using hardcoded
  61819. case 1:
  61820. log += "exp\n";
  61821. break;
  61822. case 2:
  61823. log += "exp2\n";
  61824. break;
  61825. case 3:
  61826. log += "linear\n";
  61827. break;
  61828. }
  61829. }
  61830. //Physics
  61831. if (parsedData.physicsEnabled) {
  61832. var physicsPlugin;
  61833. if (parsedData.physicsEngine === "cannon") {
  61834. physicsPlugin = new BABYLON.CannonJSPlugin();
  61835. }
  61836. else if (parsedData.physicsEngine === "oimo") {
  61837. physicsPlugin = new BABYLON.OimoJSPlugin();
  61838. }
  61839. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61840. //else - default engine, which is currently oimo
  61841. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61842. scene.enablePhysics(physicsGravity, physicsPlugin);
  61843. }
  61844. // Metadata
  61845. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61846. scene.metadata = parsedData.metadata;
  61847. }
  61848. //collisions, if defined. otherwise, default is true
  61849. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61850. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61851. }
  61852. scene.workerCollisions = !!parsedData.workerCollisions;
  61853. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61854. if (!container) {
  61855. return false;
  61856. }
  61857. if (parsedData.autoAnimate) {
  61858. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61859. }
  61860. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61861. scene.setActiveCameraByID(parsedData.activeCameraID);
  61862. }
  61863. // Environment texture
  61864. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61865. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61866. if (parsedData.createDefaultSkybox === true) {
  61867. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61868. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61869. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61870. }
  61871. }
  61872. // Finish
  61873. return true;
  61874. }
  61875. catch (err) {
  61876. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61877. if (onError) {
  61878. onError(msg, err);
  61879. }
  61880. else {
  61881. BABYLON.Tools.Log(msg);
  61882. throw err;
  61883. }
  61884. }
  61885. finally {
  61886. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61887. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61888. }
  61889. }
  61890. return false;
  61891. },
  61892. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61893. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61894. return container;
  61895. }
  61896. });
  61897. })(BABYLON || (BABYLON = {}));
  61898. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61899. var BABYLON;
  61900. (function (BABYLON) {
  61901. var FilesInput = /** @class */ (function () {
  61902. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61903. this.onProcessFileCallback = function () { return true; };
  61904. this._engine = engine;
  61905. this._currentScene = scene;
  61906. this._sceneLoadedCallback = sceneLoadedCallback;
  61907. this._progressCallback = progressCallback;
  61908. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61909. this._textureLoadingCallback = textureLoadingCallback;
  61910. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61911. this._onReloadCallback = onReloadCallback;
  61912. this._errorCallback = errorCallback;
  61913. }
  61914. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61915. var _this = this;
  61916. if (elementToMonitor) {
  61917. this._elementToMonitor = elementToMonitor;
  61918. this._dragEnterHandler = function (e) { _this.drag(e); };
  61919. this._dragOverHandler = function (e) { _this.drag(e); };
  61920. this._dropHandler = function (e) { _this.drop(e); };
  61921. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61922. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61923. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61924. }
  61925. };
  61926. FilesInput.prototype.dispose = function () {
  61927. if (!this._elementToMonitor) {
  61928. return;
  61929. }
  61930. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61931. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61932. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61933. };
  61934. FilesInput.prototype.renderFunction = function () {
  61935. if (this._additionalRenderLoopLogicCallback) {
  61936. this._additionalRenderLoopLogicCallback();
  61937. }
  61938. if (this._currentScene) {
  61939. if (this._textureLoadingCallback) {
  61940. var remaining = this._currentScene.getWaitingItemsCount();
  61941. if (remaining > 0) {
  61942. this._textureLoadingCallback(remaining);
  61943. }
  61944. }
  61945. this._currentScene.render();
  61946. }
  61947. };
  61948. FilesInput.prototype.drag = function (e) {
  61949. e.stopPropagation();
  61950. e.preventDefault();
  61951. };
  61952. FilesInput.prototype.drop = function (eventDrop) {
  61953. eventDrop.stopPropagation();
  61954. eventDrop.preventDefault();
  61955. this.loadFiles(eventDrop);
  61956. };
  61957. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61958. var _this = this;
  61959. var reader = folder.createReader();
  61960. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61961. reader.readEntries(function (entries) {
  61962. remaining.count += entries.length;
  61963. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61964. var entry = entries_1[_i];
  61965. if (entry.isFile) {
  61966. entry.file(function (file) {
  61967. file.correctName = relativePath + file.name;
  61968. files.push(file);
  61969. if (--remaining.count === 0) {
  61970. callback();
  61971. }
  61972. });
  61973. }
  61974. else if (entry.isDirectory) {
  61975. _this._traverseFolder(entry, files, remaining, callback);
  61976. }
  61977. }
  61978. if (--remaining.count) {
  61979. callback();
  61980. }
  61981. });
  61982. };
  61983. FilesInput.prototype._processFiles = function (files) {
  61984. for (var i = 0; i < files.length; i++) {
  61985. var name = files[i].correctName.toLowerCase();
  61986. var extension = name.split('.').pop();
  61987. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61988. continue;
  61989. }
  61990. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61991. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61992. this._sceneFileToLoad = files[i];
  61993. }
  61994. else {
  61995. FilesInput.FilesToLoad[name] = files[i];
  61996. }
  61997. }
  61998. };
  61999. FilesInput.prototype.loadFiles = function (event) {
  62000. var _this = this;
  62001. if (this._startingProcessingFilesCallback)
  62002. this._startingProcessingFilesCallback();
  62003. // Handling data transfer via drag'n'drop
  62004. if (event && event.dataTransfer && event.dataTransfer.files) {
  62005. this._filesToLoad = event.dataTransfer.files;
  62006. }
  62007. // Handling files from input files
  62008. if (event && event.target && event.target.files) {
  62009. this._filesToLoad = event.target.files;
  62010. }
  62011. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62012. var files_1 = new Array();
  62013. var folders = [];
  62014. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62015. for (var i = 0; i < this._filesToLoad.length; i++) {
  62016. var fileToLoad = this._filesToLoad[i];
  62017. var name_1 = fileToLoad.name.toLowerCase();
  62018. var entry = void 0;
  62019. fileToLoad.correctName = name_1;
  62020. if (items) {
  62021. var item = items[i];
  62022. if (item.getAsEntry) {
  62023. entry = item.getAsEntry();
  62024. }
  62025. else if (item.webkitGetAsEntry) {
  62026. entry = item.webkitGetAsEntry();
  62027. }
  62028. }
  62029. if (!entry) {
  62030. files_1.push(fileToLoad);
  62031. }
  62032. else {
  62033. if (entry.isDirectory) {
  62034. folders.push(entry);
  62035. }
  62036. else {
  62037. files_1.push(fileToLoad);
  62038. }
  62039. }
  62040. }
  62041. if (folders.length === 0) {
  62042. this._processFiles(files_1);
  62043. this._processReload();
  62044. }
  62045. else {
  62046. var remaining = { count: folders.length };
  62047. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62048. var folder = folders_1[_i];
  62049. this._traverseFolder(folder, files_1, remaining, function () {
  62050. _this._processFiles(files_1);
  62051. if (remaining.count === 0) {
  62052. _this._processReload();
  62053. }
  62054. });
  62055. }
  62056. }
  62057. }
  62058. };
  62059. FilesInput.prototype._processReload = function () {
  62060. if (this._onReloadCallback) {
  62061. this._onReloadCallback(this._sceneFileToLoad);
  62062. }
  62063. else {
  62064. this.reload();
  62065. }
  62066. };
  62067. FilesInput.prototype.reload = function () {
  62068. var _this = this;
  62069. // If a scene file has been provided
  62070. if (this._sceneFileToLoad) {
  62071. if (this._currentScene) {
  62072. if (BABYLON.Tools.errorsCount > 0) {
  62073. BABYLON.Tools.ClearLogCache();
  62074. }
  62075. this._engine.stopRenderLoop();
  62076. this._currentScene.dispose();
  62077. }
  62078. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62079. if (_this._progressCallback) {
  62080. _this._progressCallback(progress);
  62081. }
  62082. }).then(function (scene) {
  62083. _this._currentScene = scene;
  62084. if (_this._sceneLoadedCallback) {
  62085. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62086. }
  62087. // Wait for textures and shaders to be ready
  62088. _this._currentScene.executeWhenReady(function () {
  62089. _this._engine.runRenderLoop(function () {
  62090. _this.renderFunction();
  62091. });
  62092. });
  62093. }).catch(function (error) {
  62094. if (_this._errorCallback) {
  62095. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62096. }
  62097. });
  62098. }
  62099. else {
  62100. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62101. }
  62102. };
  62103. FilesInput.FilesToLoad = {};
  62104. return FilesInput;
  62105. }());
  62106. BABYLON.FilesInput = FilesInput;
  62107. })(BABYLON || (BABYLON = {}));
  62108. //# sourceMappingURL=babylon.filesInput.js.map
  62109. var BABYLON;
  62110. (function (BABYLON) {
  62111. /**
  62112. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62113. * The underlying implementation relies on an associative array to ensure the best performances.
  62114. * The value can be anything including 'null' but except 'undefined'
  62115. */
  62116. var StringDictionary = /** @class */ (function () {
  62117. function StringDictionary() {
  62118. this._count = 0;
  62119. this._data = {};
  62120. }
  62121. /**
  62122. * This will clear this dictionary and copy the content from the 'source' one.
  62123. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62124. * @param source the dictionary to take the content from and copy to this dictionary
  62125. */
  62126. StringDictionary.prototype.copyFrom = function (source) {
  62127. var _this = this;
  62128. this.clear();
  62129. source.forEach(function (t, v) { return _this.add(t, v); });
  62130. };
  62131. /**
  62132. * Get a value based from its key
  62133. * @param key the given key to get the matching value from
  62134. * @return the value if found, otherwise undefined is returned
  62135. */
  62136. StringDictionary.prototype.get = function (key) {
  62137. var val = this._data[key];
  62138. if (val !== undefined) {
  62139. return val;
  62140. }
  62141. return undefined;
  62142. };
  62143. /**
  62144. * Get a value from its key or add it if it doesn't exist.
  62145. * This method will ensure you that a given key/data will be present in the dictionary.
  62146. * @param key the given key to get the matching value from
  62147. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62148. * The factory will only be invoked if there's no data for the given key.
  62149. * @return the value corresponding to the key.
  62150. */
  62151. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62152. var val = this.get(key);
  62153. if (val !== undefined) {
  62154. return val;
  62155. }
  62156. val = factory(key);
  62157. if (val) {
  62158. this.add(key, val);
  62159. }
  62160. return val;
  62161. };
  62162. /**
  62163. * Get a value from its key if present in the dictionary otherwise add it
  62164. * @param key the key to get the value from
  62165. * @param val if there's no such key/value pair in the dictionary add it with this value
  62166. * @return the value corresponding to the key
  62167. */
  62168. StringDictionary.prototype.getOrAdd = function (key, val) {
  62169. var curVal = this.get(key);
  62170. if (curVal !== undefined) {
  62171. return curVal;
  62172. }
  62173. this.add(key, val);
  62174. return val;
  62175. };
  62176. /**
  62177. * Check if there's a given key in the dictionary
  62178. * @param key the key to check for
  62179. * @return true if the key is present, false otherwise
  62180. */
  62181. StringDictionary.prototype.contains = function (key) {
  62182. return this._data[key] !== undefined;
  62183. };
  62184. /**
  62185. * Add a new key and its corresponding value
  62186. * @param key the key to add
  62187. * @param value the value corresponding to the key
  62188. * @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
  62189. */
  62190. StringDictionary.prototype.add = function (key, value) {
  62191. if (this._data[key] !== undefined) {
  62192. return false;
  62193. }
  62194. this._data[key] = value;
  62195. ++this._count;
  62196. return true;
  62197. };
  62198. StringDictionary.prototype.set = function (key, value) {
  62199. if (this._data[key] === undefined) {
  62200. return false;
  62201. }
  62202. this._data[key] = value;
  62203. return true;
  62204. };
  62205. /**
  62206. * Get the element of the given key and remove it from the dictionary
  62207. * @param key
  62208. */
  62209. StringDictionary.prototype.getAndRemove = function (key) {
  62210. var val = this.get(key);
  62211. if (val !== undefined) {
  62212. delete this._data[key];
  62213. --this._count;
  62214. return val;
  62215. }
  62216. return null;
  62217. };
  62218. /**
  62219. * Remove a key/value from the dictionary.
  62220. * @param key the key to remove
  62221. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62222. */
  62223. StringDictionary.prototype.remove = function (key) {
  62224. if (this.contains(key)) {
  62225. delete this._data[key];
  62226. --this._count;
  62227. return true;
  62228. }
  62229. return false;
  62230. };
  62231. /**
  62232. * Clear the whole content of the dictionary
  62233. */
  62234. StringDictionary.prototype.clear = function () {
  62235. this._data = {};
  62236. this._count = 0;
  62237. };
  62238. Object.defineProperty(StringDictionary.prototype, "count", {
  62239. get: function () {
  62240. return this._count;
  62241. },
  62242. enumerable: true,
  62243. configurable: true
  62244. });
  62245. /**
  62246. * Execute a callback on each key/val of the dictionary.
  62247. * Note that you can remove any element in this dictionary in the callback implementation
  62248. * @param callback the callback to execute on a given key/value pair
  62249. */
  62250. StringDictionary.prototype.forEach = function (callback) {
  62251. for (var cur in this._data) {
  62252. var val = this._data[cur];
  62253. callback(cur, val);
  62254. }
  62255. };
  62256. /**
  62257. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62258. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62259. * Note that you can remove any element in this dictionary in the callback implementation
  62260. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62261. */
  62262. StringDictionary.prototype.first = function (callback) {
  62263. for (var cur in this._data) {
  62264. var val = this._data[cur];
  62265. var res = callback(cur, val);
  62266. if (res) {
  62267. return res;
  62268. }
  62269. }
  62270. return null;
  62271. };
  62272. return StringDictionary;
  62273. }());
  62274. BABYLON.StringDictionary = StringDictionary;
  62275. })(BABYLON || (BABYLON = {}));
  62276. //# sourceMappingURL=babylon.stringDictionary.js.map
  62277. var BABYLON;
  62278. (function (BABYLON) {
  62279. var Tags = /** @class */ (function () {
  62280. function Tags() {
  62281. }
  62282. Tags.EnableFor = function (obj) {
  62283. obj._tags = obj._tags || {};
  62284. obj.hasTags = function () {
  62285. return Tags.HasTags(obj);
  62286. };
  62287. obj.addTags = function (tagsString) {
  62288. return Tags.AddTagsTo(obj, tagsString);
  62289. };
  62290. obj.removeTags = function (tagsString) {
  62291. return Tags.RemoveTagsFrom(obj, tagsString);
  62292. };
  62293. obj.matchesTagsQuery = function (tagsQuery) {
  62294. return Tags.MatchesQuery(obj, tagsQuery);
  62295. };
  62296. };
  62297. Tags.DisableFor = function (obj) {
  62298. delete obj._tags;
  62299. delete obj.hasTags;
  62300. delete obj.addTags;
  62301. delete obj.removeTags;
  62302. delete obj.matchesTagsQuery;
  62303. };
  62304. Tags.HasTags = function (obj) {
  62305. if (!obj._tags) {
  62306. return false;
  62307. }
  62308. return !BABYLON.Tools.IsEmpty(obj._tags);
  62309. };
  62310. Tags.GetTags = function (obj, asString) {
  62311. if (asString === void 0) { asString = true; }
  62312. if (!obj._tags) {
  62313. return null;
  62314. }
  62315. if (asString) {
  62316. var tagsArray = [];
  62317. for (var tag in obj._tags) {
  62318. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62319. tagsArray.push(tag);
  62320. }
  62321. }
  62322. return tagsArray.join(" ");
  62323. }
  62324. else {
  62325. return obj._tags;
  62326. }
  62327. };
  62328. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62329. // a tag cannot start with '||', '&&', and '!'
  62330. // it cannot contain whitespaces
  62331. Tags.AddTagsTo = function (obj, tagsString) {
  62332. if (!tagsString) {
  62333. return;
  62334. }
  62335. if (typeof tagsString !== "string") {
  62336. return;
  62337. }
  62338. var tags = tagsString.split(" ");
  62339. tags.forEach(function (tag, index, array) {
  62340. Tags._AddTagTo(obj, tag);
  62341. });
  62342. };
  62343. Tags._AddTagTo = function (obj, tag) {
  62344. tag = tag.trim();
  62345. if (tag === "" || tag === "true" || tag === "false") {
  62346. return;
  62347. }
  62348. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62349. return;
  62350. }
  62351. Tags.EnableFor(obj);
  62352. obj._tags[tag] = true;
  62353. };
  62354. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62355. if (!Tags.HasTags(obj)) {
  62356. return;
  62357. }
  62358. var tags = tagsString.split(" ");
  62359. for (var t in tags) {
  62360. Tags._RemoveTagFrom(obj, tags[t]);
  62361. }
  62362. };
  62363. Tags._RemoveTagFrom = function (obj, tag) {
  62364. delete obj._tags[tag];
  62365. };
  62366. Tags.MatchesQuery = function (obj, tagsQuery) {
  62367. if (tagsQuery === undefined) {
  62368. return true;
  62369. }
  62370. if (tagsQuery === "") {
  62371. return Tags.HasTags(obj);
  62372. }
  62373. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62374. };
  62375. return Tags;
  62376. }());
  62377. BABYLON.Tags = Tags;
  62378. })(BABYLON || (BABYLON = {}));
  62379. //# sourceMappingURL=babylon.tags.js.map
  62380. var BABYLON;
  62381. (function (BABYLON) {
  62382. var AndOrNotEvaluator = /** @class */ (function () {
  62383. function AndOrNotEvaluator() {
  62384. }
  62385. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62386. if (!query.match(/\([^\(\)]*\)/g)) {
  62387. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62388. }
  62389. else {
  62390. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62391. // remove parenthesis
  62392. r = r.slice(1, r.length - 1);
  62393. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62394. });
  62395. }
  62396. if (query === "true") {
  62397. return true;
  62398. }
  62399. if (query === "false") {
  62400. return false;
  62401. }
  62402. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62403. };
  62404. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62405. evaluateCallback = evaluateCallback || (function (r) {
  62406. return r === "true" ? true : false;
  62407. });
  62408. var result;
  62409. var or = parenthesisContent.split("||");
  62410. for (var i in or) {
  62411. if (or.hasOwnProperty(i)) {
  62412. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62413. var and = ori.split("&&");
  62414. if (and.length > 1) {
  62415. for (var j = 0; j < and.length; ++j) {
  62416. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62417. if (andj !== "true" && andj !== "false") {
  62418. if (andj[0] === "!") {
  62419. result = !evaluateCallback(andj.substring(1));
  62420. }
  62421. else {
  62422. result = evaluateCallback(andj);
  62423. }
  62424. }
  62425. else {
  62426. result = andj === "true" ? true : false;
  62427. }
  62428. if (!result) {
  62429. ori = "false";
  62430. break;
  62431. }
  62432. }
  62433. }
  62434. if (result || ori === "true") {
  62435. result = true;
  62436. break;
  62437. }
  62438. // result equals false (or undefined)
  62439. if (ori !== "true" && ori !== "false") {
  62440. if (ori[0] === "!") {
  62441. result = !evaluateCallback(ori.substring(1));
  62442. }
  62443. else {
  62444. result = evaluateCallback(ori);
  62445. }
  62446. }
  62447. else {
  62448. result = ori === "true" ? true : false;
  62449. }
  62450. }
  62451. }
  62452. // the whole parenthesis scope is replaced by 'true' or 'false'
  62453. return result ? "true" : "false";
  62454. };
  62455. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62456. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62457. // remove whitespaces
  62458. r = r.replace(/[\s]/g, function () { return ""; });
  62459. return r.length % 2 ? "!" : "";
  62460. });
  62461. booleanString = booleanString.trim();
  62462. if (booleanString === "!true") {
  62463. booleanString = "false";
  62464. }
  62465. else if (booleanString === "!false") {
  62466. booleanString = "true";
  62467. }
  62468. return booleanString;
  62469. };
  62470. return AndOrNotEvaluator;
  62471. }());
  62472. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62473. })(BABYLON || (BABYLON = {}));
  62474. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62475. var BABYLON;
  62476. (function (BABYLON) {
  62477. var Database = /** @class */ (function () {
  62478. function Database(urlToScene, callbackManifestChecked) {
  62479. // Handling various flavors of prefixed version of IndexedDB
  62480. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62481. this.callbackManifestChecked = callbackManifestChecked;
  62482. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62483. this.db = null;
  62484. this._enableSceneOffline = false;
  62485. this._enableTexturesOffline = false;
  62486. this.manifestVersionFound = 0;
  62487. this.mustUpdateRessources = false;
  62488. this.hasReachedQuota = false;
  62489. if (!Database.IDBStorageEnabled) {
  62490. this.callbackManifestChecked(true);
  62491. }
  62492. else {
  62493. this.checkManifestFile();
  62494. }
  62495. }
  62496. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62497. get: function () {
  62498. return this._enableSceneOffline;
  62499. },
  62500. enumerable: true,
  62501. configurable: true
  62502. });
  62503. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62504. get: function () {
  62505. return this._enableTexturesOffline;
  62506. },
  62507. enumerable: true,
  62508. configurable: true
  62509. });
  62510. Database.prototype.checkManifestFile = function () {
  62511. var _this = this;
  62512. var noManifestFile = function () {
  62513. _this._enableSceneOffline = false;
  62514. _this._enableTexturesOffline = false;
  62515. _this.callbackManifestChecked(false);
  62516. };
  62517. var timeStampUsed = false;
  62518. var manifestURL = this.currentSceneUrl + ".manifest";
  62519. var xhr = new XMLHttpRequest();
  62520. if (navigator.onLine) {
  62521. // Adding a timestamp to by-pass browsers' cache
  62522. timeStampUsed = true;
  62523. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62524. }
  62525. xhr.open("GET", manifestURL, true);
  62526. xhr.addEventListener("load", function () {
  62527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62528. try {
  62529. var manifestFile = JSON.parse(xhr.response);
  62530. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62531. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62532. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62533. _this.manifestVersionFound = manifestFile.version;
  62534. }
  62535. if (_this.callbackManifestChecked) {
  62536. _this.callbackManifestChecked(true);
  62537. }
  62538. }
  62539. catch (ex) {
  62540. noManifestFile();
  62541. }
  62542. }
  62543. else {
  62544. noManifestFile();
  62545. }
  62546. }, false);
  62547. xhr.addEventListener("error", function (event) {
  62548. if (timeStampUsed) {
  62549. timeStampUsed = false;
  62550. // Let's retry without the timeStamp
  62551. // It could fail when coupled with HTML5 Offline API
  62552. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62553. xhr.open("GET", retryManifestURL, true);
  62554. xhr.send();
  62555. }
  62556. else {
  62557. noManifestFile();
  62558. }
  62559. }, false);
  62560. try {
  62561. xhr.send();
  62562. }
  62563. catch (ex) {
  62564. BABYLON.Tools.Error("Error on XHR send request.");
  62565. this.callbackManifestChecked(false);
  62566. }
  62567. };
  62568. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62569. var _this = this;
  62570. var handleError = function () {
  62571. _this.isSupported = false;
  62572. if (errorCallback)
  62573. errorCallback();
  62574. };
  62575. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62576. // Your browser doesn't support IndexedDB
  62577. this.isSupported = false;
  62578. if (errorCallback)
  62579. errorCallback();
  62580. }
  62581. else {
  62582. // If the DB hasn't been opened or created yet
  62583. if (!this.db) {
  62584. this.hasReachedQuota = false;
  62585. this.isSupported = true;
  62586. var request = this.idbFactory.open("babylonjs", 1);
  62587. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62588. request.onerror = function (event) {
  62589. handleError();
  62590. };
  62591. // executes when a version change transaction cannot complete due to other active transactions
  62592. request.onblocked = function (event) {
  62593. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62594. handleError();
  62595. };
  62596. // DB has been opened successfully
  62597. request.onsuccess = function (event) {
  62598. _this.db = request.result;
  62599. successCallback();
  62600. };
  62601. // Initialization of the DB. Creating Scenes & Textures stores
  62602. request.onupgradeneeded = function (event) {
  62603. _this.db = (event.target).result;
  62604. if (_this.db) {
  62605. try {
  62606. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62607. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62608. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62609. }
  62610. catch (ex) {
  62611. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62612. handleError();
  62613. }
  62614. }
  62615. };
  62616. }
  62617. else {
  62618. if (successCallback)
  62619. successCallback();
  62620. }
  62621. }
  62622. };
  62623. Database.prototype.loadImageFromDB = function (url, image) {
  62624. var _this = this;
  62625. var completeURL = Database.ReturnFullUrlLocation(url);
  62626. var saveAndLoadImage = function () {
  62627. if (!_this.hasReachedQuota && _this.db !== null) {
  62628. // the texture is not yet in the DB, let's try to save it
  62629. _this._saveImageIntoDBAsync(completeURL, image);
  62630. }
  62631. else {
  62632. image.src = url;
  62633. }
  62634. };
  62635. if (!this.mustUpdateRessources) {
  62636. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62637. }
  62638. else {
  62639. saveAndLoadImage();
  62640. }
  62641. };
  62642. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62643. if (this.isSupported && this.db !== null) {
  62644. var texture;
  62645. var transaction = this.db.transaction(["textures"]);
  62646. transaction.onabort = function (event) {
  62647. image.src = url;
  62648. };
  62649. transaction.oncomplete = function (event) {
  62650. var blobTextureURL;
  62651. if (texture) {
  62652. var URL = window.URL || window.webkitURL;
  62653. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62654. image.onerror = function () {
  62655. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62656. image.src = url;
  62657. };
  62658. image.src = blobTextureURL;
  62659. }
  62660. else {
  62661. notInDBCallback();
  62662. }
  62663. };
  62664. var getRequest = transaction.objectStore("textures").get(url);
  62665. getRequest.onsuccess = function (event) {
  62666. texture = (event.target).result;
  62667. };
  62668. getRequest.onerror = function (event) {
  62669. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62670. image.src = url;
  62671. };
  62672. }
  62673. else {
  62674. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62675. image.src = url;
  62676. }
  62677. };
  62678. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62679. var _this = this;
  62680. if (this.isSupported) {
  62681. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62682. var generateBlobUrl = function () {
  62683. var blobTextureURL;
  62684. if (blob) {
  62685. var URL = window.URL || window.webkitURL;
  62686. try {
  62687. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62688. }
  62689. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62690. catch (ex) {
  62691. blobTextureURL = URL.createObjectURL(blob);
  62692. }
  62693. }
  62694. if (blobTextureURL) {
  62695. image.src = blobTextureURL;
  62696. }
  62697. };
  62698. if (Database.IsUASupportingBlobStorage) {
  62699. var xhr = new XMLHttpRequest(), blob;
  62700. xhr.open("GET", url, true);
  62701. xhr.responseType = "blob";
  62702. xhr.addEventListener("load", function () {
  62703. if (xhr.status === 200 && _this.db) {
  62704. // Blob as response (XHR2)
  62705. blob = xhr.response;
  62706. var transaction = _this.db.transaction(["textures"], "readwrite");
  62707. // the transaction could abort because of a QuotaExceededError error
  62708. transaction.onabort = function (event) {
  62709. try {
  62710. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62711. var srcElement = (event.srcElement || event.target);
  62712. var error = srcElement.error;
  62713. if (error && error.name === "QuotaExceededError") {
  62714. _this.hasReachedQuota = true;
  62715. }
  62716. }
  62717. catch (ex) { }
  62718. generateBlobUrl();
  62719. };
  62720. transaction.oncomplete = function (event) {
  62721. generateBlobUrl();
  62722. };
  62723. var newTexture = { textureUrl: url, data: blob };
  62724. try {
  62725. // Put the blob into the dabase
  62726. var addRequest = transaction.objectStore("textures").put(newTexture);
  62727. addRequest.onsuccess = function (event) {
  62728. };
  62729. addRequest.onerror = function (event) {
  62730. generateBlobUrl();
  62731. };
  62732. }
  62733. catch (ex) {
  62734. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62735. if (ex.code === 25) {
  62736. Database.IsUASupportingBlobStorage = false;
  62737. }
  62738. image.src = url;
  62739. }
  62740. }
  62741. else {
  62742. image.src = url;
  62743. }
  62744. }, false);
  62745. xhr.addEventListener("error", function (event) {
  62746. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62747. image.src = url;
  62748. }, false);
  62749. xhr.send();
  62750. }
  62751. else {
  62752. image.src = url;
  62753. }
  62754. }
  62755. else {
  62756. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62757. image.src = url;
  62758. }
  62759. };
  62760. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62761. var _this = this;
  62762. var updateVersion = function () {
  62763. // the version is not yet in the DB or we need to update it
  62764. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62765. };
  62766. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62767. };
  62768. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62769. var _this = this;
  62770. if (this.isSupported && this.db) {
  62771. var version;
  62772. try {
  62773. var transaction = this.db.transaction(["versions"]);
  62774. transaction.oncomplete = function (event) {
  62775. if (version) {
  62776. // If the version in the JSON file is > than the version in DB
  62777. if (_this.manifestVersionFound > version.data) {
  62778. _this.mustUpdateRessources = true;
  62779. updateInDBCallback();
  62780. }
  62781. else {
  62782. callback(version.data);
  62783. }
  62784. }
  62785. else {
  62786. _this.mustUpdateRessources = true;
  62787. updateInDBCallback();
  62788. }
  62789. };
  62790. transaction.onabort = function (event) {
  62791. callback(-1);
  62792. };
  62793. var getRequest = transaction.objectStore("versions").get(url);
  62794. getRequest.onsuccess = function (event) {
  62795. version = (event.target).result;
  62796. };
  62797. getRequest.onerror = function (event) {
  62798. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62799. callback(-1);
  62800. };
  62801. }
  62802. catch (ex) {
  62803. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62804. callback(-1);
  62805. }
  62806. }
  62807. else {
  62808. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62809. callback(-1);
  62810. }
  62811. };
  62812. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62813. var _this = this;
  62814. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62815. try {
  62816. // Open a transaction to the database
  62817. var transaction = this.db.transaction(["versions"], "readwrite");
  62818. // the transaction could abort because of a QuotaExceededError error
  62819. transaction.onabort = function (event) {
  62820. try {
  62821. var error = event.srcElement['error'];
  62822. if (error && error.name === "QuotaExceededError") {
  62823. _this.hasReachedQuota = true;
  62824. }
  62825. }
  62826. catch (ex) { }
  62827. callback(-1);
  62828. };
  62829. transaction.oncomplete = function (event) {
  62830. callback(_this.manifestVersionFound);
  62831. };
  62832. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62833. // Put the scene into the database
  62834. var addRequest = transaction.objectStore("versions").put(newVersion);
  62835. addRequest.onsuccess = function (event) {
  62836. };
  62837. addRequest.onerror = function (event) {
  62838. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62839. };
  62840. }
  62841. catch (ex) {
  62842. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62843. callback(-1);
  62844. }
  62845. }
  62846. else {
  62847. callback(-1);
  62848. }
  62849. };
  62850. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62851. var _this = this;
  62852. var completeUrl = Database.ReturnFullUrlLocation(url);
  62853. var saveAndLoadFile = function () {
  62854. // the scene is not yet in the DB, let's try to save it
  62855. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62856. };
  62857. this._checkVersionFromDB(completeUrl, function (version) {
  62858. if (version !== -1) {
  62859. if (!_this.mustUpdateRessources) {
  62860. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62861. }
  62862. else {
  62863. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62864. }
  62865. }
  62866. else {
  62867. if (errorCallback) {
  62868. errorCallback();
  62869. }
  62870. }
  62871. });
  62872. };
  62873. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62874. if (this.isSupported && this.db) {
  62875. var targetStore;
  62876. if (url.indexOf(".babylon") !== -1) {
  62877. targetStore = "scenes";
  62878. }
  62879. else {
  62880. targetStore = "textures";
  62881. }
  62882. var file;
  62883. var transaction = this.db.transaction([targetStore]);
  62884. transaction.oncomplete = function (event) {
  62885. if (file) {
  62886. callback(file.data);
  62887. }
  62888. else {
  62889. notInDBCallback();
  62890. }
  62891. };
  62892. transaction.onabort = function (event) {
  62893. notInDBCallback();
  62894. };
  62895. var getRequest = transaction.objectStore(targetStore).get(url);
  62896. getRequest.onsuccess = function (event) {
  62897. file = (event.target).result;
  62898. };
  62899. getRequest.onerror = function (event) {
  62900. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62901. notInDBCallback();
  62902. };
  62903. }
  62904. else {
  62905. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62906. callback();
  62907. }
  62908. };
  62909. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62910. var _this = this;
  62911. if (this.isSupported) {
  62912. var targetStore;
  62913. if (url.indexOf(".babylon") !== -1) {
  62914. targetStore = "scenes";
  62915. }
  62916. else {
  62917. targetStore = "textures";
  62918. }
  62919. // Create XHR
  62920. var xhr = new XMLHttpRequest();
  62921. var fileData;
  62922. xhr.open("GET", url, true);
  62923. if (useArrayBuffer) {
  62924. xhr.responseType = "arraybuffer";
  62925. }
  62926. if (progressCallback) {
  62927. xhr.onprogress = progressCallback;
  62928. }
  62929. xhr.addEventListener("load", function () {
  62930. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62931. // Blob as response (XHR2)
  62932. //fileData = xhr.responseText;
  62933. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62934. if (!_this.hasReachedQuota && _this.db) {
  62935. // Open a transaction to the database
  62936. var transaction = _this.db.transaction([targetStore], "readwrite");
  62937. // the transaction could abort because of a QuotaExceededError error
  62938. transaction.onabort = function (event) {
  62939. try {
  62940. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62941. var error = event.srcElement['error'];
  62942. if (error && error.name === "QuotaExceededError") {
  62943. _this.hasReachedQuota = true;
  62944. }
  62945. }
  62946. catch (ex) { }
  62947. callback(fileData);
  62948. };
  62949. transaction.oncomplete = function (event) {
  62950. callback(fileData);
  62951. };
  62952. var newFile;
  62953. if (targetStore === "scenes") {
  62954. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62955. }
  62956. else {
  62957. newFile = { textureUrl: url, data: fileData };
  62958. }
  62959. try {
  62960. // Put the scene into the database
  62961. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62962. addRequest.onsuccess = function (event) {
  62963. };
  62964. addRequest.onerror = function (event) {
  62965. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62966. };
  62967. }
  62968. catch (ex) {
  62969. callback(fileData);
  62970. }
  62971. }
  62972. else {
  62973. callback(fileData);
  62974. }
  62975. }
  62976. else {
  62977. callback();
  62978. }
  62979. }, false);
  62980. xhr.addEventListener("error", function (event) {
  62981. BABYLON.Tools.Error("error on XHR request.");
  62982. callback();
  62983. }, false);
  62984. xhr.send();
  62985. }
  62986. else {
  62987. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62988. callback();
  62989. }
  62990. };
  62991. Database.IsUASupportingBlobStorage = true;
  62992. Database.IDBStorageEnabled = true;
  62993. Database.parseURL = function (url) {
  62994. var a = document.createElement('a');
  62995. a.href = url;
  62996. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62997. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62998. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62999. return absLocation;
  63000. };
  63001. Database.ReturnFullUrlLocation = function (url) {
  63002. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63003. return (Database.parseURL(window.location.href) + url);
  63004. }
  63005. else {
  63006. return url;
  63007. }
  63008. };
  63009. return Database;
  63010. }());
  63011. BABYLON.Database = Database;
  63012. })(BABYLON || (BABYLON = {}));
  63013. //# sourceMappingURL=babylon.database.js.map
  63014. var BABYLON;
  63015. (function (BABYLON) {
  63016. var FresnelParameters = /** @class */ (function () {
  63017. function FresnelParameters() {
  63018. this._isEnabled = true;
  63019. this.leftColor = BABYLON.Color3.White();
  63020. this.rightColor = BABYLON.Color3.Black();
  63021. this.bias = 0;
  63022. this.power = 1;
  63023. }
  63024. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63025. get: function () {
  63026. return this._isEnabled;
  63027. },
  63028. set: function (value) {
  63029. if (this._isEnabled === value) {
  63030. return;
  63031. }
  63032. this._isEnabled = value;
  63033. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63034. },
  63035. enumerable: true,
  63036. configurable: true
  63037. });
  63038. FresnelParameters.prototype.clone = function () {
  63039. var newFresnelParameters = new FresnelParameters();
  63040. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63041. return newFresnelParameters;
  63042. };
  63043. FresnelParameters.prototype.serialize = function () {
  63044. var serializationObject = {};
  63045. serializationObject.isEnabled = this.isEnabled;
  63046. serializationObject.leftColor = this.leftColor;
  63047. serializationObject.rightColor = this.rightColor;
  63048. serializationObject.bias = this.bias;
  63049. serializationObject.power = this.power;
  63050. return serializationObject;
  63051. };
  63052. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63053. var fresnelParameters = new FresnelParameters();
  63054. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63055. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63056. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63057. fresnelParameters.bias = parsedFresnelParameters.bias;
  63058. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63059. return fresnelParameters;
  63060. };
  63061. return FresnelParameters;
  63062. }());
  63063. BABYLON.FresnelParameters = FresnelParameters;
  63064. })(BABYLON || (BABYLON = {}));
  63065. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63066. var BABYLON;
  63067. (function (BABYLON) {
  63068. var MultiMaterial = /** @class */ (function (_super) {
  63069. __extends(MultiMaterial, _super);
  63070. function MultiMaterial(name, scene) {
  63071. var _this = _super.call(this, name, scene, true) || this;
  63072. scene.multiMaterials.push(_this);
  63073. _this.subMaterials = new Array();
  63074. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63075. return _this;
  63076. }
  63077. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63078. get: function () {
  63079. return this._subMaterials;
  63080. },
  63081. set: function (value) {
  63082. this._subMaterials = value;
  63083. this._hookArray(value);
  63084. },
  63085. enumerable: true,
  63086. configurable: true
  63087. });
  63088. MultiMaterial.prototype._hookArray = function (array) {
  63089. var _this = this;
  63090. var oldPush = array.push;
  63091. array.push = function () {
  63092. var items = [];
  63093. for (var _i = 0; _i < arguments.length; _i++) {
  63094. items[_i] = arguments[_i];
  63095. }
  63096. var result = oldPush.apply(array, items);
  63097. _this._markAllSubMeshesAsTexturesDirty();
  63098. return result;
  63099. };
  63100. var oldSplice = array.splice;
  63101. array.splice = function (index, deleteCount) {
  63102. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63103. _this._markAllSubMeshesAsTexturesDirty();
  63104. return deleted;
  63105. };
  63106. };
  63107. // Properties
  63108. MultiMaterial.prototype.getSubMaterial = function (index) {
  63109. if (index < 0 || index >= this.subMaterials.length) {
  63110. return this.getScene().defaultMaterial;
  63111. }
  63112. return this.subMaterials[index];
  63113. };
  63114. MultiMaterial.prototype.getActiveTextures = function () {
  63115. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63116. if (subMaterial) {
  63117. return subMaterial.getActiveTextures();
  63118. }
  63119. else {
  63120. return [];
  63121. }
  63122. }));
  63123. var _a;
  63124. };
  63125. // Methods
  63126. MultiMaterial.prototype.getClassName = function () {
  63127. return "MultiMaterial";
  63128. };
  63129. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63130. for (var index = 0; index < this.subMaterials.length; index++) {
  63131. var subMaterial = this.subMaterials[index];
  63132. if (subMaterial) {
  63133. if (subMaterial.storeEffectOnSubMeshes) {
  63134. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63135. return false;
  63136. }
  63137. continue;
  63138. }
  63139. if (!subMaterial.isReady(mesh)) {
  63140. return false;
  63141. }
  63142. }
  63143. }
  63144. return true;
  63145. };
  63146. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63147. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63148. for (var index = 0; index < this.subMaterials.length; index++) {
  63149. var subMaterial = null;
  63150. var current = this.subMaterials[index];
  63151. if (cloneChildren && current) {
  63152. subMaterial = current.clone(name + "-" + current.name);
  63153. }
  63154. else {
  63155. subMaterial = this.subMaterials[index];
  63156. }
  63157. newMultiMaterial.subMaterials.push(subMaterial);
  63158. }
  63159. return newMultiMaterial;
  63160. };
  63161. MultiMaterial.prototype.serialize = function () {
  63162. var serializationObject = {};
  63163. serializationObject.name = this.name;
  63164. serializationObject.id = this.id;
  63165. if (BABYLON.Tags) {
  63166. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63167. }
  63168. serializationObject.materials = [];
  63169. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63170. var subMat = this.subMaterials[matIndex];
  63171. if (subMat) {
  63172. serializationObject.materials.push(subMat.id);
  63173. }
  63174. else {
  63175. serializationObject.materials.push(null);
  63176. }
  63177. }
  63178. return serializationObject;
  63179. };
  63180. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63181. var scene = this.getScene();
  63182. if (!scene) {
  63183. return;
  63184. }
  63185. var index = scene.multiMaterials.indexOf(this);
  63186. if (index >= 0) {
  63187. scene.multiMaterials.splice(index, 1);
  63188. }
  63189. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63190. };
  63191. return MultiMaterial;
  63192. }(BABYLON.Material));
  63193. BABYLON.MultiMaterial = MultiMaterial;
  63194. })(BABYLON || (BABYLON = {}));
  63195. //# sourceMappingURL=babylon.multiMaterial.js.map
  63196. var BABYLON;
  63197. (function (BABYLON) {
  63198. var FreeCameraTouchInput = /** @class */ (function () {
  63199. function FreeCameraTouchInput() {
  63200. this._offsetX = null;
  63201. this._offsetY = null;
  63202. this._pointerPressed = new Array();
  63203. this.touchAngularSensibility = 200000.0;
  63204. this.touchMoveSensibility = 250.0;
  63205. }
  63206. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63207. var _this = this;
  63208. var previousPosition = null;
  63209. if (this._pointerInput === undefined) {
  63210. this._onLostFocus = function (evt) {
  63211. _this._offsetX = null;
  63212. _this._offsetY = null;
  63213. };
  63214. this._pointerInput = function (p, s) {
  63215. var evt = p.event;
  63216. if (evt.pointerType === "mouse") {
  63217. return;
  63218. }
  63219. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63220. if (!noPreventDefault) {
  63221. evt.preventDefault();
  63222. }
  63223. _this._pointerPressed.push(evt.pointerId);
  63224. if (_this._pointerPressed.length !== 1) {
  63225. return;
  63226. }
  63227. previousPosition = {
  63228. x: evt.clientX,
  63229. y: evt.clientY
  63230. };
  63231. }
  63232. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63233. if (!noPreventDefault) {
  63234. evt.preventDefault();
  63235. }
  63236. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63237. if (index === -1) {
  63238. return;
  63239. }
  63240. _this._pointerPressed.splice(index, 1);
  63241. if (index != 0) {
  63242. return;
  63243. }
  63244. previousPosition = null;
  63245. _this._offsetX = null;
  63246. _this._offsetY = null;
  63247. }
  63248. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63249. if (!noPreventDefault) {
  63250. evt.preventDefault();
  63251. }
  63252. if (!previousPosition) {
  63253. return;
  63254. }
  63255. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63256. if (index != 0) {
  63257. return;
  63258. }
  63259. _this._offsetX = evt.clientX - previousPosition.x;
  63260. _this._offsetY = -(evt.clientY - previousPosition.y);
  63261. }
  63262. };
  63263. }
  63264. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63265. if (this._onLostFocus) {
  63266. element.addEventListener("blur", this._onLostFocus);
  63267. }
  63268. };
  63269. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63270. if (this._pointerInput && element) {
  63271. if (this._observer) {
  63272. this.camera.getScene().onPointerObservable.remove(this._observer);
  63273. this._observer = null;
  63274. }
  63275. if (this._onLostFocus) {
  63276. element.removeEventListener("blur", this._onLostFocus);
  63277. this._onLostFocus = null;
  63278. }
  63279. this._pointerPressed = [];
  63280. this._offsetX = null;
  63281. this._offsetY = null;
  63282. }
  63283. };
  63284. FreeCameraTouchInput.prototype.checkInputs = function () {
  63285. if (this._offsetX && this._offsetY) {
  63286. var camera = this.camera;
  63287. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63288. if (this._pointerPressed.length > 1) {
  63289. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63290. }
  63291. else {
  63292. var speed = camera._computeLocalCameraSpeed();
  63293. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63294. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63295. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63296. }
  63297. }
  63298. };
  63299. FreeCameraTouchInput.prototype.getClassName = function () {
  63300. return "FreeCameraTouchInput";
  63301. };
  63302. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63303. return "touch";
  63304. };
  63305. __decorate([
  63306. BABYLON.serialize()
  63307. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63308. __decorate([
  63309. BABYLON.serialize()
  63310. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63311. return FreeCameraTouchInput;
  63312. }());
  63313. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63314. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63315. })(BABYLON || (BABYLON = {}));
  63316. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63317. var BABYLON;
  63318. (function (BABYLON) {
  63319. // We're mainly based on the logic defined into the FreeCamera code
  63320. var TouchCamera = /** @class */ (function (_super) {
  63321. __extends(TouchCamera, _super);
  63322. //-- end properties for backward compatibility for inputs
  63323. function TouchCamera(name, position, scene) {
  63324. var _this = _super.call(this, name, position, scene) || this;
  63325. _this.inputs.addTouch();
  63326. _this._setupInputs();
  63327. return _this;
  63328. }
  63329. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63330. //-- Begin properties for backward compatibility for inputs
  63331. get: function () {
  63332. var touch = this.inputs.attached["touch"];
  63333. if (touch)
  63334. return touch.touchAngularSensibility;
  63335. return 0;
  63336. },
  63337. set: function (value) {
  63338. var touch = this.inputs.attached["touch"];
  63339. if (touch)
  63340. touch.touchAngularSensibility = value;
  63341. },
  63342. enumerable: true,
  63343. configurable: true
  63344. });
  63345. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63346. get: function () {
  63347. var touch = this.inputs.attached["touch"];
  63348. if (touch)
  63349. return touch.touchMoveSensibility;
  63350. return 0;
  63351. },
  63352. set: function (value) {
  63353. var touch = this.inputs.attached["touch"];
  63354. if (touch)
  63355. touch.touchMoveSensibility = value;
  63356. },
  63357. enumerable: true,
  63358. configurable: true
  63359. });
  63360. TouchCamera.prototype.getClassName = function () {
  63361. return "TouchCamera";
  63362. };
  63363. TouchCamera.prototype._setupInputs = function () {
  63364. var mouse = this.inputs.attached["mouse"];
  63365. if (mouse) {
  63366. mouse.touchEnabled = false;
  63367. }
  63368. };
  63369. return TouchCamera;
  63370. }(BABYLON.FreeCamera));
  63371. BABYLON.TouchCamera = TouchCamera;
  63372. })(BABYLON || (BABYLON = {}));
  63373. //# sourceMappingURL=babylon.touchCamera.js.map
  63374. var BABYLON;
  63375. (function (BABYLON) {
  63376. var ProceduralTexture = /** @class */ (function (_super) {
  63377. __extends(ProceduralTexture, _super);
  63378. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63379. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63380. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63381. if (isCube === void 0) { isCube = false; }
  63382. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63383. _this.isCube = isCube;
  63384. _this.isEnabled = true;
  63385. _this._currentRefreshId = -1;
  63386. _this._refreshRate = 1;
  63387. _this._vertexBuffers = {};
  63388. _this._uniforms = new Array();
  63389. _this._samplers = new Array();
  63390. _this._textures = {};
  63391. _this._floats = {};
  63392. _this._floatsArrays = {};
  63393. _this._colors3 = {};
  63394. _this._colors4 = {};
  63395. _this._vectors2 = {};
  63396. _this._vectors3 = {};
  63397. _this._matrices = {};
  63398. _this._fallbackTextureUsed = false;
  63399. scene._proceduralTextures.push(_this);
  63400. _this._engine = scene.getEngine();
  63401. _this.name = name;
  63402. _this.isRenderTarget = true;
  63403. _this._size = size;
  63404. _this._generateMipMaps = generateMipMaps;
  63405. _this.setFragment(fragment);
  63406. _this._fallbackTexture = fallbackTexture;
  63407. if (isCube) {
  63408. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63409. _this.setFloat("face", 0);
  63410. }
  63411. else {
  63412. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63413. }
  63414. // VBO
  63415. var vertices = [];
  63416. vertices.push(1, 1);
  63417. vertices.push(-1, 1);
  63418. vertices.push(-1, -1);
  63419. vertices.push(1, -1);
  63420. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63421. _this._createIndexBuffer();
  63422. return _this;
  63423. }
  63424. ProceduralTexture.prototype._createIndexBuffer = function () {
  63425. var engine = this._engine;
  63426. // Indices
  63427. var indices = [];
  63428. indices.push(0);
  63429. indices.push(1);
  63430. indices.push(2);
  63431. indices.push(0);
  63432. indices.push(2);
  63433. indices.push(3);
  63434. this._indexBuffer = engine.createIndexBuffer(indices);
  63435. };
  63436. ProceduralTexture.prototype._rebuild = function () {
  63437. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63438. if (vb) {
  63439. vb._rebuild();
  63440. }
  63441. this._createIndexBuffer();
  63442. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63443. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63444. }
  63445. };
  63446. ProceduralTexture.prototype.reset = function () {
  63447. if (this._effect === undefined) {
  63448. return;
  63449. }
  63450. var engine = this._engine;
  63451. engine._releaseEffect(this._effect);
  63452. };
  63453. ProceduralTexture.prototype.isReady = function () {
  63454. var _this = this;
  63455. var engine = this._engine;
  63456. var shaders;
  63457. if (!this._fragment) {
  63458. return false;
  63459. }
  63460. if (this._fallbackTextureUsed) {
  63461. return true;
  63462. }
  63463. if (this._fragment.fragmentElement !== undefined) {
  63464. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63465. }
  63466. else {
  63467. shaders = { vertex: "procedural", fragment: this._fragment };
  63468. }
  63469. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63470. _this.releaseInternalTexture();
  63471. if (_this._fallbackTexture) {
  63472. _this._texture = _this._fallbackTexture._texture;
  63473. if (_this._texture) {
  63474. _this._texture.incrementReferences();
  63475. }
  63476. }
  63477. _this._fallbackTextureUsed = true;
  63478. });
  63479. return this._effect.isReady();
  63480. };
  63481. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63482. this._currentRefreshId = -1;
  63483. };
  63484. ProceduralTexture.prototype.setFragment = function (fragment) {
  63485. this._fragment = fragment;
  63486. };
  63487. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63488. get: function () {
  63489. return this._refreshRate;
  63490. },
  63491. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63492. set: function (value) {
  63493. this._refreshRate = value;
  63494. this.resetRefreshCounter();
  63495. },
  63496. enumerable: true,
  63497. configurable: true
  63498. });
  63499. ProceduralTexture.prototype._shouldRender = function () {
  63500. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63501. return false;
  63502. }
  63503. if (this._fallbackTextureUsed) {
  63504. return false;
  63505. }
  63506. if (this._currentRefreshId === -1) {
  63507. this._currentRefreshId = 1;
  63508. return true;
  63509. }
  63510. if (this.refreshRate === this._currentRefreshId) {
  63511. this._currentRefreshId = 1;
  63512. return true;
  63513. }
  63514. this._currentRefreshId++;
  63515. return false;
  63516. };
  63517. ProceduralTexture.prototype.getRenderSize = function () {
  63518. return this._size;
  63519. };
  63520. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63521. if (this._fallbackTextureUsed) {
  63522. return;
  63523. }
  63524. this.releaseInternalTexture();
  63525. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63526. };
  63527. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63528. if (this._uniforms.indexOf(uniformName) === -1) {
  63529. this._uniforms.push(uniformName);
  63530. }
  63531. };
  63532. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63533. if (this._samplers.indexOf(name) === -1) {
  63534. this._samplers.push(name);
  63535. }
  63536. this._textures[name] = texture;
  63537. return this;
  63538. };
  63539. ProceduralTexture.prototype.setFloat = function (name, value) {
  63540. this._checkUniform(name);
  63541. this._floats[name] = value;
  63542. return this;
  63543. };
  63544. ProceduralTexture.prototype.setFloats = function (name, value) {
  63545. this._checkUniform(name);
  63546. this._floatsArrays[name] = value;
  63547. return this;
  63548. };
  63549. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63550. this._checkUniform(name);
  63551. this._colors3[name] = value;
  63552. return this;
  63553. };
  63554. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63555. this._checkUniform(name);
  63556. this._colors4[name] = value;
  63557. return this;
  63558. };
  63559. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63560. this._checkUniform(name);
  63561. this._vectors2[name] = value;
  63562. return this;
  63563. };
  63564. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63565. this._checkUniform(name);
  63566. this._vectors3[name] = value;
  63567. return this;
  63568. };
  63569. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63570. this._checkUniform(name);
  63571. this._matrices[name] = value;
  63572. return this;
  63573. };
  63574. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63575. var scene = this.getScene();
  63576. if (!scene) {
  63577. return;
  63578. }
  63579. var engine = this._engine;
  63580. // Render
  63581. engine.enableEffect(this._effect);
  63582. engine.setState(false);
  63583. // Texture
  63584. for (var name in this._textures) {
  63585. this._effect.setTexture(name, this._textures[name]);
  63586. }
  63587. // Float
  63588. for (name in this._floats) {
  63589. this._effect.setFloat(name, this._floats[name]);
  63590. }
  63591. // Floats
  63592. for (name in this._floatsArrays) {
  63593. this._effect.setArray(name, this._floatsArrays[name]);
  63594. }
  63595. // Color3
  63596. for (name in this._colors3) {
  63597. this._effect.setColor3(name, this._colors3[name]);
  63598. }
  63599. // Color4
  63600. for (name in this._colors4) {
  63601. var color = this._colors4[name];
  63602. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63603. }
  63604. // Vector2
  63605. for (name in this._vectors2) {
  63606. this._effect.setVector2(name, this._vectors2[name]);
  63607. }
  63608. // Vector3
  63609. for (name in this._vectors3) {
  63610. this._effect.setVector3(name, this._vectors3[name]);
  63611. }
  63612. // Matrix
  63613. for (name in this._matrices) {
  63614. this._effect.setMatrix(name, this._matrices[name]);
  63615. }
  63616. if (!this._texture) {
  63617. return;
  63618. }
  63619. if (this.isCube) {
  63620. for (var face = 0; face < 6; face++) {
  63621. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63622. // VBOs
  63623. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63624. this._effect.setFloat("face", face);
  63625. // Clear
  63626. engine.clear(scene.clearColor, true, true, true);
  63627. // Draw order
  63628. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63629. // Mipmaps
  63630. if (face === 5) {
  63631. engine.generateMipMapsForCubemap(this._texture);
  63632. }
  63633. }
  63634. }
  63635. else {
  63636. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63637. // VBOs
  63638. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63639. // Clear
  63640. engine.clear(scene.clearColor, true, true, true);
  63641. // Draw order
  63642. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63643. }
  63644. // Unbind
  63645. engine.unBindFramebuffer(this._texture, this.isCube);
  63646. if (this.onGenerated) {
  63647. this.onGenerated();
  63648. }
  63649. };
  63650. ProceduralTexture.prototype.clone = function () {
  63651. var textureSize = this.getSize();
  63652. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63653. // Base texture
  63654. newTexture.hasAlpha = this.hasAlpha;
  63655. newTexture.level = this.level;
  63656. // RenderTarget Texture
  63657. newTexture.coordinatesMode = this.coordinatesMode;
  63658. return newTexture;
  63659. };
  63660. ProceduralTexture.prototype.dispose = function () {
  63661. var scene = this.getScene();
  63662. if (!scene) {
  63663. return;
  63664. }
  63665. var index = scene._proceduralTextures.indexOf(this);
  63666. if (index >= 0) {
  63667. scene._proceduralTextures.splice(index, 1);
  63668. }
  63669. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63670. if (vertexBuffer) {
  63671. vertexBuffer.dispose();
  63672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63673. }
  63674. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63675. this._indexBuffer = null;
  63676. }
  63677. _super.prototype.dispose.call(this);
  63678. };
  63679. return ProceduralTexture;
  63680. }(BABYLON.Texture));
  63681. BABYLON.ProceduralTexture = ProceduralTexture;
  63682. })(BABYLON || (BABYLON = {}));
  63683. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63684. var BABYLON;
  63685. (function (BABYLON) {
  63686. var CustomProceduralTexture = /** @class */ (function (_super) {
  63687. __extends(CustomProceduralTexture, _super);
  63688. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63689. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63690. _this._animate = true;
  63691. _this._time = 0;
  63692. _this._texturePath = texturePath;
  63693. //Try to load json
  63694. _this.loadJson(texturePath);
  63695. _this.refreshRate = 1;
  63696. return _this;
  63697. }
  63698. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63699. var _this = this;
  63700. var noConfigFile = function () {
  63701. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63702. try {
  63703. _this.setFragment(_this._texturePath);
  63704. }
  63705. catch (ex) {
  63706. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63707. }
  63708. };
  63709. var configFileUrl = jsonUrl + "/config.json";
  63710. var xhr = new XMLHttpRequest();
  63711. xhr.open("GET", configFileUrl, true);
  63712. xhr.addEventListener("load", function () {
  63713. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63714. try {
  63715. _this._config = JSON.parse(xhr.response);
  63716. _this.updateShaderUniforms();
  63717. _this.updateTextures();
  63718. _this.setFragment(_this._texturePath + "/custom");
  63719. _this._animate = _this._config.animate;
  63720. _this.refreshRate = _this._config.refreshrate;
  63721. }
  63722. catch (ex) {
  63723. noConfigFile();
  63724. }
  63725. }
  63726. else {
  63727. noConfigFile();
  63728. }
  63729. }, false);
  63730. xhr.addEventListener("error", function () {
  63731. noConfigFile();
  63732. }, false);
  63733. try {
  63734. xhr.send();
  63735. }
  63736. catch (ex) {
  63737. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63738. }
  63739. };
  63740. CustomProceduralTexture.prototype.isReady = function () {
  63741. if (!_super.prototype.isReady.call(this)) {
  63742. return false;
  63743. }
  63744. for (var name in this._textures) {
  63745. var texture = this._textures[name];
  63746. if (!texture.isReady()) {
  63747. return false;
  63748. }
  63749. }
  63750. return true;
  63751. };
  63752. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63753. var scene = this.getScene();
  63754. if (this._animate && scene) {
  63755. this._time += scene.getAnimationRatio() * 0.03;
  63756. this.updateShaderUniforms();
  63757. }
  63758. _super.prototype.render.call(this, useCameraPostProcess);
  63759. };
  63760. CustomProceduralTexture.prototype.updateTextures = function () {
  63761. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63762. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63763. }
  63764. };
  63765. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63766. if (this._config) {
  63767. for (var j = 0; j < this._config.uniforms.length; j++) {
  63768. var uniform = this._config.uniforms[j];
  63769. switch (uniform.type) {
  63770. case "float":
  63771. this.setFloat(uniform.name, uniform.value);
  63772. break;
  63773. case "color3":
  63774. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63775. break;
  63776. case "color4":
  63777. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63778. break;
  63779. case "vector2":
  63780. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63781. break;
  63782. case "vector3":
  63783. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63784. break;
  63785. }
  63786. }
  63787. }
  63788. this.setFloat("time", this._time);
  63789. };
  63790. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63791. get: function () {
  63792. return this._animate;
  63793. },
  63794. set: function (value) {
  63795. this._animate = value;
  63796. },
  63797. enumerable: true,
  63798. configurable: true
  63799. });
  63800. return CustomProceduralTexture;
  63801. }(BABYLON.ProceduralTexture));
  63802. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63803. })(BABYLON || (BABYLON = {}));
  63804. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63805. var BABYLON;
  63806. (function (BABYLON) {
  63807. var FreeCameraGamepadInput = /** @class */ (function () {
  63808. function FreeCameraGamepadInput() {
  63809. this.gamepadAngularSensibility = 200;
  63810. this.gamepadMoveSensibility = 40;
  63811. // private members
  63812. this._cameraTransform = BABYLON.Matrix.Identity();
  63813. this._deltaTransform = BABYLON.Vector3.Zero();
  63814. this._vector3 = BABYLON.Vector3.Zero();
  63815. this._vector2 = BABYLON.Vector2.Zero();
  63816. }
  63817. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63818. var _this = this;
  63819. var manager = this.camera.getScene().gamepadManager;
  63820. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63821. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63822. // prioritize XBOX gamepads.
  63823. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63824. _this.gamepad = gamepad;
  63825. }
  63826. }
  63827. });
  63828. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63829. if (_this.gamepad === gamepad) {
  63830. _this.gamepad = null;
  63831. }
  63832. });
  63833. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63834. };
  63835. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63836. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63837. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63838. this.gamepad = null;
  63839. };
  63840. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63841. if (this.gamepad && this.gamepad.leftStick) {
  63842. var camera = this.camera;
  63843. var LSValues = this.gamepad.leftStick;
  63844. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63845. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63846. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63847. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63848. var RSValues = this.gamepad.rightStick;
  63849. if (RSValues) {
  63850. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63851. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63852. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63853. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63854. }
  63855. else {
  63856. RSValues = { x: 0, y: 0 };
  63857. }
  63858. if (!camera.rotationQuaternion) {
  63859. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63860. }
  63861. else {
  63862. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63863. }
  63864. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63865. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63866. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63867. camera.cameraDirection.addInPlace(this._deltaTransform);
  63868. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63869. camera.cameraRotation.addInPlace(this._vector2);
  63870. }
  63871. };
  63872. FreeCameraGamepadInput.prototype.getClassName = function () {
  63873. return "FreeCameraGamepadInput";
  63874. };
  63875. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63876. return "gamepad";
  63877. };
  63878. __decorate([
  63879. BABYLON.serialize()
  63880. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63881. __decorate([
  63882. BABYLON.serialize()
  63883. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63884. return FreeCameraGamepadInput;
  63885. }());
  63886. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63887. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63888. })(BABYLON || (BABYLON = {}));
  63889. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63890. var BABYLON;
  63891. (function (BABYLON) {
  63892. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63893. function ArcRotateCameraGamepadInput() {
  63894. this.gamepadRotationSensibility = 80;
  63895. this.gamepadMoveSensibility = 40;
  63896. }
  63897. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63898. var _this = this;
  63899. var manager = this.camera.getScene().gamepadManager;
  63900. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63901. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63902. // prioritize XBOX gamepads.
  63903. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63904. _this.gamepad = gamepad;
  63905. }
  63906. }
  63907. });
  63908. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63909. if (_this.gamepad === gamepad) {
  63910. _this.gamepad = null;
  63911. }
  63912. });
  63913. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63914. };
  63915. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63916. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63917. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63918. this.gamepad = null;
  63919. };
  63920. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63921. if (this.gamepad) {
  63922. var camera = this.camera;
  63923. var RSValues = this.gamepad.rightStick;
  63924. if (RSValues) {
  63925. if (RSValues.x != 0) {
  63926. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63927. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63928. camera.inertialAlphaOffset += normalizedRX;
  63929. }
  63930. }
  63931. if (RSValues.y != 0) {
  63932. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63933. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63934. camera.inertialBetaOffset += normalizedRY;
  63935. }
  63936. }
  63937. }
  63938. var LSValues = this.gamepad.leftStick;
  63939. if (LSValues && LSValues.y != 0) {
  63940. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63941. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63942. this.camera.inertialRadiusOffset -= normalizedLY;
  63943. }
  63944. }
  63945. }
  63946. };
  63947. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63948. return "ArcRotateCameraGamepadInput";
  63949. };
  63950. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63951. return "gamepad";
  63952. };
  63953. __decorate([
  63954. BABYLON.serialize()
  63955. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63956. __decorate([
  63957. BABYLON.serialize()
  63958. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63959. return ArcRotateCameraGamepadInput;
  63960. }());
  63961. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63962. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63963. })(BABYLON || (BABYLON = {}));
  63964. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63965. var BABYLON;
  63966. (function (BABYLON) {
  63967. var GamepadManager = /** @class */ (function () {
  63968. function GamepadManager(_scene) {
  63969. var _this = this;
  63970. this._scene = _scene;
  63971. this._babylonGamepads = [];
  63972. this._oneGamepadConnected = false;
  63973. this._isMonitoring = false;
  63974. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63975. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63976. this._gamepadEventSupported = false;
  63977. }
  63978. else {
  63979. this._gamepadEventSupported = 'GamepadEvent' in window;
  63980. this._gamepadSupport = (navigator.getGamepads ||
  63981. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63982. }
  63983. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63984. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63985. for (var i in _this._babylonGamepads) {
  63986. var gamepad = _this._babylonGamepads[i];
  63987. if (gamepad && gamepad._isConnected) {
  63988. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63989. }
  63990. }
  63991. });
  63992. this._onGamepadConnectedEvent = function (evt) {
  63993. var gamepad = evt.gamepad;
  63994. if (gamepad.index in _this._babylonGamepads) {
  63995. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63996. return;
  63997. }
  63998. }
  63999. var newGamepad;
  64000. if (_this._babylonGamepads[gamepad.index]) {
  64001. newGamepad = _this._babylonGamepads[gamepad.index];
  64002. newGamepad.browserGamepad = gamepad;
  64003. newGamepad._isConnected = true;
  64004. }
  64005. else {
  64006. newGamepad = _this._addNewGamepad(gamepad);
  64007. }
  64008. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64009. _this._startMonitoringGamepads();
  64010. };
  64011. this._onGamepadDisconnectedEvent = function (evt) {
  64012. var gamepad = evt.gamepad;
  64013. // Remove the gamepad from the list of gamepads to monitor.
  64014. for (var i in _this._babylonGamepads) {
  64015. if (_this._babylonGamepads[i].index === gamepad.index) {
  64016. var disconnectedGamepad = _this._babylonGamepads[i];
  64017. disconnectedGamepad._isConnected = false;
  64018. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64019. break;
  64020. }
  64021. }
  64022. };
  64023. if (this._gamepadSupport) {
  64024. //first add already-connected gamepads
  64025. this._updateGamepadObjects();
  64026. if (this._babylonGamepads.length) {
  64027. this._startMonitoringGamepads();
  64028. }
  64029. // Checking if the gamepad connected event is supported (like in Firefox)
  64030. if (this._gamepadEventSupported) {
  64031. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64032. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64033. }
  64034. else {
  64035. this._startMonitoringGamepads();
  64036. }
  64037. }
  64038. }
  64039. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64040. get: function () {
  64041. return this._babylonGamepads;
  64042. },
  64043. enumerable: true,
  64044. configurable: true
  64045. });
  64046. GamepadManager.prototype.getGamepadByType = function (type) {
  64047. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64048. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64049. var gamepad = _a[_i];
  64050. if (gamepad && gamepad.type === type) {
  64051. return gamepad;
  64052. }
  64053. }
  64054. return null;
  64055. };
  64056. GamepadManager.prototype.dispose = function () {
  64057. if (this._gamepadEventSupported) {
  64058. if (this._onGamepadConnectedEvent) {
  64059. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64060. }
  64061. if (this._onGamepadDisconnectedEvent) {
  64062. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64063. }
  64064. this._onGamepadConnectedEvent = null;
  64065. this._onGamepadDisconnectedEvent = null;
  64066. }
  64067. this._babylonGamepads.forEach(function (gamepad) {
  64068. gamepad.dispose();
  64069. });
  64070. this.onGamepadConnectedObservable.clear();
  64071. this.onGamepadDisconnectedObservable.clear();
  64072. this._oneGamepadConnected = false;
  64073. this._stopMonitoringGamepads();
  64074. this._babylonGamepads = [];
  64075. };
  64076. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64077. if (!this._oneGamepadConnected) {
  64078. this._oneGamepadConnected = true;
  64079. }
  64080. var newGamepad;
  64081. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64082. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64083. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64084. }
  64085. else if (gamepad.pose) {
  64086. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64087. }
  64088. else {
  64089. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64090. }
  64091. this._babylonGamepads[newGamepad.index] = newGamepad;
  64092. return newGamepad;
  64093. };
  64094. GamepadManager.prototype._startMonitoringGamepads = function () {
  64095. if (!this._isMonitoring) {
  64096. this._isMonitoring = true;
  64097. //back-comp
  64098. if (!this._scene) {
  64099. this._checkGamepadsStatus();
  64100. }
  64101. }
  64102. };
  64103. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64104. this._isMonitoring = false;
  64105. };
  64106. GamepadManager.prototype._checkGamepadsStatus = function () {
  64107. var _this = this;
  64108. // Hack to be compatible Chrome
  64109. this._updateGamepadObjects();
  64110. for (var i in this._babylonGamepads) {
  64111. var gamepad = this._babylonGamepads[i];
  64112. if (!gamepad || !gamepad.isConnected) {
  64113. continue;
  64114. }
  64115. gamepad.update();
  64116. }
  64117. if (this._isMonitoring && !this._scene) {
  64118. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64119. }
  64120. };
  64121. // This function is called only on Chrome, which does not properly support
  64122. // connection/disconnection events and forces you to recopy again the gamepad object
  64123. GamepadManager.prototype._updateGamepadObjects = function () {
  64124. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64125. for (var i = 0; i < gamepads.length; i++) {
  64126. if (gamepads[i]) {
  64127. if (!this._babylonGamepads[gamepads[i].index]) {
  64128. var newGamepad = this._addNewGamepad(gamepads[i]);
  64129. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64130. }
  64131. else {
  64132. // Forced to copy again this object for Chrome for unknown reason
  64133. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64134. if (!this._babylonGamepads[i].isConnected) {
  64135. this._babylonGamepads[i]._isConnected = true;
  64136. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64137. }
  64138. }
  64139. }
  64140. }
  64141. };
  64142. return GamepadManager;
  64143. }());
  64144. BABYLON.GamepadManager = GamepadManager;
  64145. })(BABYLON || (BABYLON = {}));
  64146. //# sourceMappingURL=babylon.gamepadManager.js.map
  64147. var BABYLON;
  64148. (function (BABYLON) {
  64149. var StickValues = /** @class */ (function () {
  64150. function StickValues(x, y) {
  64151. this.x = x;
  64152. this.y = y;
  64153. }
  64154. return StickValues;
  64155. }());
  64156. BABYLON.StickValues = StickValues;
  64157. var Gamepad = /** @class */ (function () {
  64158. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64159. if (leftStickX === void 0) { leftStickX = 0; }
  64160. if (leftStickY === void 0) { leftStickY = 1; }
  64161. if (rightStickX === void 0) { rightStickX = 2; }
  64162. if (rightStickY === void 0) { rightStickY = 3; }
  64163. this.id = id;
  64164. this.index = index;
  64165. this.browserGamepad = browserGamepad;
  64166. this._isConnected = true;
  64167. this._invertLeftStickY = false;
  64168. this.type = Gamepad.GAMEPAD;
  64169. this._leftStickAxisX = leftStickX;
  64170. this._leftStickAxisY = leftStickY;
  64171. this._rightStickAxisX = rightStickX;
  64172. this._rightStickAxisY = rightStickY;
  64173. if (this.browserGamepad.axes.length >= 2) {
  64174. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64175. }
  64176. if (this.browserGamepad.axes.length >= 4) {
  64177. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64178. }
  64179. }
  64180. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64181. get: function () {
  64182. return this._isConnected;
  64183. },
  64184. enumerable: true,
  64185. configurable: true
  64186. });
  64187. Gamepad.prototype.onleftstickchanged = function (callback) {
  64188. this._onleftstickchanged = callback;
  64189. };
  64190. Gamepad.prototype.onrightstickchanged = function (callback) {
  64191. this._onrightstickchanged = callback;
  64192. };
  64193. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64194. get: function () {
  64195. return this._leftStick;
  64196. },
  64197. set: function (newValues) {
  64198. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64199. this._onleftstickchanged(newValues);
  64200. }
  64201. this._leftStick = newValues;
  64202. },
  64203. enumerable: true,
  64204. configurable: true
  64205. });
  64206. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64207. get: function () {
  64208. return this._rightStick;
  64209. },
  64210. set: function (newValues) {
  64211. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64212. this._onrightstickchanged(newValues);
  64213. }
  64214. this._rightStick = newValues;
  64215. },
  64216. enumerable: true,
  64217. configurable: true
  64218. });
  64219. Gamepad.prototype.update = function () {
  64220. if (this._leftStick) {
  64221. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64222. if (this._invertLeftStickY) {
  64223. this.leftStick.y *= -1;
  64224. }
  64225. }
  64226. if (this._rightStick) {
  64227. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64228. }
  64229. };
  64230. Gamepad.prototype.dispose = function () {
  64231. };
  64232. Gamepad.GAMEPAD = 0;
  64233. Gamepad.GENERIC = 1;
  64234. Gamepad.XBOX = 2;
  64235. Gamepad.POSE_ENABLED = 3;
  64236. return Gamepad;
  64237. }());
  64238. BABYLON.Gamepad = Gamepad;
  64239. var GenericPad = /** @class */ (function (_super) {
  64240. __extends(GenericPad, _super);
  64241. function GenericPad(id, index, browserGamepad) {
  64242. var _this = _super.call(this, id, index, browserGamepad) || this;
  64243. _this.onButtonDownObservable = new BABYLON.Observable();
  64244. _this.onButtonUpObservable = new BABYLON.Observable();
  64245. _this.type = Gamepad.GENERIC;
  64246. _this._buttons = new Array(browserGamepad.buttons.length);
  64247. return _this;
  64248. }
  64249. GenericPad.prototype.onbuttondown = function (callback) {
  64250. this._onbuttondown = callback;
  64251. };
  64252. GenericPad.prototype.onbuttonup = function (callback) {
  64253. this._onbuttonup = callback;
  64254. };
  64255. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64256. if (newValue !== currentValue) {
  64257. if (newValue === 1) {
  64258. if (this._onbuttondown) {
  64259. this._onbuttondown(buttonIndex);
  64260. }
  64261. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64262. }
  64263. if (newValue === 0) {
  64264. if (this._onbuttonup) {
  64265. this._onbuttonup(buttonIndex);
  64266. }
  64267. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64268. }
  64269. }
  64270. return newValue;
  64271. };
  64272. GenericPad.prototype.update = function () {
  64273. _super.prototype.update.call(this);
  64274. for (var index = 0; index < this._buttons.length; index++) {
  64275. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64276. }
  64277. };
  64278. GenericPad.prototype.dispose = function () {
  64279. _super.prototype.dispose.call(this);
  64280. this.onButtonDownObservable.clear();
  64281. this.onButtonUpObservable.clear();
  64282. };
  64283. return GenericPad;
  64284. }(Gamepad));
  64285. BABYLON.GenericPad = GenericPad;
  64286. })(BABYLON || (BABYLON = {}));
  64287. //# sourceMappingURL=babylon.gamepad.js.map
  64288. var BABYLON;
  64289. (function (BABYLON) {
  64290. var Xbox360Button;
  64291. (function (Xbox360Button) {
  64292. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64293. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64294. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64295. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64296. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64297. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64298. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64299. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64300. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64301. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64302. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64303. var Xbox360Dpad;
  64304. (function (Xbox360Dpad) {
  64305. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64306. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64307. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64308. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64309. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64310. var Xbox360Pad = /** @class */ (function (_super) {
  64311. __extends(Xbox360Pad, _super);
  64312. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64313. if (xboxOne === void 0) { xboxOne = false; }
  64314. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64315. _this._leftTrigger = 0;
  64316. _this._rightTrigger = 0;
  64317. _this.onButtonDownObservable = new BABYLON.Observable();
  64318. _this.onButtonUpObservable = new BABYLON.Observable();
  64319. _this.onPadDownObservable = new BABYLON.Observable();
  64320. _this.onPadUpObservable = new BABYLON.Observable();
  64321. _this._buttonA = 0;
  64322. _this._buttonB = 0;
  64323. _this._buttonX = 0;
  64324. _this._buttonY = 0;
  64325. _this._buttonBack = 0;
  64326. _this._buttonStart = 0;
  64327. _this._buttonLB = 0;
  64328. _this._buttonRB = 0;
  64329. _this._buttonLeftStick = 0;
  64330. _this._buttonRightStick = 0;
  64331. _this._dPadUp = 0;
  64332. _this._dPadDown = 0;
  64333. _this._dPadLeft = 0;
  64334. _this._dPadRight = 0;
  64335. _this._isXboxOnePad = false;
  64336. _this.type = BABYLON.Gamepad.XBOX;
  64337. _this._isXboxOnePad = xboxOne;
  64338. return _this;
  64339. }
  64340. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64341. this._onlefttriggerchanged = callback;
  64342. };
  64343. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64344. this._onrighttriggerchanged = callback;
  64345. };
  64346. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64347. get: function () {
  64348. return this._leftTrigger;
  64349. },
  64350. set: function (newValue) {
  64351. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64352. this._onlefttriggerchanged(newValue);
  64353. }
  64354. this._leftTrigger = newValue;
  64355. },
  64356. enumerable: true,
  64357. configurable: true
  64358. });
  64359. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64360. get: function () {
  64361. return this._rightTrigger;
  64362. },
  64363. set: function (newValue) {
  64364. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64365. this._onrighttriggerchanged(newValue);
  64366. }
  64367. this._rightTrigger = newValue;
  64368. },
  64369. enumerable: true,
  64370. configurable: true
  64371. });
  64372. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64373. this._onbuttondown = callback;
  64374. };
  64375. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64376. this._onbuttonup = callback;
  64377. };
  64378. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64379. this._ondpaddown = callback;
  64380. };
  64381. Xbox360Pad.prototype.ondpadup = function (callback) {
  64382. this._ondpadup = callback;
  64383. };
  64384. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64385. if (newValue !== currentValue) {
  64386. if (newValue === 1) {
  64387. if (this._onbuttondown) {
  64388. this._onbuttondown(buttonType);
  64389. }
  64390. this.onButtonDownObservable.notifyObservers(buttonType);
  64391. }
  64392. if (newValue === 0) {
  64393. if (this._onbuttonup) {
  64394. this._onbuttonup(buttonType);
  64395. }
  64396. this.onButtonUpObservable.notifyObservers(buttonType);
  64397. }
  64398. }
  64399. return newValue;
  64400. };
  64401. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64402. if (newValue !== currentValue) {
  64403. if (newValue === 1) {
  64404. if (this._ondpaddown) {
  64405. this._ondpaddown(buttonType);
  64406. }
  64407. this.onPadDownObservable.notifyObservers(buttonType);
  64408. }
  64409. if (newValue === 0) {
  64410. if (this._ondpadup) {
  64411. this._ondpadup(buttonType);
  64412. }
  64413. this.onPadUpObservable.notifyObservers(buttonType);
  64414. }
  64415. }
  64416. return newValue;
  64417. };
  64418. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64419. get: function () {
  64420. return this._buttonA;
  64421. },
  64422. set: function (value) {
  64423. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64424. },
  64425. enumerable: true,
  64426. configurable: true
  64427. });
  64428. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64429. get: function () {
  64430. return this._buttonB;
  64431. },
  64432. set: function (value) {
  64433. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64439. get: function () {
  64440. return this._buttonX;
  64441. },
  64442. set: function (value) {
  64443. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64444. },
  64445. enumerable: true,
  64446. configurable: true
  64447. });
  64448. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64449. get: function () {
  64450. return this._buttonY;
  64451. },
  64452. set: function (value) {
  64453. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64454. },
  64455. enumerable: true,
  64456. configurable: true
  64457. });
  64458. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64459. get: function () {
  64460. return this._buttonStart;
  64461. },
  64462. set: function (value) {
  64463. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64464. },
  64465. enumerable: true,
  64466. configurable: true
  64467. });
  64468. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64469. get: function () {
  64470. return this._buttonBack;
  64471. },
  64472. set: function (value) {
  64473. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64479. get: function () {
  64480. return this._buttonLB;
  64481. },
  64482. set: function (value) {
  64483. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64484. },
  64485. enumerable: true,
  64486. configurable: true
  64487. });
  64488. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64489. get: function () {
  64490. return this._buttonRB;
  64491. },
  64492. set: function (value) {
  64493. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64494. },
  64495. enumerable: true,
  64496. configurable: true
  64497. });
  64498. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64499. get: function () {
  64500. return this._buttonLeftStick;
  64501. },
  64502. set: function (value) {
  64503. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64504. },
  64505. enumerable: true,
  64506. configurable: true
  64507. });
  64508. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64509. get: function () {
  64510. return this._buttonRightStick;
  64511. },
  64512. set: function (value) {
  64513. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64514. },
  64515. enumerable: true,
  64516. configurable: true
  64517. });
  64518. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64519. get: function () {
  64520. return this._dPadUp;
  64521. },
  64522. set: function (value) {
  64523. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64524. },
  64525. enumerable: true,
  64526. configurable: true
  64527. });
  64528. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64529. get: function () {
  64530. return this._dPadDown;
  64531. },
  64532. set: function (value) {
  64533. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64534. },
  64535. enumerable: true,
  64536. configurable: true
  64537. });
  64538. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64539. get: function () {
  64540. return this._dPadLeft;
  64541. },
  64542. set: function (value) {
  64543. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64544. },
  64545. enumerable: true,
  64546. configurable: true
  64547. });
  64548. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64549. get: function () {
  64550. return this._dPadRight;
  64551. },
  64552. set: function (value) {
  64553. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64554. },
  64555. enumerable: true,
  64556. configurable: true
  64557. });
  64558. Xbox360Pad.prototype.update = function () {
  64559. _super.prototype.update.call(this);
  64560. if (this._isXboxOnePad) {
  64561. this.buttonA = this.browserGamepad.buttons[0].value;
  64562. this.buttonB = this.browserGamepad.buttons[1].value;
  64563. this.buttonX = this.browserGamepad.buttons[2].value;
  64564. this.buttonY = this.browserGamepad.buttons[3].value;
  64565. this.buttonLB = this.browserGamepad.buttons[4].value;
  64566. this.buttonRB = this.browserGamepad.buttons[5].value;
  64567. this.leftTrigger = this.browserGamepad.axes[2];
  64568. this.rightTrigger = this.browserGamepad.axes[5];
  64569. this.buttonBack = this.browserGamepad.buttons[9].value;
  64570. this.buttonStart = this.browserGamepad.buttons[8].value;
  64571. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64572. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64573. this.dPadUp = this.browserGamepad.buttons[11].value;
  64574. this.dPadDown = this.browserGamepad.buttons[12].value;
  64575. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64576. this.dPadRight = this.browserGamepad.buttons[14].value;
  64577. }
  64578. else {
  64579. this.buttonA = this.browserGamepad.buttons[0].value;
  64580. this.buttonB = this.browserGamepad.buttons[1].value;
  64581. this.buttonX = this.browserGamepad.buttons[2].value;
  64582. this.buttonY = this.browserGamepad.buttons[3].value;
  64583. this.buttonLB = this.browserGamepad.buttons[4].value;
  64584. this.buttonRB = this.browserGamepad.buttons[5].value;
  64585. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64586. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64587. this.buttonBack = this.browserGamepad.buttons[8].value;
  64588. this.buttonStart = this.browserGamepad.buttons[9].value;
  64589. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64590. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64591. this.dPadUp = this.browserGamepad.buttons[12].value;
  64592. this.dPadDown = this.browserGamepad.buttons[13].value;
  64593. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64594. this.dPadRight = this.browserGamepad.buttons[15].value;
  64595. }
  64596. };
  64597. Xbox360Pad.prototype.dispose = function () {
  64598. _super.prototype.dispose.call(this);
  64599. this.onButtonDownObservable.clear();
  64600. this.onButtonUpObservable.clear();
  64601. this.onPadDownObservable.clear();
  64602. this.onPadUpObservable.clear();
  64603. };
  64604. return Xbox360Pad;
  64605. }(BABYLON.Gamepad));
  64606. BABYLON.Xbox360Pad = Xbox360Pad;
  64607. })(BABYLON || (BABYLON = {}));
  64608. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64609. var BABYLON;
  64610. (function (BABYLON) {
  64611. var PoseEnabledControllerType;
  64612. (function (PoseEnabledControllerType) {
  64613. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64614. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64615. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64616. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64617. /**
  64618. * Google Daydream
  64619. */
  64620. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64621. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64622. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64623. var PoseEnabledControllerHelper = /** @class */ (function () {
  64624. function PoseEnabledControllerHelper() {
  64625. }
  64626. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64627. // Oculus Touch
  64628. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64629. return new BABYLON.OculusTouchController(vrGamepad);
  64630. }
  64631. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64632. return new BABYLON.WindowsMotionController(vrGamepad);
  64633. }
  64634. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64635. return new BABYLON.ViveController(vrGamepad);
  64636. }
  64637. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64638. return new BABYLON.GearVRController(vrGamepad);
  64639. }
  64640. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64641. return new BABYLON.DaydreamController(vrGamepad);
  64642. }
  64643. else {
  64644. return new BABYLON.GenericController(vrGamepad);
  64645. }
  64646. };
  64647. return PoseEnabledControllerHelper;
  64648. }());
  64649. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64650. var PoseEnabledController = /** @class */ (function (_super) {
  64651. __extends(PoseEnabledController, _super);
  64652. function PoseEnabledController(browserGamepad) {
  64653. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64654. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64655. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64656. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64657. // Represents device position and rotation in babylon space
  64658. _this.devicePosition = BABYLON.Vector3.Zero();
  64659. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64660. _this.deviceScaleFactor = 1;
  64661. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64662. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64663. /**
  64664. * Node to be used when casting a ray from the controller
  64665. */
  64666. _this._pointingPoseNode = null;
  64667. _this._workingMatrix = BABYLON.Matrix.Identity();
  64668. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64669. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64670. _this.position = BABYLON.Vector3.Zero();
  64671. _this.rotationQuaternion = new BABYLON.Quaternion();
  64672. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64673. _this._calculatedRotation = new BABYLON.Quaternion();
  64674. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64675. return _this;
  64676. }
  64677. PoseEnabledController.prototype.update = function () {
  64678. _super.prototype.update.call(this);
  64679. var pose = this.browserGamepad.pose;
  64680. this.updateFromDevice(pose);
  64681. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64682. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64683. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64684. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64685. if (this._mesh) {
  64686. this._mesh.position.copyFrom(this.devicePosition);
  64687. if (this._mesh.rotationQuaternion) {
  64688. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64689. }
  64690. }
  64691. };
  64692. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64693. if (poseData) {
  64694. this.rawPose = poseData;
  64695. if (poseData.position) {
  64696. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64697. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64698. this._deviceRoomPosition.z *= -1;
  64699. }
  64700. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64701. this._calculatedPosition.addInPlace(this.position);
  64702. }
  64703. var pose = this.rawPose;
  64704. if (poseData.orientation && pose.orientation) {
  64705. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64706. if (this._mesh) {
  64707. if (this._mesh.getScene().useRightHandedSystem) {
  64708. this._deviceRoomRotationQuaternion.z *= -1;
  64709. this._deviceRoomRotationQuaternion.w *= -1;
  64710. }
  64711. else {
  64712. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64713. }
  64714. }
  64715. // if the camera is set, rotate to the camera's rotation
  64716. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64717. }
  64718. }
  64719. };
  64720. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64721. if (this._mesh) {
  64722. this._mesh.parent = null;
  64723. }
  64724. this._mesh = mesh;
  64725. if (this._poseControlledCamera) {
  64726. this._mesh.parent = this._poseControlledCamera;
  64727. }
  64728. if (!this._mesh.rotationQuaternion) {
  64729. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64730. }
  64731. };
  64732. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64733. this._poseControlledCamera = camera;
  64734. if (this._mesh) {
  64735. this._mesh.parent = this._poseControlledCamera;
  64736. }
  64737. };
  64738. PoseEnabledController.prototype.dispose = function () {
  64739. if (this._mesh) {
  64740. this._mesh.dispose();
  64741. }
  64742. this._mesh = null;
  64743. _super.prototype.dispose.call(this);
  64744. };
  64745. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64746. get: function () {
  64747. return this._mesh;
  64748. },
  64749. enumerable: true,
  64750. configurable: true
  64751. });
  64752. PoseEnabledController.prototype.getForwardRay = function (length) {
  64753. if (length === void 0) { length = 100; }
  64754. if (!this.mesh) {
  64755. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64756. }
  64757. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64758. var origin = m.getTranslation();
  64759. var forward = new BABYLON.Vector3(0, 0, -1);
  64760. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64761. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64762. return new BABYLON.Ray(origin, direction, length);
  64763. };
  64764. /**
  64765. * Name of the child mesh that can be used to cast a ray from the controller
  64766. */
  64767. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64768. return PoseEnabledController;
  64769. }(BABYLON.Gamepad));
  64770. BABYLON.PoseEnabledController = PoseEnabledController;
  64771. })(BABYLON || (BABYLON = {}));
  64772. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64773. var BABYLON;
  64774. (function (BABYLON) {
  64775. var WebVRController = /** @class */ (function (_super) {
  64776. __extends(WebVRController, _super);
  64777. function WebVRController(vrGamepad) {
  64778. var _this = _super.call(this, vrGamepad) || this;
  64779. // Observables
  64780. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64781. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64782. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64783. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64784. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64785. _this.pad = { x: 0, y: 0 };
  64786. // avoid GC, store state in a tmp object
  64787. _this._changes = {
  64788. pressChanged: false,
  64789. touchChanged: false,
  64790. valueChanged: false,
  64791. changed: false
  64792. };
  64793. _this._buttons = new Array(vrGamepad.buttons.length);
  64794. _this.hand = vrGamepad.hand;
  64795. return _this;
  64796. }
  64797. WebVRController.prototype.onButtonStateChange = function (callback) {
  64798. this._onButtonStateChange = callback;
  64799. };
  64800. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64801. get: function () {
  64802. return this._defaultModel;
  64803. },
  64804. enumerable: true,
  64805. configurable: true
  64806. });
  64807. WebVRController.prototype.update = function () {
  64808. _super.prototype.update.call(this);
  64809. for (var index = 0; index < this._buttons.length; index++) {
  64810. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64811. }
  64812. ;
  64813. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64814. this.pad.x = this.leftStick.x;
  64815. this.pad.y = this.leftStick.y;
  64816. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64817. }
  64818. };
  64819. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64820. if (!newState) {
  64821. newState = {
  64822. pressed: false,
  64823. touched: false,
  64824. value: 0
  64825. };
  64826. }
  64827. if (!currentState) {
  64828. this._buttons[buttonIndex] = {
  64829. pressed: newState.pressed,
  64830. touched: newState.touched,
  64831. value: newState.value
  64832. };
  64833. return;
  64834. }
  64835. this._checkChanges(newState, currentState);
  64836. if (this._changes.changed) {
  64837. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64838. this._handleButtonChange(buttonIndex, newState, this._changes);
  64839. }
  64840. this._buttons[buttonIndex].pressed = newState.pressed;
  64841. this._buttons[buttonIndex].touched = newState.touched;
  64842. // oculus triggers are never 0, thou not touched.
  64843. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64844. };
  64845. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64846. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64847. this._changes.touchChanged = newState.touched !== currentState.touched;
  64848. this._changes.valueChanged = newState.value !== currentState.value;
  64849. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64850. return this._changes;
  64851. };
  64852. WebVRController.prototype.dispose = function () {
  64853. _super.prototype.dispose.call(this);
  64854. this.onTriggerStateChangedObservable.clear();
  64855. this.onMainButtonStateChangedObservable.clear();
  64856. this.onSecondaryButtonStateChangedObservable.clear();
  64857. this.onPadStateChangedObservable.clear();
  64858. this.onPadValuesChangedObservable.clear();
  64859. };
  64860. return WebVRController;
  64861. }(BABYLON.PoseEnabledController));
  64862. BABYLON.WebVRController = WebVRController;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.webVRController.js.map
  64865. var BABYLON;
  64866. (function (BABYLON) {
  64867. var OculusTouchController = /** @class */ (function (_super) {
  64868. __extends(OculusTouchController, _super);
  64869. function OculusTouchController(vrGamepad) {
  64870. var _this = _super.call(this, vrGamepad) || this;
  64871. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64872. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64873. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64874. return _this;
  64875. }
  64876. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64877. var _this = this;
  64878. var meshName;
  64879. // Hand
  64880. if (this.hand === 'left') {
  64881. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64882. }
  64883. else {
  64884. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64885. }
  64886. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64887. /*
  64888. Parent Mesh name: oculus_touch_left
  64889. - body
  64890. - trigger
  64891. - thumbstick
  64892. - grip
  64893. - button_y
  64894. - button_x
  64895. - button_enter
  64896. */
  64897. _this._defaultModel = newMeshes[1];
  64898. _this.attachToMesh(_this._defaultModel);
  64899. if (meshLoaded) {
  64900. meshLoaded(_this._defaultModel);
  64901. }
  64902. });
  64903. };
  64904. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64905. // helper getters for left and right hand.
  64906. get: function () {
  64907. if (this.hand === 'right') {
  64908. return this.onMainButtonStateChangedObservable;
  64909. }
  64910. else {
  64911. throw new Error('No A button on left hand');
  64912. }
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64918. get: function () {
  64919. if (this.hand === 'right') {
  64920. return this.onSecondaryButtonStateChangedObservable;
  64921. }
  64922. else {
  64923. throw new Error('No B button on left hand');
  64924. }
  64925. },
  64926. enumerable: true,
  64927. configurable: true
  64928. });
  64929. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64930. get: function () {
  64931. if (this.hand === 'left') {
  64932. return this.onMainButtonStateChangedObservable;
  64933. }
  64934. else {
  64935. throw new Error('No X button on right hand');
  64936. }
  64937. },
  64938. enumerable: true,
  64939. configurable: true
  64940. });
  64941. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64942. get: function () {
  64943. if (this.hand === 'left') {
  64944. return this.onSecondaryButtonStateChangedObservable;
  64945. }
  64946. else {
  64947. throw new Error('No Y button on right hand');
  64948. }
  64949. },
  64950. enumerable: true,
  64951. configurable: true
  64952. });
  64953. /*
  64954. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64955. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64956. 2) secondary trigger (same)
  64957. 3) A (right) X (left), touch, pressed = value
  64958. 4) B / Y
  64959. 5) thumb rest
  64960. */
  64961. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64962. var notifyObject = state; //{ state: state, changes: changes };
  64963. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64964. switch (buttonIdx) {
  64965. case 0:
  64966. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64967. return;
  64968. case 1:// index trigger
  64969. if (this._defaultModel) {
  64970. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64971. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64972. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64973. }
  64974. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64975. return;
  64976. case 2:// secondary trigger
  64977. if (this._defaultModel) {
  64978. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64979. }
  64980. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64981. return;
  64982. case 3:
  64983. if (this._defaultModel) {
  64984. if (notifyObject.pressed) {
  64985. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64986. }
  64987. else {
  64988. (this._defaultModel.getChildren()[1]).position.y = 0;
  64989. }
  64990. }
  64991. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64992. return;
  64993. case 4:
  64994. if (this._defaultModel) {
  64995. if (notifyObject.pressed) {
  64996. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64997. }
  64998. else {
  64999. (this._defaultModel.getChildren()[2]).position.y = 0;
  65000. }
  65001. }
  65002. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65003. return;
  65004. case 5:
  65005. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65006. return;
  65007. }
  65008. };
  65009. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65010. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65011. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65012. return OculusTouchController;
  65013. }(BABYLON.WebVRController));
  65014. BABYLON.OculusTouchController = OculusTouchController;
  65015. })(BABYLON || (BABYLON = {}));
  65016. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65017. var BABYLON;
  65018. (function (BABYLON) {
  65019. var ViveController = /** @class */ (function (_super) {
  65020. __extends(ViveController, _super);
  65021. function ViveController(vrGamepad) {
  65022. var _this = _super.call(this, vrGamepad) || this;
  65023. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65024. _this._invertLeftStickY = true;
  65025. return _this;
  65026. }
  65027. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65028. var _this = this;
  65029. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65030. /*
  65031. Parent Mesh name: ViveWand
  65032. - body
  65033. - r_gripper
  65034. - l_gripper
  65035. - menu_button
  65036. - system_button
  65037. - trackpad
  65038. - trigger
  65039. - LED
  65040. */
  65041. _this._defaultModel = newMeshes[1];
  65042. _this.attachToMesh(_this._defaultModel);
  65043. if (meshLoaded) {
  65044. meshLoaded(_this._defaultModel);
  65045. }
  65046. });
  65047. };
  65048. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65049. get: function () {
  65050. return this.onMainButtonStateChangedObservable;
  65051. },
  65052. enumerable: true,
  65053. configurable: true
  65054. });
  65055. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65056. get: function () {
  65057. return this.onMainButtonStateChangedObservable;
  65058. },
  65059. enumerable: true,
  65060. configurable: true
  65061. });
  65062. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65063. get: function () {
  65064. return this.onSecondaryButtonStateChangedObservable;
  65065. },
  65066. enumerable: true,
  65067. configurable: true
  65068. });
  65069. /**
  65070. * Vive mapping:
  65071. * 0: touchpad
  65072. * 1: trigger
  65073. * 2: left AND right buttons
  65074. * 3: menu button
  65075. */
  65076. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65077. var notifyObject = state; //{ state: state, changes: changes };
  65078. switch (buttonIdx) {
  65079. case 0:
  65080. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65081. return;
  65082. case 1:// index trigger
  65083. if (this._defaultModel) {
  65084. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65085. }
  65086. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65087. return;
  65088. case 2:// left AND right button
  65089. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65090. return;
  65091. case 3:
  65092. if (this._defaultModel) {
  65093. if (notifyObject.pressed) {
  65094. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65095. }
  65096. else {
  65097. (this._defaultModel.getChildren()[2]).position.y = 0;
  65098. }
  65099. }
  65100. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65101. return;
  65102. }
  65103. };
  65104. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65105. ViveController.MODEL_FILENAME = 'wand.babylon';
  65106. return ViveController;
  65107. }(BABYLON.WebVRController));
  65108. BABYLON.ViveController = ViveController;
  65109. })(BABYLON || (BABYLON = {}));
  65110. //# sourceMappingURL=babylon.viveController.js.map
  65111. var BABYLON;
  65112. (function (BABYLON) {
  65113. var GenericController = /** @class */ (function (_super) {
  65114. __extends(GenericController, _super);
  65115. function GenericController(vrGamepad) {
  65116. return _super.call(this, vrGamepad) || this;
  65117. }
  65118. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65119. var _this = this;
  65120. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65121. _this._defaultModel = newMeshes[1];
  65122. _this.attachToMesh(_this._defaultModel);
  65123. if (meshLoaded) {
  65124. meshLoaded(_this._defaultModel);
  65125. }
  65126. });
  65127. };
  65128. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65129. console.log("Button id: " + buttonIdx + "state: ");
  65130. console.dir(state);
  65131. };
  65132. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65133. GenericController.MODEL_FILENAME = 'generic.babylon';
  65134. return GenericController;
  65135. }(BABYLON.WebVRController));
  65136. BABYLON.GenericController = GenericController;
  65137. })(BABYLON || (BABYLON = {}));
  65138. //# sourceMappingURL=babylon.genericController.js.map
  65139. var BABYLON;
  65140. (function (BABYLON) {
  65141. var LoadedMeshInfo = /** @class */ (function () {
  65142. function LoadedMeshInfo() {
  65143. this.buttonMeshes = {};
  65144. this.axisMeshes = {};
  65145. }
  65146. return LoadedMeshInfo;
  65147. }());
  65148. var WindowsMotionController = /** @class */ (function (_super) {
  65149. __extends(WindowsMotionController, _super);
  65150. function WindowsMotionController(vrGamepad) {
  65151. var _this = _super.call(this, vrGamepad) || this;
  65152. _this._mapping = {
  65153. // Semantic button names
  65154. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65155. // A mapping of the button name to glTF model node name
  65156. // that should be transformed by button value.
  65157. buttonMeshNames: {
  65158. 'trigger': 'SELECT',
  65159. 'menu': 'MENU',
  65160. 'grip': 'GRASP',
  65161. 'thumbstick': 'THUMBSTICK_PRESS',
  65162. 'trackpad': 'TOUCHPAD_PRESS'
  65163. },
  65164. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65165. buttonObservableNames: {
  65166. 'trigger': 'onTriggerStateChangedObservable',
  65167. 'menu': 'onSecondaryButtonStateChangedObservable',
  65168. 'grip': 'onMainButtonStateChangedObservable',
  65169. 'thumbstick': 'onPadStateChangedObservable',
  65170. 'trackpad': 'onTrackpadChangedObservable'
  65171. },
  65172. // A mapping of the axis name to glTF model node name
  65173. // that should be transformed by axis value.
  65174. // This array mirrors the browserGamepad.axes array, such that
  65175. // the mesh corresponding to axis 0 is in this array index 0.
  65176. axisMeshNames: [
  65177. 'THUMBSTICK_X',
  65178. 'THUMBSTICK_Y',
  65179. 'TOUCHPAD_TOUCH_X',
  65180. 'TOUCHPAD_TOUCH_Y'
  65181. ],
  65182. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65183. };
  65184. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65185. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65186. _this.trackpad = { x: 0, y: 0 };
  65187. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65188. _this._loadedMeshInfo = null;
  65189. return _this;
  65190. }
  65191. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65192. get: function () {
  65193. return this.onTriggerStateChangedObservable;
  65194. },
  65195. enumerable: true,
  65196. configurable: true
  65197. });
  65198. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65199. get: function () {
  65200. return this.onSecondaryButtonStateChangedObservable;
  65201. },
  65202. enumerable: true,
  65203. configurable: true
  65204. });
  65205. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65206. get: function () {
  65207. return this.onMainButtonStateChangedObservable;
  65208. },
  65209. enumerable: true,
  65210. configurable: true
  65211. });
  65212. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65213. get: function () {
  65214. return this.onPadStateChangedObservable;
  65215. },
  65216. enumerable: true,
  65217. configurable: true
  65218. });
  65219. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65220. get: function () {
  65221. return this.onTrackpadChangedObservable;
  65222. },
  65223. enumerable: true,
  65224. configurable: true
  65225. });
  65226. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65227. get: function () {
  65228. return this.onTrackpadValuesChangedObservable;
  65229. },
  65230. enumerable: true,
  65231. configurable: true
  65232. });
  65233. /**
  65234. * Called once per frame by the engine.
  65235. */
  65236. WindowsMotionController.prototype.update = function () {
  65237. _super.prototype.update.call(this);
  65238. if (this.browserGamepad.axes) {
  65239. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65240. this.trackpad.x = this.browserGamepad["axes"][2];
  65241. this.trackpad.y = this.browserGamepad["axes"][3];
  65242. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65243. }
  65244. // Only need to animate axes if there is a loaded mesh
  65245. if (this._loadedMeshInfo) {
  65246. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65247. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65248. }
  65249. }
  65250. }
  65251. };
  65252. /**
  65253. * Called once for each button that changed state since the last frame
  65254. * @param buttonIdx Which button index changed
  65255. * @param state New state of the button
  65256. * @param changes Which properties on the state changed since last frame
  65257. */
  65258. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65259. var buttonName = this._mapping.buttons[buttonIdx];
  65260. if (!buttonName) {
  65261. return;
  65262. }
  65263. // Only emit events for buttons that we know how to map from index to name
  65264. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65265. if (observable) {
  65266. observable.notifyObservers(state);
  65267. }
  65268. this.lerpButtonTransform(buttonName, state.value);
  65269. };
  65270. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65271. // If there is no loaded mesh, there is nothing to transform.
  65272. if (!this._loadedMeshInfo) {
  65273. return;
  65274. }
  65275. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65276. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65277. return;
  65278. }
  65279. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65280. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65281. };
  65282. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65283. if (!this._loadedMeshInfo) {
  65284. return;
  65285. }
  65286. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65287. if (!meshInfo) {
  65288. return;
  65289. }
  65290. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65291. return;
  65292. }
  65293. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65294. var lerpValue = axisValue * 0.5 + 0.5;
  65295. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65296. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65297. };
  65298. /**
  65299. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65300. * @param scene scene in which to add meshes
  65301. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65302. */
  65303. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65304. var _this = this;
  65305. if (forceDefault === void 0) { forceDefault = false; }
  65306. var path;
  65307. var filename;
  65308. // Checking if GLB loader is present
  65309. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65310. // Determine the device specific folder based on the ID suffix
  65311. var device = 'default';
  65312. if (this.id && !forceDefault) {
  65313. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65314. device = ((match && match[0]) || device);
  65315. }
  65316. // Hand
  65317. if (this.hand === 'left') {
  65318. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65319. }
  65320. else {
  65321. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65322. }
  65323. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65324. }
  65325. else {
  65326. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65327. path = BABYLON.GenericController.MODEL_BASE_URL;
  65328. filename = BABYLON.GenericController.MODEL_FILENAME;
  65329. }
  65330. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65331. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65332. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65333. if (!_this._loadedMeshInfo) {
  65334. return;
  65335. }
  65336. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65337. _this.attachToMesh(_this._defaultModel);
  65338. if (meshLoaded) {
  65339. meshLoaded(_this._defaultModel);
  65340. }
  65341. }, null, function (scene, message) {
  65342. BABYLON.Tools.Log(message);
  65343. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65344. if (!forceDefault) {
  65345. _this.initControllerMesh(scene, meshLoaded, true);
  65346. }
  65347. });
  65348. };
  65349. /**
  65350. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65351. * can be transformed by button presses and axes values, based on this._mapping.
  65352. *
  65353. * @param scene scene in which the meshes exist
  65354. * @param meshes list of meshes that make up the controller model to process
  65355. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65356. */
  65357. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65358. var loadedMeshInfo = null;
  65359. // Create a new mesh to contain the glTF hierarchy
  65360. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65361. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65362. var childMesh = null;
  65363. for (var i = 0; i < meshes.length; i++) {
  65364. var mesh = meshes[i];
  65365. if (!mesh.parent) {
  65366. // Exclude controller meshes from picking results
  65367. mesh.isPickable = false;
  65368. // Handle root node, attach to the new parentMesh
  65369. childMesh = mesh;
  65370. break;
  65371. }
  65372. }
  65373. if (childMesh) {
  65374. childMesh.setParent(parentMesh);
  65375. // Create our mesh info. Note that this method will always return non-null.
  65376. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65377. }
  65378. else {
  65379. BABYLON.Tools.Warn('Could not find root node in model file.');
  65380. }
  65381. return loadedMeshInfo;
  65382. };
  65383. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65384. var loadedMeshInfo = new LoadedMeshInfo();
  65385. var i;
  65386. loadedMeshInfo.rootNode = rootNode;
  65387. // Reset the caches
  65388. loadedMeshInfo.buttonMeshes = {};
  65389. loadedMeshInfo.axisMeshes = {};
  65390. // Button Meshes
  65391. for (i = 0; i < this._mapping.buttons.length; i++) {
  65392. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65393. if (!buttonMeshName) {
  65394. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65395. continue;
  65396. }
  65397. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65398. if (!buttonMesh) {
  65399. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65400. continue;
  65401. }
  65402. var buttonMeshInfo = {
  65403. index: i,
  65404. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65405. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65406. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65407. };
  65408. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65409. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65410. }
  65411. else {
  65412. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65413. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65414. '(VALUE: ' + !!buttonMeshInfo.value +
  65415. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65416. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65417. ')');
  65418. }
  65419. }
  65420. // Axis Meshes
  65421. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65422. var axisMeshName = this._mapping.axisMeshNames[i];
  65423. if (!axisMeshName) {
  65424. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65425. continue;
  65426. }
  65427. var axisMesh = getChildByName(rootNode, axisMeshName);
  65428. if (!axisMesh) {
  65429. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65430. continue;
  65431. }
  65432. var axisMeshInfo = {
  65433. index: i,
  65434. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65435. min: getImmediateChildByName(axisMesh, 'MIN'),
  65436. max: getImmediateChildByName(axisMesh, 'MAX')
  65437. };
  65438. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65439. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65440. }
  65441. else {
  65442. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65443. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65444. '(VALUE: ' + !!axisMeshInfo.value +
  65445. ', MIN: ' + !!axisMeshInfo.min +
  65446. ', MAX:' + !!axisMeshInfo.max +
  65447. ')');
  65448. }
  65449. }
  65450. // Pointing Ray
  65451. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65452. if (!loadedMeshInfo.pointingPoseNode) {
  65453. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65454. }
  65455. return loadedMeshInfo;
  65456. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65457. function getChildByName(node, name) {
  65458. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65459. }
  65460. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65461. function getImmediateChildByName(node, name) {
  65462. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65463. }
  65464. };
  65465. WindowsMotionController.prototype.getForwardRay = function (length) {
  65466. if (length === void 0) { length = 100; }
  65467. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65468. return _super.prototype.getForwardRay.call(this, length);
  65469. }
  65470. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65471. var origin = m.getTranslation();
  65472. var forward = new BABYLON.Vector3(0, 0, -1);
  65473. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65474. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65475. return new BABYLON.Ray(origin, direction, length);
  65476. };
  65477. WindowsMotionController.prototype.dispose = function () {
  65478. _super.prototype.dispose.call(this);
  65479. this.onTrackpadChangedObservable.clear();
  65480. };
  65481. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65482. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65483. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65484. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65485. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65486. return WindowsMotionController;
  65487. }(BABYLON.WebVRController));
  65488. BABYLON.WindowsMotionController = WindowsMotionController;
  65489. })(BABYLON || (BABYLON = {}));
  65490. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65491. var BABYLON;
  65492. (function (BABYLON) {
  65493. var GearVRController = /** @class */ (function (_super) {
  65494. __extends(GearVRController, _super);
  65495. function GearVRController(vrGamepad) {
  65496. var _this = _super.call(this, vrGamepad) || this;
  65497. _this._buttonIndexToObservableNameMap = [
  65498. 'onTrackpadChangedObservable',
  65499. 'onTriggerStateChangedObservable' // Trigger
  65500. ];
  65501. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65502. return _this;
  65503. }
  65504. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65505. var _this = this;
  65506. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65507. _this._defaultModel = newMeshes[1];
  65508. _this.attachToMesh(_this._defaultModel);
  65509. if (meshLoaded) {
  65510. meshLoaded(_this._defaultModel);
  65511. }
  65512. });
  65513. };
  65514. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65515. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65516. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65517. // Only emit events for buttons that we know how to map from index to observable
  65518. var observable = this[observableName];
  65519. if (observable) {
  65520. observable.notifyObservers(state);
  65521. }
  65522. }
  65523. };
  65524. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65525. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65526. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65527. return GearVRController;
  65528. }(BABYLON.WebVRController));
  65529. BABYLON.GearVRController = GearVRController;
  65530. })(BABYLON || (BABYLON = {}));
  65531. //# sourceMappingURL=babylon.gearVRController.js.map
  65532. var BABYLON;
  65533. (function (BABYLON) {
  65534. /**
  65535. * Google Daydream controller
  65536. */
  65537. var DaydreamController = /** @class */ (function (_super) {
  65538. __extends(DaydreamController, _super);
  65539. function DaydreamController(vrGamepad) {
  65540. var _this = _super.call(this, vrGamepad) || this;
  65541. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65542. return _this;
  65543. }
  65544. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65545. var _this = this;
  65546. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65547. _this._defaultModel = newMeshes[1];
  65548. _this.attachToMesh(_this._defaultModel);
  65549. if (meshLoaded) {
  65550. meshLoaded(_this._defaultModel);
  65551. }
  65552. });
  65553. };
  65554. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65555. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65556. if (buttonIdx === 0) {
  65557. var observable = this.onTriggerStateChangedObservable;
  65558. if (observable) {
  65559. observable.notifyObservers(state);
  65560. }
  65561. }
  65562. else {
  65563. // If the app or home buttons are ever made available
  65564. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65565. }
  65566. };
  65567. /**
  65568. * Base Url for the controller model.
  65569. */
  65570. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65571. /**
  65572. * File name for the controller model.
  65573. */
  65574. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65575. /**
  65576. * Gamepad Id prefix used to identify Daydream Controller.
  65577. */
  65578. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65579. return DaydreamController;
  65580. }(BABYLON.WebVRController));
  65581. BABYLON.DaydreamController = DaydreamController;
  65582. })(BABYLON || (BABYLON = {}));
  65583. //# sourceMappingURL=babylon.daydreamController.js.map
  65584. var BABYLON;
  65585. (function (BABYLON) {
  65586. var FollowCamera = /** @class */ (function (_super) {
  65587. __extends(FollowCamera, _super);
  65588. function FollowCamera(name, position, scene, lockedTarget) {
  65589. if (lockedTarget === void 0) { lockedTarget = null; }
  65590. var _this = _super.call(this, name, position, scene) || this;
  65591. _this.radius = 12;
  65592. _this.rotationOffset = 0;
  65593. _this.heightOffset = 4;
  65594. _this.cameraAcceleration = 0.05;
  65595. _this.maxCameraSpeed = 20;
  65596. _this.lockedTarget = lockedTarget;
  65597. return _this;
  65598. }
  65599. FollowCamera.prototype.getRadians = function (degrees) {
  65600. return degrees * Math.PI / 180;
  65601. };
  65602. FollowCamera.prototype.follow = function (cameraTarget) {
  65603. if (!cameraTarget)
  65604. return;
  65605. var yRotation;
  65606. if (cameraTarget.rotationQuaternion) {
  65607. var rotMatrix = new BABYLON.Matrix();
  65608. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65609. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65610. }
  65611. else {
  65612. yRotation = cameraTarget.rotation.y;
  65613. }
  65614. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65615. var targetPosition = cameraTarget.getAbsolutePosition();
  65616. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65617. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65618. var dx = targetX - this.position.x;
  65619. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65620. var dz = (targetZ) - this.position.z;
  65621. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65622. var vy = dy * this.cameraAcceleration;
  65623. var vz = dz * this.cameraAcceleration * 2;
  65624. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65625. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65626. }
  65627. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65628. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65629. }
  65630. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65631. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65632. }
  65633. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65634. this.setTarget(targetPosition);
  65635. };
  65636. FollowCamera.prototype._checkInputs = function () {
  65637. _super.prototype._checkInputs.call(this);
  65638. if (this.lockedTarget) {
  65639. this.follow(this.lockedTarget);
  65640. }
  65641. };
  65642. FollowCamera.prototype.getClassName = function () {
  65643. return "FollowCamera";
  65644. };
  65645. __decorate([
  65646. BABYLON.serialize()
  65647. ], FollowCamera.prototype, "radius", void 0);
  65648. __decorate([
  65649. BABYLON.serialize()
  65650. ], FollowCamera.prototype, "rotationOffset", void 0);
  65651. __decorate([
  65652. BABYLON.serialize()
  65653. ], FollowCamera.prototype, "heightOffset", void 0);
  65654. __decorate([
  65655. BABYLON.serialize()
  65656. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65657. __decorate([
  65658. BABYLON.serialize()
  65659. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65660. __decorate([
  65661. BABYLON.serializeAsMeshReference("lockedTargetId")
  65662. ], FollowCamera.prototype, "lockedTarget", void 0);
  65663. return FollowCamera;
  65664. }(BABYLON.TargetCamera));
  65665. BABYLON.FollowCamera = FollowCamera;
  65666. var ArcFollowCamera = /** @class */ (function (_super) {
  65667. __extends(ArcFollowCamera, _super);
  65668. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65669. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65670. _this.alpha = alpha;
  65671. _this.beta = beta;
  65672. _this.radius = radius;
  65673. _this.target = target;
  65674. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65675. _this.follow();
  65676. return _this;
  65677. }
  65678. ArcFollowCamera.prototype.follow = function () {
  65679. if (!this.target) {
  65680. return;
  65681. }
  65682. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65683. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65684. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65685. var targetPosition = this.target.getAbsolutePosition();
  65686. this.position = targetPosition.add(this._cartesianCoordinates);
  65687. this.setTarget(targetPosition);
  65688. };
  65689. ArcFollowCamera.prototype._checkInputs = function () {
  65690. _super.prototype._checkInputs.call(this);
  65691. this.follow();
  65692. };
  65693. ArcFollowCamera.prototype.getClassName = function () {
  65694. return "ArcFollowCamera";
  65695. };
  65696. return ArcFollowCamera;
  65697. }(BABYLON.TargetCamera));
  65698. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65699. })(BABYLON || (BABYLON = {}));
  65700. //# sourceMappingURL=babylon.followCamera.js.map
  65701. var BABYLON;
  65702. (function (BABYLON) {
  65703. // We're mainly based on the logic defined into the FreeCamera code
  65704. var UniversalCamera = /** @class */ (function (_super) {
  65705. __extends(UniversalCamera, _super);
  65706. //-- end properties for backward compatibility for inputs
  65707. function UniversalCamera(name, position, scene) {
  65708. var _this = _super.call(this, name, position, scene) || this;
  65709. _this.inputs.addGamepad();
  65710. return _this;
  65711. }
  65712. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65713. //-- Begin properties for backward compatibility for inputs
  65714. get: function () {
  65715. var gamepad = this.inputs.attached["gamepad"];
  65716. if (gamepad)
  65717. return gamepad.gamepadAngularSensibility;
  65718. return 0;
  65719. },
  65720. set: function (value) {
  65721. var gamepad = this.inputs.attached["gamepad"];
  65722. if (gamepad)
  65723. gamepad.gamepadAngularSensibility = value;
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65729. get: function () {
  65730. var gamepad = this.inputs.attached["gamepad"];
  65731. if (gamepad)
  65732. return gamepad.gamepadMoveSensibility;
  65733. return 0;
  65734. },
  65735. set: function (value) {
  65736. var gamepad = this.inputs.attached["gamepad"];
  65737. if (gamepad)
  65738. gamepad.gamepadMoveSensibility = value;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. UniversalCamera.prototype.getClassName = function () {
  65744. return "UniversalCamera";
  65745. };
  65746. return UniversalCamera;
  65747. }(BABYLON.TouchCamera));
  65748. BABYLON.UniversalCamera = UniversalCamera;
  65749. })(BABYLON || (BABYLON = {}));
  65750. //# sourceMappingURL=babylon.universalCamera.js.map
  65751. var BABYLON;
  65752. (function (BABYLON) {
  65753. // We're mainly based on the logic defined into the FreeCamera code
  65754. var GamepadCamera = /** @class */ (function (_super) {
  65755. __extends(GamepadCamera, _super);
  65756. //-- end properties for backward compatibility for inputs
  65757. function GamepadCamera(name, position, scene) {
  65758. return _super.call(this, name, position, scene) || this;
  65759. }
  65760. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65761. //-- Begin properties for backward compatibility for inputs
  65762. get: function () {
  65763. var gamepad = this.inputs.attached["gamepad"];
  65764. if (gamepad)
  65765. return gamepad.gamepadAngularSensibility;
  65766. return 0;
  65767. },
  65768. set: function (value) {
  65769. var gamepad = this.inputs.attached["gamepad"];
  65770. if (gamepad)
  65771. gamepad.gamepadAngularSensibility = value;
  65772. },
  65773. enumerable: true,
  65774. configurable: true
  65775. });
  65776. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65777. get: function () {
  65778. var gamepad = this.inputs.attached["gamepad"];
  65779. if (gamepad)
  65780. return gamepad.gamepadMoveSensibility;
  65781. return 0;
  65782. },
  65783. set: function (value) {
  65784. var gamepad = this.inputs.attached["gamepad"];
  65785. if (gamepad)
  65786. gamepad.gamepadMoveSensibility = value;
  65787. },
  65788. enumerable: true,
  65789. configurable: true
  65790. });
  65791. GamepadCamera.prototype.getClassName = function () {
  65792. return "GamepadCamera";
  65793. };
  65794. return GamepadCamera;
  65795. }(BABYLON.UniversalCamera));
  65796. BABYLON.GamepadCamera = GamepadCamera;
  65797. })(BABYLON || (BABYLON = {}));
  65798. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65799. var BABYLON;
  65800. (function (BABYLON) {
  65801. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65802. function PostProcessRenderPipelineManager() {
  65803. this._renderPipelines = {};
  65804. }
  65805. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65806. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65807. };
  65808. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65809. if (unique === void 0) { unique = false; }
  65810. var renderPipeline = this._renderPipelines[renderPipelineName];
  65811. if (!renderPipeline) {
  65812. return;
  65813. }
  65814. renderPipeline._attachCameras(cameras, unique);
  65815. };
  65816. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65817. var renderPipeline = this._renderPipelines[renderPipelineName];
  65818. if (!renderPipeline) {
  65819. return;
  65820. }
  65821. renderPipeline._detachCameras(cameras);
  65822. };
  65823. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65824. var renderPipeline = this._renderPipelines[renderPipelineName];
  65825. if (!renderPipeline) {
  65826. return;
  65827. }
  65828. renderPipeline._enableEffect(renderEffectName, cameras);
  65829. };
  65830. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65831. var renderPipeline = this._renderPipelines[renderPipelineName];
  65832. if (!renderPipeline) {
  65833. return;
  65834. }
  65835. renderPipeline._disableEffect(renderEffectName, cameras);
  65836. };
  65837. PostProcessRenderPipelineManager.prototype.update = function () {
  65838. for (var renderPipelineName in this._renderPipelines) {
  65839. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65840. var pipeline = this._renderPipelines[renderPipelineName];
  65841. if (!pipeline.isSupported) {
  65842. pipeline.dispose();
  65843. delete this._renderPipelines[renderPipelineName];
  65844. }
  65845. else {
  65846. pipeline._update();
  65847. }
  65848. }
  65849. }
  65850. };
  65851. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65852. for (var renderPipelineName in this._renderPipelines) {
  65853. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65854. var pipeline = this._renderPipelines[renderPipelineName];
  65855. pipeline._rebuild();
  65856. }
  65857. }
  65858. };
  65859. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65860. for (var renderPipelineName in this._renderPipelines) {
  65861. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65862. var pipeline = this._renderPipelines[renderPipelineName];
  65863. pipeline.dispose();
  65864. }
  65865. }
  65866. };
  65867. return PostProcessRenderPipelineManager;
  65868. }());
  65869. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65870. })(BABYLON || (BABYLON = {}));
  65871. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65872. var BABYLON;
  65873. (function (BABYLON) {
  65874. /**
  65875. * This represents a set of one or more post processes in Babylon.
  65876. * A post process can be used to apply a shader to a texture after it is rendered.
  65877. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65878. */
  65879. var PostProcessRenderEffect = /** @class */ (function () {
  65880. /**
  65881. * Instantiates a post process render effect.
  65882. * A post process can be used to apply a shader to a texture after it is rendered.
  65883. * @param engine The engine the effect is tied to
  65884. * @param name The name of the effect
  65885. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65886. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65887. */
  65888. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65889. this._name = name;
  65890. this._singleInstance = singleInstance || true;
  65891. this._getPostProcesses = getPostProcesses;
  65892. this._cameras = {};
  65893. this._indicesForCamera = {};
  65894. this._postProcesses = {};
  65895. }
  65896. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65897. /**
  65898. * Checks if all the post processes in the effect are supported.
  65899. */
  65900. get: function () {
  65901. for (var index in this._postProcesses) {
  65902. for (var ppIndex in this._postProcesses[index]) {
  65903. if (!this._postProcesses[index][ppIndex].isSupported) {
  65904. return false;
  65905. }
  65906. }
  65907. }
  65908. return true;
  65909. },
  65910. enumerable: true,
  65911. configurable: true
  65912. });
  65913. /**
  65914. * Updates the current state of the effect
  65915. */
  65916. PostProcessRenderEffect.prototype._update = function () {
  65917. };
  65918. /**
  65919. * Attaches the effect on cameras
  65920. * @param cameras The camera to attach to.
  65921. */
  65922. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65923. var _this = this;
  65924. var cameraKey;
  65925. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65926. if (!cams) {
  65927. return;
  65928. }
  65929. for (var i = 0; i < cams.length; i++) {
  65930. var camera = cams[i];
  65931. var cameraName = camera.name;
  65932. if (this._singleInstance) {
  65933. cameraKey = 0;
  65934. }
  65935. else {
  65936. cameraKey = cameraName;
  65937. }
  65938. if (!this._postProcesses[cameraKey]) {
  65939. var postProcess = this._getPostProcesses();
  65940. if (postProcess) {
  65941. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65942. }
  65943. }
  65944. if (!this._indicesForCamera[cameraName]) {
  65945. this._indicesForCamera[cameraName] = [];
  65946. }
  65947. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65948. var index = camera.attachPostProcess(postProcess);
  65949. _this._indicesForCamera[cameraName].push(index);
  65950. });
  65951. if (!this._cameras[cameraName]) {
  65952. this._cameras[cameraName] = camera;
  65953. }
  65954. }
  65955. };
  65956. /**
  65957. * Detatches the effect on cameras
  65958. * @param cameras The camera to detatch from.
  65959. */
  65960. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65961. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65962. if (!cams) {
  65963. return;
  65964. }
  65965. for (var i = 0; i < cams.length; i++) {
  65966. var camera = cams[i];
  65967. var cameraName = camera.name;
  65968. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65969. camera.detachPostProcess(postProcess);
  65970. });
  65971. if (this._cameras[cameraName]) {
  65972. //this._indicesForCamera.splice(index, 1);
  65973. this._cameras[cameraName] = null;
  65974. }
  65975. }
  65976. };
  65977. /**
  65978. * Enables the effect on given cameras
  65979. * @param cameras The camera to enable.
  65980. */
  65981. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65982. var _this = this;
  65983. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65984. if (!cams) {
  65985. return;
  65986. }
  65987. for (var i = 0; i < cams.length; i++) {
  65988. var camera = cams[i];
  65989. var cameraName = camera.name;
  65990. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65991. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  65992. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65993. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65994. });
  65995. }
  65996. }
  65997. }
  65998. };
  65999. /**
  66000. * Disables the effect on the given cameras
  66001. * @param cameras The camera to disable.
  66002. */
  66003. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66004. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66005. if (!cams) {
  66006. return;
  66007. }
  66008. for (var i = 0; i < cams.length; i++) {
  66009. var camera = cams[i];
  66010. var cameraName = camera.name;
  66011. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66012. camera.detachPostProcess(postProcess);
  66013. });
  66014. }
  66015. };
  66016. /**
  66017. * Gets a list of the post processes contained in the effect.
  66018. * @param camera The camera to get the post processes on.
  66019. * @returns The list of the post processes in the effect.
  66020. */
  66021. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66022. if (this._singleInstance) {
  66023. return this._postProcesses[0];
  66024. }
  66025. else {
  66026. if (!camera) {
  66027. return null;
  66028. }
  66029. return this._postProcesses[camera.name];
  66030. }
  66031. };
  66032. return PostProcessRenderEffect;
  66033. }());
  66034. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66035. })(BABYLON || (BABYLON = {}));
  66036. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66037. var BABYLON;
  66038. (function (BABYLON) {
  66039. var PostProcessRenderPipeline = /** @class */ (function () {
  66040. function PostProcessRenderPipeline(engine, name) {
  66041. this.engine = engine;
  66042. this._name = name;
  66043. this._renderEffects = {};
  66044. this._renderEffectsForIsolatedPass = new Array();
  66045. this._cameras = [];
  66046. }
  66047. PostProcessRenderPipeline.prototype.getClassName = function () {
  66048. return "PostProcessRenderPipeline";
  66049. };
  66050. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66051. get: function () {
  66052. for (var renderEffectName in this._renderEffects) {
  66053. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66054. if (!this._renderEffects[renderEffectName].isSupported) {
  66055. return false;
  66056. }
  66057. }
  66058. }
  66059. return true;
  66060. },
  66061. enumerable: true,
  66062. configurable: true
  66063. });
  66064. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66065. this._renderEffects[renderEffect._name] = renderEffect;
  66066. };
  66067. // private
  66068. PostProcessRenderPipeline.prototype._rebuild = function () {
  66069. };
  66070. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66071. var renderEffects = this._renderEffects[renderEffectName];
  66072. if (!renderEffects) {
  66073. return;
  66074. }
  66075. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66076. };
  66077. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66078. var renderEffects = this._renderEffects[renderEffectName];
  66079. if (!renderEffects) {
  66080. return;
  66081. }
  66082. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66083. };
  66084. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66085. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66086. if (!cams) {
  66087. return;
  66088. }
  66089. var indicesToDelete = [];
  66090. var i;
  66091. for (i = 0; i < cams.length; i++) {
  66092. var camera = cams[i];
  66093. var cameraName = camera.name;
  66094. if (this._cameras.indexOf(camera) === -1) {
  66095. this._cameras[cameraName] = camera;
  66096. }
  66097. else if (unique) {
  66098. indicesToDelete.push(i);
  66099. }
  66100. }
  66101. for (i = 0; i < indicesToDelete.length; i++) {
  66102. cameras.splice(indicesToDelete[i], 1);
  66103. }
  66104. for (var renderEffectName in this._renderEffects) {
  66105. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66106. this._renderEffects[renderEffectName]._attachCameras(cams);
  66107. }
  66108. }
  66109. };
  66110. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66111. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66112. if (!cams) {
  66113. return;
  66114. }
  66115. for (var renderEffectName in this._renderEffects) {
  66116. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66117. this._renderEffects[renderEffectName]._detachCameras(cams);
  66118. }
  66119. }
  66120. for (var i = 0; i < cams.length; i++) {
  66121. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66122. }
  66123. };
  66124. PostProcessRenderPipeline.prototype._update = function () {
  66125. for (var renderEffectName in this._renderEffects) {
  66126. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66127. this._renderEffects[renderEffectName]._update();
  66128. }
  66129. }
  66130. for (var i = 0; i < this._cameras.length; i++) {
  66131. var cameraName = this._cameras[i].name;
  66132. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66133. this._renderEffectsForIsolatedPass[cameraName]._update();
  66134. }
  66135. }
  66136. };
  66137. PostProcessRenderPipeline.prototype._reset = function () {
  66138. this._renderEffects = {};
  66139. this._renderEffectsForIsolatedPass = new Array();
  66140. };
  66141. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66142. // 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)
  66143. var effectKeys = Object.keys(this._renderEffects);
  66144. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66145. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66146. if (postProcesses) {
  66147. postProcesses[0].samples = 4;
  66148. return true;
  66149. }
  66150. }
  66151. return false;
  66152. };
  66153. PostProcessRenderPipeline.prototype.dispose = function () {
  66154. // Must be implemented by children
  66155. };
  66156. __decorate([
  66157. BABYLON.serialize()
  66158. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66159. return PostProcessRenderPipeline;
  66160. }());
  66161. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66162. })(BABYLON || (BABYLON = {}));
  66163. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66164. var BABYLON;
  66165. (function (BABYLON) {
  66166. /**
  66167. * This represents a depth renderer in Babylon.
  66168. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66169. */
  66170. var DepthRenderer = /** @class */ (function () {
  66171. /**
  66172. * Instantiates a depth renderer
  66173. * @param scene The scene the renderer belongs to
  66174. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66175. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66176. */
  66177. function DepthRenderer(scene, type, camera) {
  66178. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66179. if (camera === void 0) { camera = null; }
  66180. var _this = this;
  66181. this._scene = scene;
  66182. this._camera = camera;
  66183. var engine = scene.getEngine();
  66184. // Render target
  66185. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66186. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66187. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66188. this._depthMap.refreshRate = 1;
  66189. this._depthMap.renderParticles = false;
  66190. this._depthMap.renderList = null;
  66191. // Camera to get depth map from to support multiple concurrent cameras
  66192. this._depthMap.activeCamera = this._camera;
  66193. this._depthMap.ignoreCameraViewport = true;
  66194. this._depthMap.useCameraPostProcesses = false;
  66195. // set default depth value to 1.0 (far away)
  66196. this._depthMap.onClearObservable.add(function (engine) {
  66197. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66198. });
  66199. // Custom render function
  66200. var renderSubMesh = function (subMesh) {
  66201. var mesh = subMesh.getRenderingMesh();
  66202. var scene = _this._scene;
  66203. var engine = scene.getEngine();
  66204. var material = subMesh.getMaterial();
  66205. if (!material) {
  66206. return;
  66207. }
  66208. // Culling and reverse (right handed system)
  66209. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66210. // Managing instances
  66211. var batch = mesh._getInstancesRenderList(subMesh._id);
  66212. if (batch.mustReturn) {
  66213. return;
  66214. }
  66215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66216. var camera = _this._camera || scene.activeCamera;
  66217. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66218. engine.enableEffect(_this._effect);
  66219. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66220. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66221. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66222. // Alpha test
  66223. if (material && material.needAlphaTesting()) {
  66224. var alphaTexture = material.getAlphaTestTexture();
  66225. if (alphaTexture) {
  66226. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66227. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66228. }
  66229. }
  66230. // Bones
  66231. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66232. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66233. }
  66234. // Draw
  66235. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66236. }
  66237. };
  66238. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66239. var index;
  66240. if (depthOnlySubMeshes.length) {
  66241. engine.setColorWrite(false);
  66242. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66243. renderSubMesh(depthOnlySubMeshes.data[index]);
  66244. }
  66245. engine.setColorWrite(true);
  66246. }
  66247. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66248. renderSubMesh(opaqueSubMeshes.data[index]);
  66249. }
  66250. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66251. renderSubMesh(alphaTestSubMeshes.data[index]);
  66252. }
  66253. };
  66254. }
  66255. /**
  66256. * Creates the depth rendering effect and checks if the effect is ready.
  66257. * @param subMesh The submesh to be used to render the depth map of
  66258. * @param useInstances If multiple world instances should be used
  66259. * @returns if the depth renderer is ready to render the depth map
  66260. */
  66261. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66262. var material = subMesh.getMaterial();
  66263. if (material.disableDepthWrite) {
  66264. return false;
  66265. }
  66266. var defines = [];
  66267. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66268. var mesh = subMesh.getMesh();
  66269. // Alpha test
  66270. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66271. defines.push("#define ALPHATEST");
  66272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66273. attribs.push(BABYLON.VertexBuffer.UVKind);
  66274. defines.push("#define UV1");
  66275. }
  66276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66277. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66278. defines.push("#define UV2");
  66279. }
  66280. }
  66281. // Bones
  66282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66285. if (mesh.numBoneInfluencers > 4) {
  66286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66288. }
  66289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66290. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66291. }
  66292. else {
  66293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66294. }
  66295. // Instances
  66296. if (useInstances) {
  66297. defines.push("#define INSTANCES");
  66298. attribs.push("world0");
  66299. attribs.push("world1");
  66300. attribs.push("world2");
  66301. attribs.push("world3");
  66302. }
  66303. // Get correct effect
  66304. var join = defines.join("\n");
  66305. if (this._cachedDefines !== join) {
  66306. this._cachedDefines = join;
  66307. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66308. }
  66309. return this._effect.isReady();
  66310. };
  66311. /**
  66312. * Gets the texture which the depth map will be written to.
  66313. * @returns The depth map texture
  66314. */
  66315. DepthRenderer.prototype.getDepthMap = function () {
  66316. return this._depthMap;
  66317. };
  66318. /**
  66319. * Disposes of the depth renderer.
  66320. */
  66321. DepthRenderer.prototype.dispose = function () {
  66322. this._depthMap.dispose();
  66323. };
  66324. return DepthRenderer;
  66325. }());
  66326. BABYLON.DepthRenderer = DepthRenderer;
  66327. })(BABYLON || (BABYLON = {}));
  66328. //# sourceMappingURL=babylon.depthRenderer.js.map
  66329. var BABYLON;
  66330. (function (BABYLON) {
  66331. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66332. __extends(SSAORenderingPipeline, _super);
  66333. /**
  66334. * @constructor
  66335. * @param {string} name - The rendering pipeline name
  66336. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66337. * @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 }
  66338. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66339. */
  66340. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66341. var _this = _super.call(this, scene.getEngine(), name) || this;
  66342. // Members
  66343. /**
  66344. * The PassPostProcess id in the pipeline that contains the original scene color
  66345. * @type {string}
  66346. */
  66347. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66348. /**
  66349. * The SSAO PostProcess id in the pipeline
  66350. * @type {string}
  66351. */
  66352. _this.SSAORenderEffect = "SSAORenderEffect";
  66353. /**
  66354. * The horizontal blur PostProcess id in the pipeline
  66355. * @type {string}
  66356. */
  66357. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66358. /**
  66359. * The vertical blur PostProcess id in the pipeline
  66360. * @type {string}
  66361. */
  66362. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66363. /**
  66364. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66365. * @type {string}
  66366. */
  66367. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66368. /**
  66369. * The output strength of the SSAO post-process. Default value is 1.0.
  66370. * @type {number}
  66371. */
  66372. _this.totalStrength = 1.0;
  66373. /**
  66374. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66375. * @type {number}
  66376. */
  66377. _this.radius = 0.0001;
  66378. /**
  66379. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66380. * Must not be equal to fallOff and superior to fallOff.
  66381. * Default value is 0.975
  66382. * @type {number}
  66383. */
  66384. _this.area = 0.0075;
  66385. /**
  66386. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66387. * Must not be equal to area and inferior to area.
  66388. * Default value is 0.0
  66389. * @type {number}
  66390. */
  66391. _this.fallOff = 0.000001;
  66392. /**
  66393. * The base color of the SSAO post-process
  66394. * The final result is "base + ssao" between [0, 1]
  66395. * @type {number}
  66396. */
  66397. _this.base = 0.5;
  66398. _this._firstUpdate = true;
  66399. _this._scene = scene;
  66400. // Set up assets
  66401. _this._createRandomTexture();
  66402. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66403. var ssaoRatio = ratio.ssaoRatio || ratio;
  66404. var combineRatio = ratio.combineRatio || ratio;
  66405. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66406. _this._createSSAOPostProcess(ssaoRatio);
  66407. _this._createBlurPostProcess(ssaoRatio);
  66408. _this._createSSAOCombinePostProcess(combineRatio);
  66409. // Set up pipeline
  66410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66411. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66413. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66414. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66415. // Finish
  66416. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66417. if (cameras)
  66418. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66419. return _this;
  66420. }
  66421. // Public Methods
  66422. /**
  66423. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66424. */
  66425. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66426. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66427. for (var i = 0; i < this._scene.cameras.length; i++) {
  66428. var camera = this._scene.cameras[i];
  66429. this._originalColorPostProcess.dispose(camera);
  66430. this._ssaoPostProcess.dispose(camera);
  66431. this._blurHPostProcess.dispose(camera);
  66432. this._blurVPostProcess.dispose(camera);
  66433. this._ssaoCombinePostProcess.dispose(camera);
  66434. }
  66435. this._randomTexture.dispose();
  66436. if (disableDepthRender)
  66437. this._scene.disableDepthRenderer();
  66438. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66439. _super.prototype.dispose.call(this);
  66440. };
  66441. // Private Methods
  66442. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66443. var _this = this;
  66444. var size = 16;
  66445. 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);
  66446. 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);
  66447. this._blurHPostProcess.onActivateObservable.add(function () {
  66448. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66449. _this._blurHPostProcess.kernel = size * dw;
  66450. });
  66451. this._blurVPostProcess.onActivateObservable.add(function () {
  66452. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66453. _this._blurVPostProcess.kernel = size * dw;
  66454. });
  66455. };
  66456. SSAORenderingPipeline.prototype._rebuild = function () {
  66457. this._firstUpdate = true;
  66458. _super.prototype._rebuild.call(this);
  66459. };
  66460. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66461. var _this = this;
  66462. var numSamples = 16;
  66463. var sampleSphere = [
  66464. 0.5381, 0.1856, -0.4319,
  66465. 0.1379, 0.2486, 0.4430,
  66466. 0.3371, 0.5679, -0.0057,
  66467. -0.6999, -0.0451, -0.0019,
  66468. 0.0689, -0.1598, -0.8547,
  66469. 0.0560, 0.0069, -0.1843,
  66470. -0.0146, 0.1402, 0.0762,
  66471. 0.0100, -0.1924, -0.0344,
  66472. -0.3577, -0.5301, -0.4358,
  66473. -0.3169, 0.1063, 0.0158,
  66474. 0.0103, -0.5869, 0.0046,
  66475. -0.0897, -0.4940, 0.3287,
  66476. 0.7119, -0.0154, -0.0918,
  66477. -0.0533, 0.0596, -0.5411,
  66478. 0.0352, -0.0631, 0.5460,
  66479. -0.4776, 0.2847, -0.0271
  66480. ];
  66481. var samplesFactor = 1.0 / numSamples;
  66482. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66483. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66484. "area", "fallOff", "base", "range", "viewport"
  66485. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66486. this._ssaoPostProcess.onApply = function (effect) {
  66487. if (_this._firstUpdate) {
  66488. effect.setArray3("sampleSphere", sampleSphere);
  66489. effect.setFloat("samplesFactor", samplesFactor);
  66490. effect.setFloat("randTextureTiles", 4.0);
  66491. }
  66492. effect.setFloat("totalStrength", _this.totalStrength);
  66493. effect.setFloat("radius", _this.radius);
  66494. effect.setFloat("area", _this.area);
  66495. effect.setFloat("fallOff", _this.fallOff);
  66496. effect.setFloat("base", _this.base);
  66497. effect.setTexture("textureSampler", _this._depthTexture);
  66498. effect.setTexture("randomSampler", _this._randomTexture);
  66499. };
  66500. };
  66501. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66502. var _this = this;
  66503. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66504. this._ssaoCombinePostProcess.onApply = function (effect) {
  66505. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66506. };
  66507. };
  66508. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66509. var size = 512;
  66510. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66511. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66512. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66513. var context = this._randomTexture.getContext();
  66514. var rand = function (min, max) {
  66515. return Math.random() * (max - min) + min;
  66516. };
  66517. var randVector = BABYLON.Vector3.Zero();
  66518. for (var x = 0; x < size; x++) {
  66519. for (var y = 0; y < size; y++) {
  66520. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66521. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66522. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66523. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66524. context.fillRect(x, y, 1, 1);
  66525. }
  66526. }
  66527. this._randomTexture.update(false);
  66528. };
  66529. __decorate([
  66530. BABYLON.serialize()
  66531. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66532. __decorate([
  66533. BABYLON.serialize()
  66534. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66535. __decorate([
  66536. BABYLON.serialize()
  66537. ], SSAORenderingPipeline.prototype, "area", void 0);
  66538. __decorate([
  66539. BABYLON.serialize()
  66540. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66541. __decorate([
  66542. BABYLON.serialize()
  66543. ], SSAORenderingPipeline.prototype, "base", void 0);
  66544. return SSAORenderingPipeline;
  66545. }(BABYLON.PostProcessRenderPipeline));
  66546. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66547. })(BABYLON || (BABYLON = {}));
  66548. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66549. var BABYLON;
  66550. (function (BABYLON) {
  66551. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66552. __extends(SSAO2RenderingPipeline, _super);
  66553. /**
  66554. * @constructor
  66555. * @param {string} name - The rendering pipeline name
  66556. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66557. * @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 }
  66558. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66559. */
  66560. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66561. var _this = _super.call(this, scene.getEngine(), name) || this;
  66562. // Members
  66563. /**
  66564. * The PassPostProcess id in the pipeline that contains the original scene color
  66565. * @type {string}
  66566. */
  66567. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66568. /**
  66569. * The SSAO PostProcess id in the pipeline
  66570. * @type {string}
  66571. */
  66572. _this.SSAORenderEffect = "SSAORenderEffect";
  66573. /**
  66574. * The horizontal blur PostProcess id in the pipeline
  66575. * @type {string}
  66576. */
  66577. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66578. /**
  66579. * The vertical blur PostProcess id in the pipeline
  66580. * @type {string}
  66581. */
  66582. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66583. /**
  66584. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66585. * @type {string}
  66586. */
  66587. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66588. /**
  66589. * The output strength of the SSAO post-process. Default value is 1.0.
  66590. * @type {number}
  66591. */
  66592. _this.totalStrength = 1.0;
  66593. /**
  66594. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66595. * @type {number}
  66596. */
  66597. _this.maxZ = 100.0;
  66598. /**
  66599. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66600. * @type {number}
  66601. */
  66602. _this.minZAspect = 0.2;
  66603. /**
  66604. * Number of samples used for the SSAO calculations. Default value is 8
  66605. * @type {number}
  66606. */
  66607. _this._samples = 8;
  66608. /**
  66609. * Are we using bilateral blur ?
  66610. * @type {boolean}
  66611. */
  66612. _this._expensiveBlur = true;
  66613. /**
  66614. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66615. * @type {number}
  66616. */
  66617. _this.radius = 2.0;
  66618. /**
  66619. * The base color of the SSAO post-process
  66620. * The final result is "base + ssao" between [0, 1]
  66621. * @type {number}
  66622. */
  66623. _this.base = 0.1;
  66624. _this._firstUpdate = true;
  66625. _this._scene = scene;
  66626. if (!_this.isSupported) {
  66627. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66628. return _this;
  66629. }
  66630. var ssaoRatio = ratio.ssaoRatio || ratio;
  66631. var blurRatio = ratio.blurRatio || ratio;
  66632. // Set up assets
  66633. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66634. _this._createRandomTexture();
  66635. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66636. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66637. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66638. _this._createSSAOPostProcess(1.0);
  66639. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66640. _this._createSSAOCombinePostProcess(blurRatio);
  66641. // Set up pipeline
  66642. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66643. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66644. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66645. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66646. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66647. // Finish
  66648. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66649. if (cameras)
  66650. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66651. return _this;
  66652. }
  66653. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66654. get: function () {
  66655. return this._samples;
  66656. },
  66657. set: function (n) {
  66658. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66659. this._samples = n;
  66660. this._sampleSphere = this._generateHemisphere();
  66661. this._firstUpdate = true;
  66662. },
  66663. enumerable: true,
  66664. configurable: true
  66665. });
  66666. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66667. get: function () {
  66668. return this._expensiveBlur;
  66669. },
  66670. set: function (b) {
  66671. 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"]);
  66672. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66673. this._expensiveBlur = b;
  66674. this._firstUpdate = true;
  66675. },
  66676. enumerable: true,
  66677. configurable: true
  66678. });
  66679. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66680. /**
  66681. * Support test.
  66682. * @type {boolean}
  66683. */
  66684. get: function () {
  66685. var engine = BABYLON.Engine.LastCreatedEngine;
  66686. if (!engine) {
  66687. return false;
  66688. }
  66689. return engine.getCaps().drawBuffersExtension;
  66690. },
  66691. enumerable: true,
  66692. configurable: true
  66693. });
  66694. // Public Methods
  66695. /**
  66696. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66697. */
  66698. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66699. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66700. for (var i = 0; i < this._scene.cameras.length; i++) {
  66701. var camera = this._scene.cameras[i];
  66702. this._originalColorPostProcess.dispose(camera);
  66703. this._ssaoPostProcess.dispose(camera);
  66704. this._blurHPostProcess.dispose(camera);
  66705. this._blurVPostProcess.dispose(camera);
  66706. this._ssaoCombinePostProcess.dispose(camera);
  66707. }
  66708. this._randomTexture.dispose();
  66709. if (disableGeometryBufferRenderer)
  66710. this._scene.disableGeometryBufferRenderer();
  66711. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66712. _super.prototype.dispose.call(this);
  66713. };
  66714. // Private Methods
  66715. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66716. var _this = this;
  66717. this._samplerOffsets = [];
  66718. var expensive = this.expensiveBlur;
  66719. for (var i = -8; i < 8; i++) {
  66720. this._samplerOffsets.push(i * 2 + 0.5);
  66721. }
  66722. 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");
  66723. this._blurHPostProcess.onApply = function (effect) {
  66724. if (!_this._scene.activeCamera) {
  66725. return;
  66726. }
  66727. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66728. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66729. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66730. effect.setFloat("radius", _this.radius);
  66731. effect.setTexture("depthSampler", _this._depthTexture);
  66732. if (_this._firstUpdate) {
  66733. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66734. }
  66735. };
  66736. 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");
  66737. this._blurVPostProcess.onApply = function (effect) {
  66738. if (!_this._scene.activeCamera) {
  66739. return;
  66740. }
  66741. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66742. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66743. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66744. effect.setFloat("radius", _this.radius);
  66745. effect.setTexture("depthSampler", _this._depthTexture);
  66746. if (_this._firstUpdate) {
  66747. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66748. _this._firstUpdate = false;
  66749. }
  66750. };
  66751. };
  66752. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66753. this._firstUpdate = true;
  66754. _super.prototype._rebuild.call(this);
  66755. };
  66756. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66757. var numSamples = this.samples;
  66758. var result = [];
  66759. var vector, scale;
  66760. var rand = function (min, max) {
  66761. return Math.random() * (max - min) + min;
  66762. };
  66763. var i = 0;
  66764. while (i < numSamples) {
  66765. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66766. vector.normalize();
  66767. scale = i / numSamples;
  66768. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66769. vector.scaleInPlace(scale);
  66770. result.push(vector.x, vector.y, vector.z);
  66771. i++;
  66772. }
  66773. return result;
  66774. };
  66775. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66776. var _this = this;
  66777. var numSamples = this.samples;
  66778. this._sampleSphere = this._generateHemisphere();
  66779. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66780. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66781. "base", "range", "projection", "near", "far", "texelSize",
  66782. "xViewport", "yViewport", "maxZ", "minZAspect"
  66783. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66784. this._ssaoPostProcess.onApply = function (effect) {
  66785. if (_this._firstUpdate) {
  66786. effect.setArray3("sampleSphere", _this._sampleSphere);
  66787. effect.setFloat("randTextureTiles", 4.0);
  66788. }
  66789. if (!_this._scene.activeCamera) {
  66790. return;
  66791. }
  66792. effect.setFloat("samplesFactor", 1 / _this.samples);
  66793. effect.setFloat("totalStrength", _this.totalStrength);
  66794. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66795. effect.setFloat("radius", _this.radius);
  66796. effect.setFloat("maxZ", _this.maxZ);
  66797. effect.setFloat("minZAspect", _this.minZAspect);
  66798. effect.setFloat("base", _this.base);
  66799. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66800. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66801. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66802. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66803. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66804. effect.setTexture("textureSampler", _this._depthTexture);
  66805. effect.setTexture("normalSampler", _this._normalTexture);
  66806. effect.setTexture("randomSampler", _this._randomTexture);
  66807. };
  66808. };
  66809. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66810. var _this = this;
  66811. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66812. this._ssaoCombinePostProcess.onApply = function (effect) {
  66813. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66814. };
  66815. };
  66816. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66817. var size = 512;
  66818. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66819. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66820. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66821. var context = this._randomTexture.getContext();
  66822. var rand = function (min, max) {
  66823. return Math.random() * (max - min) + min;
  66824. };
  66825. var randVector = BABYLON.Vector3.Zero();
  66826. for (var x = 0; x < size; x++) {
  66827. for (var y = 0; y < size; y++) {
  66828. randVector.x = rand(0.0, 1.0);
  66829. randVector.y = rand(0.0, 1.0);
  66830. randVector.z = 0.0;
  66831. randVector.normalize();
  66832. randVector.scaleInPlace(255);
  66833. randVector.x = Math.floor(randVector.x);
  66834. randVector.y = Math.floor(randVector.y);
  66835. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66836. context.fillRect(x, y, 1, 1);
  66837. }
  66838. }
  66839. this._randomTexture.update(false);
  66840. };
  66841. __decorate([
  66842. BABYLON.serialize()
  66843. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66844. __decorate([
  66845. BABYLON.serialize()
  66846. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66847. __decorate([
  66848. BABYLON.serialize()
  66849. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66850. __decorate([
  66851. BABYLON.serialize("samples")
  66852. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66853. __decorate([
  66854. BABYLON.serialize("expensiveBlur")
  66855. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66856. __decorate([
  66857. BABYLON.serialize()
  66858. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66859. __decorate([
  66860. BABYLON.serialize()
  66861. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66862. return SSAO2RenderingPipeline;
  66863. }(BABYLON.PostProcessRenderPipeline));
  66864. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66865. })(BABYLON || (BABYLON = {}));
  66866. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66867. // BABYLON.JS Chromatic Aberration GLSL Shader
  66868. // Author: Olivier Guyot
  66869. // Separates very slightly R, G and B colors on the edges of the screen
  66870. // Inspired by Francois Tarlier & Martins Upitis
  66871. var BABYLON;
  66872. (function (BABYLON) {
  66873. var LensRenderingPipeline = /** @class */ (function (_super) {
  66874. __extends(LensRenderingPipeline, _super);
  66875. /**
  66876. * @constructor
  66877. *
  66878. * Effect parameters are as follow:
  66879. * {
  66880. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66881. * edge_blur: number; // from 0 to x (1 for realism)
  66882. * distortion: number; // from 0 to x (1 for realism)
  66883. * grain_amount: number; // from 0 to 1
  66884. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66885. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66886. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66887. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66888. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66889. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66890. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66891. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66892. * }
  66893. * Note: if an effect parameter is unset, effect is disabled
  66894. *
  66895. * @param {string} name - The rendering pipeline name
  66896. * @param {object} parameters - An object containing all parameters (see above)
  66897. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66898. * @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)
  66899. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66900. */
  66901. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66902. if (ratio === void 0) { ratio = 1.0; }
  66903. var _this = _super.call(this, scene.getEngine(), name) || this;
  66904. // Lens effects can be of the following:
  66905. // - chromatic aberration (slight shift of RGB colors)
  66906. // - blur on the edge of the lens
  66907. // - lens distortion
  66908. // - depth-of-field blur & highlights enhancing
  66909. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66910. // - grain effect (noise or custom texture)
  66911. // Two additional texture samplers are needed:
  66912. // - depth map (for depth-of-field)
  66913. // - grain texture
  66914. /**
  66915. * The chromatic aberration PostProcess id in the pipeline
  66916. * @type {string}
  66917. */
  66918. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66919. /**
  66920. * The highlights enhancing PostProcess id in the pipeline
  66921. * @type {string}
  66922. */
  66923. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66924. /**
  66925. * The depth-of-field PostProcess id in the pipeline
  66926. * @type {string}
  66927. */
  66928. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66929. _this._scene = scene;
  66930. // Fetch texture samplers
  66931. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66932. if (parameters.grain_texture) {
  66933. _this._grainTexture = parameters.grain_texture;
  66934. }
  66935. else {
  66936. _this._createGrainTexture();
  66937. }
  66938. // save parameters
  66939. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66940. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66941. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66942. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66943. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66944. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66945. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66946. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66947. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66948. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66949. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66950. // Create effects
  66951. _this._createChromaticAberrationPostProcess(ratio);
  66952. _this._createHighlightsPostProcess(ratio);
  66953. _this._createDepthOfFieldPostProcess(ratio / 4);
  66954. // Set up pipeline
  66955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66958. if (_this._highlightsGain === -1) {
  66959. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66960. }
  66961. // Finish
  66962. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66963. if (cameras) {
  66964. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66965. }
  66966. return _this;
  66967. }
  66968. // public methods (self explanatory)
  66969. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66970. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66971. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66972. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66973. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66974. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66975. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66976. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66977. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66978. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66979. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66980. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66981. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66982. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66983. };
  66984. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66985. this._highlightsPostProcess.updateEffect();
  66986. };
  66987. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66988. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66989. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66990. this._highlightsGain = amount;
  66991. };
  66992. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66993. if (this._highlightsGain === -1) {
  66994. this._highlightsGain = 1.0;
  66995. }
  66996. this._highlightsThreshold = amount;
  66997. };
  66998. LensRenderingPipeline.prototype.disableHighlights = function () {
  66999. this._highlightsGain = -1;
  67000. };
  67001. /**
  67002. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67003. */
  67004. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67005. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67006. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67007. this._chromaticAberrationPostProcess = null;
  67008. this._highlightsPostProcess = null;
  67009. this._depthOfFieldPostProcess = null;
  67010. this._grainTexture.dispose();
  67011. if (disableDepthRender)
  67012. this._scene.disableDepthRenderer();
  67013. };
  67014. // colors shifting and distortion
  67015. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67016. var _this = this;
  67017. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67018. [], // samplers
  67019. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67020. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67021. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67022. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67023. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67024. effect.setFloat('radialIntensity', 1);
  67025. effect.setFloat2('direction', 17, 17);
  67026. effect.setFloat2('centerPosition', 0.5, 0.5);
  67027. };
  67028. };
  67029. // highlights enhancing
  67030. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67031. var _this = this;
  67032. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67033. [], // samplers
  67034. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67035. this._highlightsPostProcess.onApply = function (effect) {
  67036. effect.setFloat('gain', _this._highlightsGain);
  67037. effect.setFloat('threshold', _this._highlightsThreshold);
  67038. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67039. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67040. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67041. };
  67042. };
  67043. // colors shifting and distortion
  67044. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67045. var _this = this;
  67046. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67047. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67048. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67049. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67050. this._depthOfFieldPostProcess.onApply = function (effect) {
  67051. effect.setTexture("depthSampler", _this._depthTexture);
  67052. effect.setTexture("grainSampler", _this._grainTexture);
  67053. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67054. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67055. effect.setFloat('grain_amount', _this._grainAmount);
  67056. effect.setBool('blur_noise', _this._blurNoise);
  67057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67059. effect.setFloat('distortion', _this._distortion);
  67060. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67061. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67062. effect.setFloat('aperture', _this._dofAperture);
  67063. effect.setFloat('darken', _this._dofDarken);
  67064. effect.setFloat('edge_blur', _this._edgeBlur);
  67065. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67066. if (_this._scene.activeCamera) {
  67067. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67068. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67069. }
  67070. };
  67071. };
  67072. // creates a black and white random noise texture, 512x512
  67073. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67074. var size = 512;
  67075. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67076. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67077. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67078. var context = this._grainTexture.getContext();
  67079. var rand = function (min, max) {
  67080. return Math.random() * (max - min) + min;
  67081. };
  67082. var value;
  67083. for (var x = 0; x < size; x++) {
  67084. for (var y = 0; y < size; y++) {
  67085. value = Math.floor(rand(0.42, 0.58) * 255);
  67086. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67087. context.fillRect(x, y, 1, 1);
  67088. }
  67089. }
  67090. this._grainTexture.update(false);
  67091. };
  67092. return LensRenderingPipeline;
  67093. }(BABYLON.PostProcessRenderPipeline));
  67094. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67095. })(BABYLON || (BABYLON = {}));
  67096. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67097. var BABYLON;
  67098. (function (BABYLON) {
  67099. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67100. __extends(StandardRenderingPipeline, _super);
  67101. /**
  67102. * @constructor
  67103. * @param {string} name - The rendering pipeline name
  67104. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67105. * @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)
  67106. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67107. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67108. */
  67109. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67110. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67111. var _this = _super.call(this, scene.getEngine(), name) || this;
  67112. _this.downSampleX4PostProcess = null;
  67113. _this.brightPassPostProcess = null;
  67114. _this.blurHPostProcesses = [];
  67115. _this.blurVPostProcesses = [];
  67116. _this.textureAdderPostProcess = null;
  67117. _this.volumetricLightPostProcess = null;
  67118. _this.volumetricLightSmoothXPostProcess = null;
  67119. _this.volumetricLightSmoothYPostProcess = null;
  67120. _this.volumetricLightMergePostProces = null;
  67121. _this.volumetricLightFinalPostProcess = null;
  67122. _this.luminancePostProcess = null;
  67123. _this.luminanceDownSamplePostProcesses = [];
  67124. _this.hdrPostProcess = null;
  67125. _this.textureAdderFinalPostProcess = null;
  67126. _this.lensFlareFinalPostProcess = null;
  67127. _this.hdrFinalPostProcess = null;
  67128. _this.lensFlarePostProcess = null;
  67129. _this.lensFlareComposePostProcess = null;
  67130. _this.motionBlurPostProcess = null;
  67131. _this.depthOfFieldPostProcess = null;
  67132. // Values
  67133. _this.brightThreshold = 1.0;
  67134. _this.blurWidth = 512.0;
  67135. _this.horizontalBlur = false;
  67136. _this.exposure = 1.0;
  67137. _this.lensTexture = null;
  67138. _this.volumetricLightCoefficient = 0.2;
  67139. _this.volumetricLightPower = 4.0;
  67140. _this.volumetricLightBlurScale = 64.0;
  67141. _this.sourceLight = null;
  67142. _this.hdrMinimumLuminance = 1.0;
  67143. _this.hdrDecreaseRate = 0.5;
  67144. _this.hdrIncreaseRate = 0.5;
  67145. _this.lensColorTexture = null;
  67146. _this.lensFlareStrength = 20.0;
  67147. _this.lensFlareGhostDispersal = 1.4;
  67148. _this.lensFlareHaloWidth = 0.7;
  67149. _this.lensFlareDistortionStrength = 16.0;
  67150. _this.lensStarTexture = null;
  67151. _this.lensFlareDirtTexture = null;
  67152. _this.depthOfFieldDistance = 10.0;
  67153. _this.depthOfFieldBlurWidth = 64.0;
  67154. _this.motionStrength = 1.0;
  67155. // IAnimatable
  67156. _this.animations = [];
  67157. _this._currentDepthOfFieldSource = null;
  67158. _this._hdrCurrentLuminance = 1.0;
  67159. // Getters and setters
  67160. _this._bloomEnabled = true;
  67161. _this._depthOfFieldEnabled = false;
  67162. _this._vlsEnabled = false;
  67163. _this._lensFlareEnabled = false;
  67164. _this._hdrEnabled = false;
  67165. _this._motionBlurEnabled = false;
  67166. _this._motionBlurSamples = 64.0;
  67167. _this._volumetricLightStepsCount = 50.0;
  67168. _this._cameras = cameras || [];
  67169. // Initialize
  67170. _this._scene = scene;
  67171. _this._basePostProcess = originalPostProcess;
  67172. _this._ratio = ratio;
  67173. // Misc
  67174. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67175. // Finish
  67176. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67177. _this._buildPipeline();
  67178. return _this;
  67179. }
  67180. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67181. get: function () {
  67182. return this._bloomEnabled;
  67183. },
  67184. set: function (enabled) {
  67185. if (this._bloomEnabled === enabled) {
  67186. return;
  67187. }
  67188. this._bloomEnabled = enabled;
  67189. this._buildPipeline();
  67190. },
  67191. enumerable: true,
  67192. configurable: true
  67193. });
  67194. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67195. get: function () {
  67196. return this._depthOfFieldEnabled;
  67197. },
  67198. set: function (enabled) {
  67199. if (this._depthOfFieldEnabled === enabled) {
  67200. return;
  67201. }
  67202. this._depthOfFieldEnabled = enabled;
  67203. this._buildPipeline();
  67204. },
  67205. enumerable: true,
  67206. configurable: true
  67207. });
  67208. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67209. get: function () {
  67210. return this._lensFlareEnabled;
  67211. },
  67212. set: function (enabled) {
  67213. if (this._lensFlareEnabled === enabled) {
  67214. return;
  67215. }
  67216. this._lensFlareEnabled = enabled;
  67217. this._buildPipeline();
  67218. },
  67219. enumerable: true,
  67220. configurable: true
  67221. });
  67222. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67223. get: function () {
  67224. return this._hdrEnabled;
  67225. },
  67226. set: function (enabled) {
  67227. if (this._hdrEnabled === enabled) {
  67228. return;
  67229. }
  67230. this._hdrEnabled = enabled;
  67231. this._buildPipeline();
  67232. },
  67233. enumerable: true,
  67234. configurable: true
  67235. });
  67236. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67237. get: function () {
  67238. return this._vlsEnabled;
  67239. },
  67240. set: function (enabled) {
  67241. if (this._vlsEnabled === enabled) {
  67242. return;
  67243. }
  67244. if (enabled) {
  67245. var geometry = this._scene.enableGeometryBufferRenderer();
  67246. if (!geometry) {
  67247. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67248. return;
  67249. }
  67250. }
  67251. this._vlsEnabled = enabled;
  67252. this._buildPipeline();
  67253. },
  67254. enumerable: true,
  67255. configurable: true
  67256. });
  67257. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67258. get: function () {
  67259. return this._motionBlurEnabled;
  67260. },
  67261. set: function (enabled) {
  67262. if (this._motionBlurEnabled === enabled) {
  67263. return;
  67264. }
  67265. this._motionBlurEnabled = enabled;
  67266. this._buildPipeline();
  67267. },
  67268. enumerable: true,
  67269. configurable: true
  67270. });
  67271. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67272. get: function () {
  67273. return this._volumetricLightStepsCount;
  67274. },
  67275. set: function (count) {
  67276. if (this.volumetricLightPostProcess) {
  67277. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67278. }
  67279. this._volumetricLightStepsCount = count;
  67280. },
  67281. enumerable: true,
  67282. configurable: true
  67283. });
  67284. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67285. get: function () {
  67286. return this._motionBlurSamples;
  67287. },
  67288. set: function (samples) {
  67289. if (this.motionBlurPostProcess) {
  67290. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67291. }
  67292. this._motionBlurSamples = samples;
  67293. },
  67294. enumerable: true,
  67295. configurable: true
  67296. });
  67297. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67298. var _this = this;
  67299. var ratio = this._ratio;
  67300. var scene = this._scene;
  67301. this._disposePostProcesses();
  67302. this._reset();
  67303. // Create pass post-process
  67304. if (!this._basePostProcess) {
  67305. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67306. this.originalPostProcess.onApply = function (effect) {
  67307. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67308. };
  67309. }
  67310. else {
  67311. this.originalPostProcess = this._basePostProcess;
  67312. }
  67313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67314. this._currentDepthOfFieldSource = this.originalPostProcess;
  67315. if (this._vlsEnabled) {
  67316. // Create volumetric light
  67317. this._createVolumetricLightPostProcess(scene, ratio);
  67318. // Create volumetric light final post-process
  67319. 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);
  67320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67321. }
  67322. if (this._bloomEnabled) {
  67323. // Create down sample X4 post-process
  67324. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67325. // Create bright pass post-process
  67326. this._createBrightPassPostProcess(scene, ratio / 2);
  67327. // Create gaussian blur post-processes (down sampling blurs)
  67328. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67329. // Create texture adder post-process
  67330. this._createTextureAdderPostProcess(scene, ratio);
  67331. // Create depth-of-field source post-process
  67332. 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);
  67333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67334. }
  67335. if (this._lensFlareEnabled) {
  67336. // Create lens flare post-process
  67337. this._createLensFlarePostProcess(scene, ratio);
  67338. // Create depth-of-field source post-process post lens-flare and disable it now
  67339. 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);
  67340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67341. }
  67342. if (this._hdrEnabled) {
  67343. // Create luminance
  67344. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67345. // Create HDR
  67346. this._createHdrPostProcess(scene, ratio);
  67347. // Create depth-of-field source post-process post hdr and disable it now
  67348. 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);
  67349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67350. }
  67351. if (this._depthOfFieldEnabled) {
  67352. // Create gaussian blur used by depth-of-field
  67353. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67354. // Create depth-of-field post-process
  67355. this._createDepthOfFieldPostProcess(scene, ratio);
  67356. }
  67357. if (this._motionBlurEnabled) {
  67358. // Create motion blur post-process
  67359. this._createMotionBlurPostProcess(scene, ratio);
  67360. }
  67361. if (this._cameras !== null) {
  67362. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67363. }
  67364. };
  67365. // Down Sample X4 Post-Processs
  67366. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67367. var _this = this;
  67368. var downSampleX4Offsets = new Array(32);
  67369. 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);
  67370. this.downSampleX4PostProcess.onApply = function (effect) {
  67371. var id = 0;
  67372. var width = _this.downSampleX4PostProcess.width;
  67373. var height = _this.downSampleX4PostProcess.height;
  67374. for (var i = -2; i < 2; i++) {
  67375. for (var j = -2; j < 2; j++) {
  67376. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67377. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67378. id += 2;
  67379. }
  67380. }
  67381. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67382. };
  67383. // Add to pipeline
  67384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67385. };
  67386. // Brightpass Post-Process
  67387. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67388. var _this = this;
  67389. var brightOffsets = new Array(8);
  67390. 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);
  67391. this.brightPassPostProcess.onApply = function (effect) {
  67392. var sU = (1.0 / _this.brightPassPostProcess.width);
  67393. var sV = (1.0 / _this.brightPassPostProcess.height);
  67394. brightOffsets[0] = -0.5 * sU;
  67395. brightOffsets[1] = 0.5 * sV;
  67396. brightOffsets[2] = 0.5 * sU;
  67397. brightOffsets[3] = 0.5 * sV;
  67398. brightOffsets[4] = -0.5 * sU;
  67399. brightOffsets[5] = -0.5 * sV;
  67400. brightOffsets[6] = 0.5 * sU;
  67401. brightOffsets[7] = -0.5 * sV;
  67402. effect.setArray2("dsOffsets", brightOffsets);
  67403. effect.setFloat("brightThreshold", _this.brightThreshold);
  67404. };
  67405. // Add to pipeline
  67406. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67407. };
  67408. // Create blur H&V post-processes
  67409. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67410. var _this = this;
  67411. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67412. var engine = scene.getEngine();
  67413. 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);
  67414. 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);
  67415. blurX.onActivateObservable.add(function () {
  67416. var dw = blurX.width / engine.getRenderWidth();
  67417. blurX.kernel = _this[blurWidthKey] * dw;
  67418. });
  67419. blurY.onActivateObservable.add(function () {
  67420. var dw = blurY.height / engine.getRenderHeight();
  67421. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67422. });
  67423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67425. this.blurHPostProcesses.push(blurX);
  67426. this.blurVPostProcesses.push(blurY);
  67427. };
  67428. // Create texture adder post-process
  67429. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67430. var _this = this;
  67431. 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);
  67432. this.textureAdderPostProcess.onApply = function (effect) {
  67433. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67434. effect.setTexture("lensSampler", _this.lensTexture);
  67435. effect.setFloat("exposure", _this.exposure);
  67436. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67437. };
  67438. // Add to pipeline
  67439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67440. };
  67441. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67442. var _this = this;
  67443. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67444. geometryRenderer.enablePosition = true;
  67445. var geometry = geometryRenderer.getGBuffer();
  67446. // Base post-process
  67447. 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));
  67448. var depthValues = BABYLON.Vector2.Zero();
  67449. this.volumetricLightPostProcess.onApply = function (effect) {
  67450. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67451. var generator = _this.sourceLight.getShadowGenerator();
  67452. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67453. effect.setTexture("positionSampler", geometry.textures[2]);
  67454. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67455. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67456. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67457. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67458. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67459. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67460. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67461. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67462. effect.setVector2("depthValues", depthValues);
  67463. }
  67464. };
  67465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67466. // Smooth
  67467. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67468. // Merge
  67469. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67470. this.volumetricLightMergePostProces.onApply = function (effect) {
  67471. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67472. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67473. };
  67474. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67475. };
  67476. // Create luminance
  67477. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67478. var _this = this;
  67479. // Create luminance
  67480. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67481. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67482. var offsets = [];
  67483. this.luminancePostProcess.onApply = function (effect) {
  67484. var sU = (1.0 / _this.luminancePostProcess.width);
  67485. var sV = (1.0 / _this.luminancePostProcess.height);
  67486. offsets[0] = -0.5 * sU;
  67487. offsets[1] = 0.5 * sV;
  67488. offsets[2] = 0.5 * sU;
  67489. offsets[3] = 0.5 * sV;
  67490. offsets[4] = -0.5 * sU;
  67491. offsets[5] = -0.5 * sV;
  67492. offsets[6] = 0.5 * sU;
  67493. offsets[7] = -0.5 * sV;
  67494. effect.setArray2("lumOffsets", offsets);
  67495. };
  67496. // Add to pipeline
  67497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67498. // Create down sample luminance
  67499. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67500. var size = Math.pow(3, i);
  67501. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67502. if (i === 0) {
  67503. defines += "#define FINAL_DOWN_SAMPLER";
  67504. }
  67505. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67506. this.luminanceDownSamplePostProcesses.push(postProcess);
  67507. }
  67508. // Create callbacks and add effects
  67509. var lastLuminance = this.luminancePostProcess;
  67510. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67511. var downSampleOffsets = new Array(18);
  67512. pp.onApply = function (effect) {
  67513. if (!lastLuminance) {
  67514. return;
  67515. }
  67516. var id = 0;
  67517. for (var x = -1; x < 2; x++) {
  67518. for (var y = -1; y < 2; y++) {
  67519. downSampleOffsets[id] = x / lastLuminance.width;
  67520. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67521. id += 2;
  67522. }
  67523. }
  67524. effect.setArray2("dsOffsets", downSampleOffsets);
  67525. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67526. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67527. lastLuminance = _this.luminancePostProcess;
  67528. }
  67529. else {
  67530. lastLuminance = pp;
  67531. }
  67532. };
  67533. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67534. pp.onAfterRender = function (effect) {
  67535. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67536. 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);
  67537. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67538. };
  67539. }
  67540. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67541. });
  67542. };
  67543. // Create HDR post-process
  67544. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67545. var _this = this;
  67546. 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);
  67547. var outputLiminance = 1;
  67548. var time = 0;
  67549. var lastTime = 0;
  67550. this.hdrPostProcess.onApply = function (effect) {
  67551. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67552. time += scene.getEngine().getDeltaTime();
  67553. if (outputLiminance < 0) {
  67554. outputLiminance = _this._hdrCurrentLuminance;
  67555. }
  67556. else {
  67557. var dt = (lastTime - time) / 1000.0;
  67558. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67559. outputLiminance += _this.hdrDecreaseRate * dt;
  67560. }
  67561. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67562. outputLiminance -= _this.hdrIncreaseRate * dt;
  67563. }
  67564. else {
  67565. outputLiminance = _this._hdrCurrentLuminance;
  67566. }
  67567. }
  67568. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67569. effect.setFloat("averageLuminance", outputLiminance);
  67570. lastTime = time;
  67571. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67572. };
  67573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67574. };
  67575. // Create lens flare post-process
  67576. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67577. var _this = this;
  67578. 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);
  67579. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67580. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67581. 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);
  67582. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67583. var resolution = new BABYLON.Vector2(0, 0);
  67584. // Lens flare
  67585. this.lensFlarePostProcess.onApply = function (effect) {
  67586. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67587. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67588. effect.setFloat("strength", _this.lensFlareStrength);
  67589. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67590. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67591. // Shift
  67592. resolution.x = _this.lensFlarePostProcess.width;
  67593. resolution.y = _this.lensFlarePostProcess.height;
  67594. effect.setVector2("resolution", resolution);
  67595. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67596. };
  67597. // Compose
  67598. 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);
  67599. 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);
  67600. this.lensFlareComposePostProcess.onApply = function (effect) {
  67601. if (!_this._scene.activeCamera) {
  67602. return;
  67603. }
  67604. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67605. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67606. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67607. // Lens start rotation matrix
  67608. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67609. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67610. 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));
  67611. camRot *= 4.0;
  67612. 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);
  67613. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67614. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67615. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67616. };
  67617. };
  67618. // Create depth-of-field post-process
  67619. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67620. var _this = this;
  67621. 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);
  67622. this.depthOfFieldPostProcess.onApply = function (effect) {
  67623. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67624. effect.setTexture("depthSampler", _this._getDepthTexture());
  67625. effect.setFloat("distance", _this.depthOfFieldDistance);
  67626. };
  67627. // Add to pipeline
  67628. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67629. };
  67630. // Create motion blur post-process
  67631. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67632. var _this = this;
  67633. 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);
  67634. var motionScale = 0;
  67635. var prevViewProjection = BABYLON.Matrix.Identity();
  67636. var invViewProjection = BABYLON.Matrix.Identity();
  67637. var viewProjection = BABYLON.Matrix.Identity();
  67638. var screenSize = BABYLON.Vector2.Zero();
  67639. this.motionBlurPostProcess.onApply = function (effect) {
  67640. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67641. viewProjection.invertToRef(invViewProjection);
  67642. effect.setMatrix("inverseViewProjection", invViewProjection);
  67643. effect.setMatrix("prevViewProjection", prevViewProjection);
  67644. prevViewProjection = viewProjection;
  67645. screenSize.x = _this.motionBlurPostProcess.width;
  67646. screenSize.y = _this.motionBlurPostProcess.height;
  67647. effect.setVector2("screenSize", screenSize);
  67648. motionScale = scene.getEngine().getFps() / 60.0;
  67649. effect.setFloat("motionScale", motionScale);
  67650. effect.setFloat("motionStrength", _this.motionStrength);
  67651. effect.setTexture("depthSampler", _this._getDepthTexture());
  67652. };
  67653. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67654. };
  67655. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67656. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67657. var renderer = this._scene.enableGeometryBufferRenderer();
  67658. return renderer.getGBuffer().textures[0];
  67659. }
  67660. return this._scene.enableDepthRenderer().getDepthMap();
  67661. };
  67662. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67663. for (var i = 0; i < this._cameras.length; i++) {
  67664. var camera = this._cameras[i];
  67665. if (this.originalPostProcess) {
  67666. this.originalPostProcess.dispose(camera);
  67667. }
  67668. if (this.downSampleX4PostProcess) {
  67669. this.downSampleX4PostProcess.dispose(camera);
  67670. }
  67671. if (this.brightPassPostProcess) {
  67672. this.brightPassPostProcess.dispose(camera);
  67673. }
  67674. if (this.textureAdderPostProcess) {
  67675. this.textureAdderPostProcess.dispose(camera);
  67676. }
  67677. if (this.textureAdderFinalPostProcess) {
  67678. this.textureAdderFinalPostProcess.dispose(camera);
  67679. }
  67680. if (this.volumetricLightPostProcess) {
  67681. this.volumetricLightPostProcess.dispose(camera);
  67682. }
  67683. if (this.volumetricLightSmoothXPostProcess) {
  67684. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67685. }
  67686. if (this.volumetricLightSmoothYPostProcess) {
  67687. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67688. }
  67689. if (this.volumetricLightMergePostProces) {
  67690. this.volumetricLightMergePostProces.dispose(camera);
  67691. }
  67692. if (this.volumetricLightFinalPostProcess) {
  67693. this.volumetricLightFinalPostProcess.dispose(camera);
  67694. }
  67695. if (this.lensFlarePostProcess) {
  67696. this.lensFlarePostProcess.dispose(camera);
  67697. }
  67698. if (this.lensFlareComposePostProcess) {
  67699. this.lensFlareComposePostProcess.dispose(camera);
  67700. }
  67701. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67702. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67703. }
  67704. if (this.luminancePostProcess) {
  67705. this.luminancePostProcess.dispose(camera);
  67706. }
  67707. if (this.hdrPostProcess) {
  67708. this.hdrPostProcess.dispose(camera);
  67709. }
  67710. if (this.hdrFinalPostProcess) {
  67711. this.hdrFinalPostProcess.dispose(camera);
  67712. }
  67713. if (this.depthOfFieldPostProcess) {
  67714. this.depthOfFieldPostProcess.dispose(camera);
  67715. }
  67716. if (this.motionBlurPostProcess) {
  67717. this.motionBlurPostProcess.dispose(camera);
  67718. }
  67719. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67720. this.blurHPostProcesses[j].dispose(camera);
  67721. }
  67722. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67723. this.blurVPostProcesses[j].dispose(camera);
  67724. }
  67725. }
  67726. this.originalPostProcess = null;
  67727. this.downSampleX4PostProcess = null;
  67728. this.brightPassPostProcess = null;
  67729. this.textureAdderPostProcess = null;
  67730. this.textureAdderFinalPostProcess = null;
  67731. this.volumetricLightPostProcess = null;
  67732. this.volumetricLightSmoothXPostProcess = null;
  67733. this.volumetricLightSmoothYPostProcess = null;
  67734. this.volumetricLightMergePostProces = null;
  67735. this.volumetricLightFinalPostProcess = null;
  67736. this.lensFlarePostProcess = null;
  67737. this.lensFlareComposePostProcess = null;
  67738. this.luminancePostProcess = null;
  67739. this.hdrPostProcess = null;
  67740. this.hdrFinalPostProcess = null;
  67741. this.depthOfFieldPostProcess = null;
  67742. this.motionBlurPostProcess = null;
  67743. this.luminanceDownSamplePostProcesses = [];
  67744. this.blurHPostProcesses = [];
  67745. this.blurVPostProcesses = [];
  67746. };
  67747. // Dispose
  67748. StandardRenderingPipeline.prototype.dispose = function () {
  67749. this._disposePostProcesses();
  67750. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67751. _super.prototype.dispose.call(this);
  67752. };
  67753. // Serialize rendering pipeline
  67754. StandardRenderingPipeline.prototype.serialize = function () {
  67755. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67756. serializationObject.customType = "StandardRenderingPipeline";
  67757. return serializationObject;
  67758. };
  67759. /**
  67760. * Static members
  67761. */
  67762. // Parse serialized pipeline
  67763. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67764. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67765. };
  67766. // Luminance steps
  67767. StandardRenderingPipeline.LuminanceSteps = 6;
  67768. __decorate([
  67769. BABYLON.serialize()
  67770. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67771. __decorate([
  67772. BABYLON.serialize()
  67773. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67774. __decorate([
  67775. BABYLON.serialize()
  67776. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67777. __decorate([
  67778. BABYLON.serialize()
  67779. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67780. __decorate([
  67781. BABYLON.serializeAsTexture("lensTexture")
  67782. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67783. __decorate([
  67784. BABYLON.serialize()
  67785. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67786. __decorate([
  67787. BABYLON.serialize()
  67788. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67789. __decorate([
  67790. BABYLON.serialize()
  67791. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67792. __decorate([
  67793. BABYLON.serialize()
  67794. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67795. __decorate([
  67796. BABYLON.serialize()
  67797. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67798. __decorate([
  67799. BABYLON.serialize()
  67800. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67801. __decorate([
  67802. BABYLON.serializeAsTexture("lensColorTexture")
  67803. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67804. __decorate([
  67805. BABYLON.serialize()
  67806. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67807. __decorate([
  67808. BABYLON.serialize()
  67809. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67810. __decorate([
  67811. BABYLON.serialize()
  67812. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67813. __decorate([
  67814. BABYLON.serialize()
  67815. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67816. __decorate([
  67817. BABYLON.serializeAsTexture("lensStarTexture")
  67818. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67819. __decorate([
  67820. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67821. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67822. __decorate([
  67823. BABYLON.serialize()
  67824. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67825. __decorate([
  67826. BABYLON.serialize()
  67827. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67828. __decorate([
  67829. BABYLON.serialize()
  67830. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67831. __decorate([
  67832. BABYLON.serialize()
  67833. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67834. __decorate([
  67835. BABYLON.serialize()
  67836. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67837. __decorate([
  67838. BABYLON.serialize()
  67839. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67840. __decorate([
  67841. BABYLON.serialize()
  67842. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67843. __decorate([
  67844. BABYLON.serialize()
  67845. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67846. __decorate([
  67847. BABYLON.serialize()
  67848. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67849. __decorate([
  67850. BABYLON.serialize()
  67851. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67852. __decorate([
  67853. BABYLON.serialize()
  67854. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67855. __decorate([
  67856. BABYLON.serialize()
  67857. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67858. return StandardRenderingPipeline;
  67859. }(BABYLON.PostProcessRenderPipeline));
  67860. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67861. })(BABYLON || (BABYLON = {}));
  67862. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67863. var BABYLON;
  67864. (function (BABYLON) {
  67865. var FxaaPostProcess = /** @class */ (function (_super) {
  67866. __extends(FxaaPostProcess, _super);
  67867. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67868. if (camera === void 0) { camera = null; }
  67869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67870. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67871. _this.onApplyObservable.add(function (effect) {
  67872. var texelSize = _this.texelSize;
  67873. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67874. });
  67875. return _this;
  67876. }
  67877. return FxaaPostProcess;
  67878. }(BABYLON.PostProcess));
  67879. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67880. })(BABYLON || (BABYLON = {}));
  67881. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67882. var BABYLON;
  67883. (function (BABYLON) {
  67884. /**
  67885. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  67886. */
  67887. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  67888. __extends(ChromaticAberrationPostProcess, _super);
  67889. /**
  67890. * Creates a new instance of @see ChromaticAberrationPostProcess
  67891. * @param name The name of the effect.
  67892. * @param screenWidth The width of the screen to apply the effect on.
  67893. * @param screenHeight The height of the screen to apply the effect on.
  67894. * @param options The required width/height ratio to downsize to before computing the render pass.
  67895. * @param camera The camera to apply the render pass to.
  67896. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67897. * @param engine The engine which the post process will be applied. (default: current engine)
  67898. * @param reusable If the post process can be reused on the same frame. (default: false)
  67899. * @param textureType Type of textures used when performing the post process. (default: 0)
  67900. * @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)
  67901. */
  67902. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67904. if (blockCompilation === void 0) { blockCompilation = false; }
  67905. 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;
  67906. /**
  67907. * The amount of seperation of rgb channels (default: 0)
  67908. */
  67909. _this.aberrationAmount = 0;
  67910. /**
  67911. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  67912. */
  67913. _this.radialIntensity = 0;
  67914. /**
  67915. * 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))
  67916. */
  67917. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  67918. /**
  67919. * 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))
  67920. */
  67921. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  67922. _this.onApplyObservable.add(function (effect) {
  67923. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  67924. effect.setFloat('screen_width', screenWidth);
  67925. effect.setFloat('screen_height', screenHeight);
  67926. effect.setFloat('radialIntensity', _this.radialIntensity);
  67927. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  67928. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  67929. });
  67930. return _this;
  67931. }
  67932. return ChromaticAberrationPostProcess;
  67933. }(BABYLON.PostProcess));
  67934. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  67935. })(BABYLON || (BABYLON = {}));
  67936. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  67937. var BABYLON;
  67938. (function (BABYLON) {
  67939. /**
  67940. * The SharpenPostProcess applies a sharpen kernel to every pixel
  67941. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67942. */
  67943. var SharpenPostProcess = /** @class */ (function (_super) {
  67944. __extends(SharpenPostProcess, _super);
  67945. /**
  67946. * Creates a new instance of @see ConvolutionPostProcess
  67947. * @param name The name of the effect.
  67948. * @param options The required width/height ratio to downsize to before computing the render pass.
  67949. * @param camera The camera to apply the render pass to.
  67950. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67951. * @param engine The engine which the post process will be applied. (default: current engine)
  67952. * @param reusable If the post process can be reused on the same frame. (default: false)
  67953. * @param textureType Type of textures used when performing the post process. (default: 0)
  67954. * @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)
  67955. */
  67956. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67958. if (blockCompilation === void 0) { blockCompilation = false; }
  67959. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67960. /**
  67961. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  67962. */
  67963. _this.colorAmount = 1.0;
  67964. /**
  67965. * How much sharpness should be applied (default: 0.3)
  67966. */
  67967. _this.edgeAmount = 0.3;
  67968. _this.onApply = function (effect) {
  67969. effect.setFloat2("screenSize", _this.width, _this.height);
  67970. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  67971. };
  67972. return _this;
  67973. }
  67974. return SharpenPostProcess;
  67975. }(BABYLON.PostProcess));
  67976. BABYLON.SharpenPostProcess = SharpenPostProcess;
  67977. })(BABYLON || (BABYLON = {}));
  67978. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  67979. var BABYLON;
  67980. (function (BABYLON) {
  67981. /**
  67982. * The Blur Post Process which blurs an image based on a kernel and direction.
  67983. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  67984. */
  67985. var BlurPostProcess = /** @class */ (function (_super) {
  67986. __extends(BlurPostProcess, _super);
  67987. /**
  67988. * Creates a new instance of @see BlurPostProcess
  67989. * @param name The name of the effect.
  67990. * @param direction The direction in which to blur the image.
  67991. * @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.
  67992. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67993. * @param camera The camera to apply the render pass to.
  67994. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67995. * @param engine The engine which the post process will be applied. (default: current engine)
  67996. * @param reusable If the post process can be reused on the same frame. (default: false)
  67997. * @param textureType Type of textures used when performing the post process. (default: 0)
  67998. * @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)
  67999. */
  68000. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68003. if (defines === void 0) { defines = ""; }
  68004. if (blockCompilation === void 0) { blockCompilation = false; }
  68005. 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;
  68006. _this.direction = direction;
  68007. _this.blockCompilation = blockCompilation;
  68008. _this._packedFloat = false;
  68009. _this._staticDefines = "";
  68010. _this._staticDefines = defines;
  68011. _this.onApplyObservable.add(function (effect) {
  68012. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68013. });
  68014. _this.kernel = kernel;
  68015. return _this;
  68016. }
  68017. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68018. /**
  68019. * Gets the length in pixels of the blur sample region
  68020. */
  68021. get: function () {
  68022. return this._idealKernel;
  68023. },
  68024. /**
  68025. * Sets the length in pixels of the blur sample region
  68026. */
  68027. set: function (v) {
  68028. if (this._idealKernel === v) {
  68029. return;
  68030. }
  68031. v = Math.max(v, 1);
  68032. this._idealKernel = v;
  68033. this._kernel = this._nearestBestKernel(v);
  68034. if (!this.blockCompilation) {
  68035. this._updateParameters();
  68036. }
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68042. /**
  68043. * Gets wether or not the blur is unpacking/repacking floats
  68044. */
  68045. get: function () {
  68046. return this._packedFloat;
  68047. },
  68048. /**
  68049. * Sets wether or not the blur needs to unpack/repack floats
  68050. */
  68051. set: function (v) {
  68052. if (this._packedFloat === v) {
  68053. return;
  68054. }
  68055. this._packedFloat = v;
  68056. if (!this.blockCompilation) {
  68057. this._updateParameters();
  68058. }
  68059. },
  68060. enumerable: true,
  68061. configurable: true
  68062. });
  68063. /**
  68064. * Updates the effect with the current post process compile time values and recompiles the shader.
  68065. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68066. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68067. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68068. * @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
  68069. * @param onCompiled Called when the shader has been compiled.
  68070. * @param onError Called if there is an error when compiling a shader.
  68071. */
  68072. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68073. if (defines === void 0) { defines = null; }
  68074. if (uniforms === void 0) { uniforms = null; }
  68075. if (samplers === void 0) { samplers = null; }
  68076. this._updateParameters(onCompiled, onError);
  68077. };
  68078. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68079. // Generate sampling offsets and weights
  68080. var N = this._kernel;
  68081. var centerIndex = (N - 1) / 2;
  68082. // Generate Gaussian sampling weights over kernel
  68083. var offsets = [];
  68084. var weights = [];
  68085. var totalWeight = 0;
  68086. for (var i = 0; i < N; i++) {
  68087. var u = i / (N - 1);
  68088. var w = this._gaussianWeight(u * 2.0 - 1);
  68089. offsets[i] = (i - centerIndex);
  68090. weights[i] = w;
  68091. totalWeight += w;
  68092. }
  68093. // Normalize weights
  68094. for (var i = 0; i < weights.length; i++) {
  68095. weights[i] /= totalWeight;
  68096. }
  68097. // Optimize: combine samples to take advantage of hardware linear sampling
  68098. // Walk from left to center, combining pairs (symmetrically)
  68099. var linearSamplingWeights = [];
  68100. var linearSamplingOffsets = [];
  68101. var linearSamplingMap = [];
  68102. for (var i = 0; i <= centerIndex; i += 2) {
  68103. var j = Math.min(i + 1, Math.floor(centerIndex));
  68104. var singleCenterSample = i === j;
  68105. if (singleCenterSample) {
  68106. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68107. }
  68108. else {
  68109. var sharedCell = j === centerIndex;
  68110. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68111. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68112. if (offsetLinear === 0) {
  68113. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68114. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68115. }
  68116. else {
  68117. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68118. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68119. }
  68120. }
  68121. }
  68122. for (var i = 0; i < linearSamplingMap.length; i++) {
  68123. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68124. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68125. }
  68126. // Replace with optimized
  68127. offsets = linearSamplingOffsets;
  68128. weights = linearSamplingWeights;
  68129. // Generate shaders
  68130. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68131. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68132. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68133. var defines = "";
  68134. defines += this._staticDefines;
  68135. for (var i = 0; i < varyingCount; i++) {
  68136. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68137. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68138. }
  68139. var depCount = 0;
  68140. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68141. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68142. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68143. depCount++;
  68144. }
  68145. if (this.packedFloat) {
  68146. defines += "#define PACKEDFLOAT 1";
  68147. }
  68148. _super.prototype.updateEffect.call(this, defines, null, null, {
  68149. varyingCount: varyingCount,
  68150. depCount: depCount
  68151. }, onCompiled, onError);
  68152. };
  68153. /**
  68154. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68155. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68156. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68157. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68158. * The gaps between physical kernels are compensated for in the weighting of the samples
  68159. * @param idealKernel Ideal blur kernel.
  68160. * @return Nearest best kernel.
  68161. */
  68162. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68163. var v = Math.round(idealKernel);
  68164. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68165. var k = _a[_i];
  68166. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68167. return Math.max(k, 3);
  68168. }
  68169. }
  68170. return Math.max(v, 3);
  68171. };
  68172. /**
  68173. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68174. * @param x The point on the Gaussian distribution to sample.
  68175. * @return the value of the Gaussian function at x.
  68176. */
  68177. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68178. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68179. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68180. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68181. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68182. // truncated at around 1.3% of peak strength.
  68183. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68184. var sigma = (1 / 3);
  68185. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68186. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68187. var weight = (1.0 / denominator) * Math.exp(exponent);
  68188. return weight;
  68189. };
  68190. /**
  68191. * Generates a string that can be used as a floating point number in GLSL.
  68192. * @param x Value to print.
  68193. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68194. * @return GLSL float string.
  68195. */
  68196. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68197. if (decimalFigures === void 0) { decimalFigures = 8; }
  68198. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68199. };
  68200. return BlurPostProcess;
  68201. }(BABYLON.PostProcess));
  68202. BABYLON.BlurPostProcess = BlurPostProcess;
  68203. })(BABYLON || (BABYLON = {}));
  68204. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68205. var BABYLON;
  68206. (function (BABYLON) {
  68207. /**
  68208. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68209. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68210. * based on samples that have a large difference in distance than the center pixel.
  68211. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68212. */
  68213. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68214. __extends(DepthOfFieldBlurPostProcess, _super);
  68215. /**
  68216. * Creates a new instance of @see CircleOfConfusionPostProcess
  68217. * @param name The name of the effect.
  68218. * @param scene The scene the effect belongs to.
  68219. * @param direction The direction the blur should be applied.
  68220. * @param kernel The size of the kernel used to blur.
  68221. * @param options The required width/height ratio to downsize to before computing the render pass.
  68222. * @param camera The camera to apply the render pass to.
  68223. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68224. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68225. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68226. * @param engine The engine which the post process will be applied. (default: current engine)
  68227. * @param reusable If the post process can be reused on the same frame. (default: false)
  68228. * @param textureType Type of textures used when performing the post process. (default: 0)
  68229. * @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)
  68230. */
  68231. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68232. if (imageToBlur === void 0) { imageToBlur = null; }
  68233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68234. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68235. if (blockCompilation === void 0) { blockCompilation = false; }
  68236. 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;
  68237. _this.direction = direction;
  68238. _this.onApplyObservable.add(function (effect) {
  68239. if (imageToBlur != null) {
  68240. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68241. }
  68242. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68243. if (scene.activeCamera) {
  68244. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68245. }
  68246. });
  68247. return _this;
  68248. }
  68249. return DepthOfFieldBlurPostProcess;
  68250. }(BABYLON.BlurPostProcess));
  68251. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68252. })(BABYLON || (BABYLON = {}));
  68253. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68254. var BABYLON;
  68255. (function (BABYLON) {
  68256. /**
  68257. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68258. */
  68259. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68260. __extends(DepthOfFieldMergePostProcess, _super);
  68261. /**
  68262. * Creates a new instance of @see CircleOfConfusionPostProcess
  68263. * @param name The name of the effect.
  68264. * @param original The non-blurred image to be modified
  68265. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68266. * @param blurSteps Incrimental bluring post processes.
  68267. * @param options The required width/height ratio to downsize to before computing the render pass.
  68268. * @param camera The camera to apply the render pass to.
  68269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68270. * @param engine The engine which the post process will be applied. (default: current engine)
  68271. * @param reusable If the post process can be reused on the same frame. (default: false)
  68272. * @param textureType Type of textures used when performing the post process. (default: 0)
  68273. * @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)
  68274. */
  68275. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68277. if (blockCompilation === void 0) { blockCompilation = false; }
  68278. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68279. _this.blurSteps = blurSteps;
  68280. _this.onApplyObservable.add(function (effect) {
  68281. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68282. effect.setTextureFromPostProcess("originalSampler", original);
  68283. blurSteps.forEach(function (step, index) {
  68284. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68285. });
  68286. });
  68287. if (!blockCompilation) {
  68288. _this.updateEffect();
  68289. }
  68290. return _this;
  68291. }
  68292. /**
  68293. * Updates the effect with the current post process compile time values and recompiles the shader.
  68294. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68295. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68296. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68297. * @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
  68298. * @param onCompiled Called when the shader has been compiled.
  68299. * @param onError Called if there is an error when compiling a shader.
  68300. */
  68301. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68302. if (defines === void 0) { defines = null; }
  68303. if (uniforms === void 0) { uniforms = null; }
  68304. if (samplers === void 0) { samplers = null; }
  68305. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  68306. };
  68307. return DepthOfFieldMergePostProcess;
  68308. }(BABYLON.PostProcess));
  68309. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68310. })(BABYLON || (BABYLON = {}));
  68311. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68312. var BABYLON;
  68313. (function (BABYLON) {
  68314. /**
  68315. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68316. */
  68317. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68318. __extends(CircleOfConfusionPostProcess, _super);
  68319. /**
  68320. * Creates a new instance of @see CircleOfConfusionPostProcess
  68321. * @param name The name of the effect.
  68322. * @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.
  68323. * @param options The required width/height ratio to downsize to before computing the render pass.
  68324. * @param camera The camera to apply the render pass to.
  68325. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68326. * @param engine The engine which the post process will be applied. (default: current engine)
  68327. * @param reusable If the post process can be reused on the same frame. (default: false)
  68328. * @param textureType Type of textures used when performing the post process. (default: 0)
  68329. * @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)
  68330. */
  68331. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68332. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68333. if (blockCompilation === void 0) { blockCompilation = false; }
  68334. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68335. /**
  68336. * 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.
  68337. */
  68338. _this.lensSize = 50;
  68339. /**
  68340. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68341. */
  68342. _this.fStop = 1.4;
  68343. /**
  68344. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68345. */
  68346. _this.focusDistance = 2000;
  68347. /**
  68348. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68349. */
  68350. _this.focalLength = 50;
  68351. _this._depthTexture = null;
  68352. _this._depthTexture = depthTexture;
  68353. _this.onApplyObservable.add(function (effect) {
  68354. if (!_this._depthTexture) {
  68355. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68356. return;
  68357. }
  68358. effect.setTexture("depthSampler", _this._depthTexture);
  68359. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68360. var aperture = _this.lensSize / _this.fStop;
  68361. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68362. effect.setFloat('focusDistance', _this.focusDistance);
  68363. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68364. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68365. });
  68366. return _this;
  68367. }
  68368. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68369. /**
  68370. * 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.
  68371. */
  68372. set: function (value) {
  68373. this._depthTexture = value;
  68374. },
  68375. enumerable: true,
  68376. configurable: true
  68377. });
  68378. return CircleOfConfusionPostProcess;
  68379. }(BABYLON.PostProcess));
  68380. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68381. })(BABYLON || (BABYLON = {}));
  68382. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68383. var BABYLON;
  68384. (function (BABYLON) {
  68385. /**
  68386. * Specifies the level of max blur that should be applied when using the depth of field effect
  68387. */
  68388. var DepthOfFieldEffectBlurLevel;
  68389. (function (DepthOfFieldEffectBlurLevel) {
  68390. /**
  68391. * Subtle blur
  68392. */
  68393. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68394. /**
  68395. * Medium blur
  68396. */
  68397. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68398. /**
  68399. * Large blur
  68400. */
  68401. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68402. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68403. ;
  68404. /**
  68405. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68406. */
  68407. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68408. __extends(DepthOfFieldEffect, _super);
  68409. /**
  68410. * Creates a new instance of @see DepthOfFieldEffect
  68411. * @param scene The scene the effect belongs to.
  68412. * @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.
  68413. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68414. * @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)
  68415. */
  68416. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  68417. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68418. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68419. if (blockCompilation === void 0) { blockCompilation = false; }
  68420. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68421. return _this._effects;
  68422. }, true) || this;
  68423. _this._effects = [];
  68424. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68425. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68426. // Capture circle of confusion texture
  68427. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68428. _this._depthOfFieldPass.autoClear = false;
  68429. // 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)
  68430. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68431. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68432. _this._depthOfFieldBlurY = [];
  68433. _this._depthOfFieldBlurX = [];
  68434. var blurCount = 1;
  68435. var kernelSize = 15;
  68436. switch (blurLevel) {
  68437. case DepthOfFieldEffectBlurLevel.High: {
  68438. blurCount = 3;
  68439. kernelSize = 51;
  68440. break;
  68441. }
  68442. case DepthOfFieldEffectBlurLevel.Medium: {
  68443. blurCount = 2;
  68444. kernelSize = 31;
  68445. break;
  68446. }
  68447. default: {
  68448. kernelSize = 15;
  68449. blurCount = 1;
  68450. break;
  68451. }
  68452. }
  68453. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68454. for (var i = 0; i < blurCount; i++) {
  68455. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68456. blurY.autoClear = false;
  68457. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68458. blurX.autoClear = false;
  68459. _this._depthOfFieldBlurY.push(blurY);
  68460. _this._depthOfFieldBlurX.push(blurX);
  68461. }
  68462. // Merge blurred images with original image based on circleOfConfusion
  68463. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68464. _this._depthOfFieldMerge.autoClear = false;
  68465. // Set all post processes on the effect.
  68466. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68467. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68468. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68469. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68470. }
  68471. _this._effects.push(_this._depthOfFieldMerge);
  68472. return _this;
  68473. }
  68474. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68475. get: function () {
  68476. return this._circleOfConfusion.focalLength;
  68477. },
  68478. /**
  68479. * The focal the length of the camera used in the effect
  68480. */
  68481. set: function (value) {
  68482. this._circleOfConfusion.focalLength = value;
  68483. },
  68484. enumerable: true,
  68485. configurable: true
  68486. });
  68487. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68488. get: function () {
  68489. return this._circleOfConfusion.fStop;
  68490. },
  68491. /**
  68492. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68493. */
  68494. set: function (value) {
  68495. this._circleOfConfusion.fStop = value;
  68496. },
  68497. enumerable: true,
  68498. configurable: true
  68499. });
  68500. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68501. get: function () {
  68502. return this._circleOfConfusion.focusDistance;
  68503. },
  68504. /**
  68505. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68506. */
  68507. set: function (value) {
  68508. this._circleOfConfusion.focusDistance = value;
  68509. },
  68510. enumerable: true,
  68511. configurable: true
  68512. });
  68513. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68514. get: function () {
  68515. return this._circleOfConfusion.lensSize;
  68516. },
  68517. /**
  68518. * 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.
  68519. */
  68520. set: function (value) {
  68521. this._circleOfConfusion.lensSize = value;
  68522. },
  68523. enumerable: true,
  68524. configurable: true
  68525. });
  68526. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  68527. /**
  68528. * 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.
  68529. */
  68530. set: function (value) {
  68531. this._circleOfConfusion.depthTexture = value;
  68532. },
  68533. enumerable: true,
  68534. configurable: true
  68535. });
  68536. /**
  68537. * Disposes each of the internal effects for a given camera.
  68538. * @param camera The camera to dispose the effect on.
  68539. */
  68540. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68541. this._depthOfFieldPass.dispose(camera);
  68542. this._circleOfConfusion.dispose(camera);
  68543. this._depthOfFieldBlurX.forEach(function (element) {
  68544. element.dispose(camera);
  68545. });
  68546. this._depthOfFieldBlurY.forEach(function (element) {
  68547. element.dispose(camera);
  68548. });
  68549. this._depthOfFieldMerge.dispose(camera);
  68550. };
  68551. /**
  68552. * Internal
  68553. */
  68554. DepthOfFieldEffect.prototype._updateEffects = function () {
  68555. for (var effect in this._effects) {
  68556. this._effects[effect].updateEffect();
  68557. }
  68558. };
  68559. /**
  68560. * Internal
  68561. * @returns if all the contained post processes are ready.
  68562. */
  68563. DepthOfFieldEffect.prototype._isReady = function () {
  68564. for (var effect in this._effects) {
  68565. if (!this._effects[effect].isReady()) {
  68566. return false;
  68567. }
  68568. }
  68569. return true;
  68570. };
  68571. return DepthOfFieldEffect;
  68572. }(BABYLON.PostProcessRenderEffect));
  68573. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68574. })(BABYLON || (BABYLON = {}));
  68575. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68576. var BABYLON;
  68577. (function (BABYLON) {
  68578. /**
  68579. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68580. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68581. */
  68582. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68583. __extends(DefaultRenderingPipeline, _super);
  68584. /**
  68585. * @constructor
  68586. * @param {string} name - The rendering pipeline name
  68587. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68588. * @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)
  68589. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68590. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68591. */
  68592. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68593. if (automaticBuild === void 0) { automaticBuild = true; }
  68594. var _this = _super.call(this, scene.getEngine(), name) || this;
  68595. _this._originalCameras = [];
  68596. /**
  68597. * ID of the sharpen post process,
  68598. */
  68599. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68600. /**
  68601. * ID of the pass post process used for bloom,
  68602. */
  68603. _this.PassPostProcessId = "PassPostProcessEffect";
  68604. /**
  68605. * ID of the highlight post process used for bloom,
  68606. */
  68607. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68608. /**
  68609. * ID of the blurX post process used for bloom,
  68610. */
  68611. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68612. /**
  68613. * ID of the blurY post process used for bloom,
  68614. */
  68615. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68616. /**
  68617. * ID of the copy back post process used for bloom,
  68618. */
  68619. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68620. /**
  68621. * ID of the image processing post process;
  68622. */
  68623. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68624. /**
  68625. * ID of the Fast Approximate Anti-Aliasing post process;
  68626. */
  68627. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68628. /**
  68629. * ID of the final merge post process;
  68630. */
  68631. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68632. /**
  68633. * ID of the chromatic aberration post process,
  68634. */
  68635. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68636. /**
  68637. * Animations which can be used to tweak settings over a period of time
  68638. */
  68639. _this.animations = [];
  68640. // Values
  68641. _this._sharpenEnabled = false;
  68642. _this._bloomEnabled = false;
  68643. _this._depthOfFieldEnabled = false;
  68644. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68645. _this._fxaaEnabled = false;
  68646. _this._msaaEnabled = false;
  68647. _this._imageProcessingEnabled = true;
  68648. _this._bloomScale = 0.6;
  68649. _this._chromaticAberrationEnabled = false;
  68650. _this._buildAllowed = true;
  68651. /**
  68652. * Specifies the size of the bloom blur kernel, relative to the final output size
  68653. */
  68654. _this.bloomKernel = 64;
  68655. /**
  68656. * Specifies the weight of the bloom in the final rendering
  68657. */
  68658. _this._bloomWeight = 0.15;
  68659. _this._prevPostProcess = null;
  68660. _this._prevPrevPostProcess = null;
  68661. _this._cameras = cameras || [];
  68662. _this._originalCameras = _this._cameras.slice();
  68663. _this._buildAllowed = automaticBuild;
  68664. // Initialize
  68665. _this._scene = scene;
  68666. var caps = _this._scene.getEngine().getCaps();
  68667. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68668. // Misc
  68669. if (_this._hdr) {
  68670. if (caps.textureHalfFloatRender) {
  68671. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68672. }
  68673. else if (caps.textureFloatRender) {
  68674. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68675. }
  68676. }
  68677. else {
  68678. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68679. }
  68680. // Attach
  68681. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68682. var engine = _this._scene.getEngine();
  68683. // Create post processes before hand so they can be modified before enabled.
  68684. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  68685. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68686. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68687. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  68688. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68689. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68690. _this._buildPipeline();
  68691. return _this;
  68692. }
  68693. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68694. get: function () {
  68695. return this._sharpenEnabled;
  68696. },
  68697. /**
  68698. * Enable or disable the sharpen process from the pipeline
  68699. */
  68700. set: function (enabled) {
  68701. if (this._sharpenEnabled === enabled) {
  68702. return;
  68703. }
  68704. this._sharpenEnabled = enabled;
  68705. this._buildPipeline();
  68706. },
  68707. enumerable: true,
  68708. configurable: true
  68709. });
  68710. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68711. get: function () {
  68712. return this._bloomWeight;
  68713. },
  68714. /**
  68715. * The strength of the bloom.
  68716. */
  68717. set: function (value) {
  68718. if (this._bloomWeight === value) {
  68719. return;
  68720. }
  68721. this._bloomWeight = value;
  68722. if (this._hdr && this.copyBack) {
  68723. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68724. }
  68725. },
  68726. enumerable: true,
  68727. configurable: true
  68728. });
  68729. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68730. get: function () {
  68731. return this._bloomScale;
  68732. },
  68733. /**
  68734. * The scale of the bloom, lower value will provide better performance.
  68735. */
  68736. set: function (value) {
  68737. if (this._bloomScale === value) {
  68738. return;
  68739. }
  68740. this._bloomScale = value;
  68741. this._buildPipeline();
  68742. },
  68743. enumerable: true,
  68744. configurable: true
  68745. });
  68746. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68747. get: function () {
  68748. return this._bloomEnabled;
  68749. },
  68750. /**
  68751. * Enable or disable the bloom from the pipeline
  68752. */
  68753. set: function (enabled) {
  68754. if (this._bloomEnabled === enabled) {
  68755. return;
  68756. }
  68757. this._bloomEnabled = enabled;
  68758. this._buildPipeline();
  68759. },
  68760. enumerable: true,
  68761. configurable: true
  68762. });
  68763. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68764. /**
  68765. * If the depth of field is enabled.
  68766. */
  68767. get: function () {
  68768. return this._depthOfFieldEnabled;
  68769. },
  68770. set: function (enabled) {
  68771. if (this._depthOfFieldEnabled === enabled) {
  68772. return;
  68773. }
  68774. this._depthOfFieldEnabled = enabled;
  68775. this._buildPipeline();
  68776. },
  68777. enumerable: true,
  68778. configurable: true
  68779. });
  68780. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68781. /**
  68782. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68783. */
  68784. get: function () {
  68785. return this._depthOfFieldBlurLevel;
  68786. },
  68787. set: function (value) {
  68788. if (this._depthOfFieldBlurLevel === value) {
  68789. return;
  68790. }
  68791. this._depthOfFieldBlurLevel = value;
  68792. // recreate dof and dispose old as this setting is not dynamic
  68793. var oldDof = this.depthOfField;
  68794. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68795. this.depthOfField.focalLength = oldDof.focalLength;
  68796. this.depthOfField.focusDistance = oldDof.focusDistance;
  68797. this.depthOfField.fStop = oldDof.fStop;
  68798. this.depthOfField.lensSize = oldDof.lensSize;
  68799. for (var i = 0; i < this._cameras.length; i++) {
  68800. oldDof.disposeEffects(this._cameras[i]);
  68801. }
  68802. this._buildPipeline();
  68803. },
  68804. enumerable: true,
  68805. configurable: true
  68806. });
  68807. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68808. get: function () {
  68809. return this._fxaaEnabled;
  68810. },
  68811. /**
  68812. * If the anti aliasing is enabled.
  68813. */
  68814. set: function (enabled) {
  68815. if (this._fxaaEnabled === enabled) {
  68816. return;
  68817. }
  68818. this._fxaaEnabled = enabled;
  68819. this._buildPipeline();
  68820. },
  68821. enumerable: true,
  68822. configurable: true
  68823. });
  68824. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68825. get: function () {
  68826. return this._msaaEnabled;
  68827. },
  68828. /**
  68829. * If the multisample anti-aliasing is enabled.
  68830. */
  68831. set: function (enabled) {
  68832. if (this._msaaEnabled === enabled) {
  68833. return;
  68834. }
  68835. this._msaaEnabled = enabled;
  68836. this._buildPipeline();
  68837. },
  68838. enumerable: true,
  68839. configurable: true
  68840. });
  68841. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68842. get: function () {
  68843. return this._imageProcessingEnabled;
  68844. },
  68845. /**
  68846. * If image processing is enabled.
  68847. */
  68848. set: function (enabled) {
  68849. if (this._imageProcessingEnabled === enabled) {
  68850. return;
  68851. }
  68852. this._imageProcessingEnabled = enabled;
  68853. this._buildPipeline();
  68854. },
  68855. enumerable: true,
  68856. configurable: true
  68857. });
  68858. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68859. get: function () {
  68860. return this._chromaticAberrationEnabled;
  68861. },
  68862. /**
  68863. * Enable or disable the chromaticAberration process from the pipeline
  68864. */
  68865. set: function (enabled) {
  68866. if (this._chromaticAberrationEnabled === enabled) {
  68867. return;
  68868. }
  68869. this._chromaticAberrationEnabled = enabled;
  68870. this._buildPipeline();
  68871. },
  68872. enumerable: true,
  68873. configurable: true
  68874. });
  68875. /**
  68876. * Force the compilation of the entire pipeline.
  68877. */
  68878. DefaultRenderingPipeline.prototype.prepare = function () {
  68879. var previousState = this._buildAllowed;
  68880. this._buildAllowed = true;
  68881. this._buildPipeline();
  68882. this._buildAllowed = previousState;
  68883. };
  68884. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68885. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68886. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68887. postProcess.autoClear = false;
  68888. }
  68889. else {
  68890. postProcess.autoClear = true;
  68891. }
  68892. if (!skipTextureSharing) {
  68893. if (this._prevPrevPostProcess) {
  68894. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68895. }
  68896. else {
  68897. postProcess.useOwnOutput();
  68898. }
  68899. if (this._prevPostProcess) {
  68900. this._prevPrevPostProcess = this._prevPostProcess;
  68901. }
  68902. this._prevPostProcess = postProcess;
  68903. }
  68904. };
  68905. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68906. var _this = this;
  68907. if (!this._buildAllowed) {
  68908. return;
  68909. }
  68910. var engine = this._scene.getEngine();
  68911. this._disposePostProcesses();
  68912. if (this._cameras !== null) {
  68913. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68914. // get back cameras to be used to reattach pipeline
  68915. this._cameras = this._originalCameras.slice();
  68916. }
  68917. this._reset();
  68918. this._prevPostProcess = null;
  68919. this._prevPrevPostProcess = null;
  68920. if (this.sharpenEnabled) {
  68921. if (!this.sharpen.isReady()) {
  68922. this.sharpen.updateEffect();
  68923. }
  68924. this.addEffect(this._sharpenEffect);
  68925. this._setAutoClearAndTextureSharing(this.sharpen);
  68926. }
  68927. if (this.depthOfFieldEnabled) {
  68928. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68929. this.depthOfField.depthTexture = depthTexture;
  68930. if (!this.depthOfField._isReady()) {
  68931. this.depthOfField._updateEffects();
  68932. }
  68933. this.addEffect(this.depthOfField);
  68934. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68935. }
  68936. if (this.bloomEnabled) {
  68937. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68938. this._setAutoClearAndTextureSharing(this.pass, true);
  68939. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68940. if (!this._hdr) {
  68941. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68942. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68943. this.highlights.autoClear = false;
  68944. this.highlights.alwaysForcePOT = true;
  68945. }
  68946. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68947. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68948. this.blurX.alwaysForcePOT = true;
  68949. this.blurX.autoClear = false;
  68950. this.blurX.onActivateObservable.add(function () {
  68951. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68952. _this.blurX.kernel = _this.bloomKernel * dw;
  68953. });
  68954. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68955. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68956. this.blurY.alwaysForcePOT = true;
  68957. this.blurY.autoClear = false;
  68958. this.blurY.onActivateObservable.add(function () {
  68959. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68960. _this.blurY.kernel = _this.bloomKernel * dh;
  68961. });
  68962. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68963. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68964. this.copyBack.alwaysForcePOT = true;
  68965. if (this._hdr) {
  68966. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68967. var w = this.bloomWeight;
  68968. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68969. }
  68970. else {
  68971. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68972. }
  68973. this.copyBack.autoClear = false;
  68974. }
  68975. if (this._imageProcessingEnabled) {
  68976. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68977. if (this._hdr) {
  68978. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68979. }
  68980. else {
  68981. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68982. }
  68983. }
  68984. if (this._hdr && this.imageProcessing) {
  68985. this.finalMerge = this.imageProcessing;
  68986. }
  68987. else {
  68988. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68989. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68990. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  68991. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68992. }
  68993. if (this.bloomEnabled) {
  68994. if (this._hdr) {
  68995. this.copyBack.shareOutputWith(this.blurX);
  68996. if (this.imageProcessing) {
  68997. this.imageProcessing.shareOutputWith(this.pass);
  68998. this.imageProcessing.autoClear = false;
  68999. }
  69000. else {
  69001. this.finalMerge.shareOutputWith(this.pass);
  69002. }
  69003. }
  69004. else {
  69005. this.finalMerge.shareOutputWith(this.pass);
  69006. }
  69007. }
  69008. if (this.fxaaEnabled) {
  69009. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69010. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69011. this._setAutoClearAndTextureSharing(this.fxaa);
  69012. }
  69013. if (this.chromaticAberrationEnabled) {
  69014. if (!this.chromaticAberration.isReady()) {
  69015. this.chromaticAberration.updateEffect();
  69016. }
  69017. this.addEffect(this._chromaticAberrationEffect);
  69018. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69019. }
  69020. if (this._cameras !== null) {
  69021. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69022. }
  69023. if (this.msaaEnabled) {
  69024. if (!this._enableMSAAOnFirstPostProcess()) {
  69025. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69026. }
  69027. }
  69028. };
  69029. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69030. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69031. for (var i = 0; i < this._cameras.length; i++) {
  69032. var camera = this._cameras[i];
  69033. if (this.pass) {
  69034. this.pass.dispose(camera);
  69035. }
  69036. if (this.highlights) {
  69037. this.highlights.dispose(camera);
  69038. }
  69039. if (this.blurX) {
  69040. this.blurX.dispose(camera);
  69041. }
  69042. if (this.blurY) {
  69043. this.blurY.dispose(camera);
  69044. }
  69045. if (this.copyBack) {
  69046. this.copyBack.dispose(camera);
  69047. }
  69048. if (this.imageProcessing) {
  69049. this.imageProcessing.dispose(camera);
  69050. }
  69051. if (this.fxaa) {
  69052. this.fxaa.dispose(camera);
  69053. }
  69054. if (this.finalMerge) {
  69055. this.finalMerge.dispose(camera);
  69056. }
  69057. // These are created in the constructor and should not be disposed on every pipeline change
  69058. if (disposeNonRecreated) {
  69059. if (this.sharpen) {
  69060. this.sharpen.dispose(camera);
  69061. }
  69062. if (this.depthOfField) {
  69063. this.depthOfField.disposeEffects(camera);
  69064. }
  69065. if (this.chromaticAberration) {
  69066. this.chromaticAberration.dispose(camera);
  69067. }
  69068. }
  69069. }
  69070. this.pass = null;
  69071. this.highlights = null;
  69072. this.blurX = null;
  69073. this.blurY = null;
  69074. this.copyBack = null;
  69075. this.imageProcessing = null;
  69076. this.fxaa = null;
  69077. this.finalMerge = null;
  69078. if (disposeNonRecreated) {
  69079. this.sharpen = null;
  69080. this.depthOfField = null;
  69081. this.chromaticAberration = null;
  69082. }
  69083. };
  69084. /**
  69085. * Dispose of the pipeline and stop all post processes
  69086. */
  69087. DefaultRenderingPipeline.prototype.dispose = function () {
  69088. this._disposePostProcesses(true);
  69089. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69090. _super.prototype.dispose.call(this);
  69091. };
  69092. /**
  69093. * Serialize the rendering pipeline (Used when exporting)
  69094. * @returns the serialized object
  69095. */
  69096. DefaultRenderingPipeline.prototype.serialize = function () {
  69097. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69098. serializationObject.customType = "DefaultRenderingPipeline";
  69099. return serializationObject;
  69100. };
  69101. /**
  69102. * Parse the serialized pipeline
  69103. * @param source Source pipeline.
  69104. * @param scene The scene to load the pipeline to.
  69105. * @param rootUrl The URL of the serialized pipeline.
  69106. * @returns An instantiated pipeline from the serialized object.
  69107. */
  69108. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69109. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69110. };
  69111. __decorate([
  69112. BABYLON.serialize()
  69113. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69114. __decorate([
  69115. BABYLON.serialize()
  69116. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69117. __decorate([
  69118. BABYLON.serialize()
  69119. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69120. __decorate([
  69121. BABYLON.serialize()
  69122. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69123. __decorate([
  69124. BABYLON.serialize()
  69125. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69126. __decorate([
  69127. BABYLON.serialize()
  69128. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69129. __decorate([
  69130. BABYLON.serialize()
  69131. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69132. __decorate([
  69133. BABYLON.serialize()
  69134. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69135. __decorate([
  69136. BABYLON.serialize()
  69137. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69138. __decorate([
  69139. BABYLON.serialize()
  69140. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69141. __decorate([
  69142. BABYLON.serialize()
  69143. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69144. __decorate([
  69145. BABYLON.serialize()
  69146. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69147. __decorate([
  69148. BABYLON.serialize()
  69149. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69150. return DefaultRenderingPipeline;
  69151. }(BABYLON.PostProcessRenderPipeline));
  69152. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69153. })(BABYLON || (BABYLON = {}));
  69154. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69155. var BABYLON;
  69156. (function (BABYLON) {
  69157. /**
  69158. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69159. */
  69160. var GeometryBufferRenderer = /** @class */ (function () {
  69161. /**
  69162. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69163. * @param scene The scene the buffer belongs to
  69164. * @param ratio How big is the buffer related to the main canvas.
  69165. */
  69166. function GeometryBufferRenderer(scene, ratio) {
  69167. if (ratio === void 0) { ratio = 1; }
  69168. this._enablePosition = false;
  69169. this._scene = scene;
  69170. this._ratio = ratio;
  69171. // Render target
  69172. this._createRenderTargets();
  69173. }
  69174. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69175. /**
  69176. * Set the render list (meshes to be rendered) used in the G buffer.
  69177. */
  69178. set: function (meshes) {
  69179. this._multiRenderTarget.renderList = meshes;
  69180. },
  69181. enumerable: true,
  69182. configurable: true
  69183. });
  69184. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69185. /**
  69186. * Gets wether or not G buffer are supported by the running hardware.
  69187. * This requires draw buffer supports
  69188. */
  69189. get: function () {
  69190. return this._multiRenderTarget.isSupported;
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69196. /**
  69197. * Gets wether or not position are enabled for the G buffer.
  69198. */
  69199. get: function () {
  69200. return this._enablePosition;
  69201. },
  69202. /**
  69203. * Sets wether or not position are enabled for the G buffer.
  69204. */
  69205. set: function (enable) {
  69206. this._enablePosition = enable;
  69207. this.dispose();
  69208. this._createRenderTargets();
  69209. },
  69210. enumerable: true,
  69211. configurable: true
  69212. });
  69213. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69214. /**
  69215. * Gets the scene associated with the buffer.
  69216. */
  69217. get: function () {
  69218. return this._scene;
  69219. },
  69220. enumerable: true,
  69221. configurable: true
  69222. });
  69223. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69224. /**
  69225. * Gets the ratio used by the buffer during its creation.
  69226. * How big is the buffer related to the main canvas.
  69227. */
  69228. get: function () {
  69229. return this._ratio;
  69230. },
  69231. enumerable: true,
  69232. configurable: true
  69233. });
  69234. /**
  69235. * Checks wether everything is ready to render a submesh to the G buffer.
  69236. * @param subMesh the submesh to check readiness for
  69237. * @param useInstances is the mesh drawn using instance or not
  69238. * @returns true if ready otherwise false
  69239. */
  69240. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69241. var material = subMesh.getMaterial();
  69242. if (material && material.disableDepthWrite) {
  69243. return false;
  69244. }
  69245. var defines = [];
  69246. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69247. var mesh = subMesh.getMesh();
  69248. // Alpha test
  69249. if (material && material.needAlphaTesting()) {
  69250. defines.push("#define ALPHATEST");
  69251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69252. attribs.push(BABYLON.VertexBuffer.UVKind);
  69253. defines.push("#define UV1");
  69254. }
  69255. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69256. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69257. defines.push("#define UV2");
  69258. }
  69259. }
  69260. // Buffers
  69261. if (this._enablePosition) {
  69262. defines.push("#define POSITION");
  69263. }
  69264. // Bones
  69265. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69268. if (mesh.numBoneInfluencers > 4) {
  69269. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69270. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69271. }
  69272. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69273. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69274. }
  69275. else {
  69276. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69277. }
  69278. // Instances
  69279. if (useInstances) {
  69280. defines.push("#define INSTANCES");
  69281. attribs.push("world0");
  69282. attribs.push("world1");
  69283. attribs.push("world2");
  69284. attribs.push("world3");
  69285. }
  69286. // Get correct effect
  69287. var join = defines.join("\n");
  69288. if (this._cachedDefines !== join) {
  69289. this._cachedDefines = join;
  69290. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69291. }
  69292. return this._effect.isReady();
  69293. };
  69294. /**
  69295. * Gets the current underlying G Buffer.
  69296. * @returns the buffer
  69297. */
  69298. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69299. return this._multiRenderTarget;
  69300. };
  69301. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69302. /**
  69303. * Gets the number of samples used to render the buffer (anti aliasing).
  69304. */
  69305. get: function () {
  69306. return this._multiRenderTarget.samples;
  69307. },
  69308. /**
  69309. * Sets the number of samples used to render the buffer (anti aliasing).
  69310. */
  69311. set: function (value) {
  69312. this._multiRenderTarget.samples = value;
  69313. },
  69314. enumerable: true,
  69315. configurable: true
  69316. });
  69317. /**
  69318. * Disposes the renderer and frees up associated resources.
  69319. */
  69320. GeometryBufferRenderer.prototype.dispose = function () {
  69321. this.getGBuffer().dispose();
  69322. };
  69323. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69324. var _this = this;
  69325. var engine = this._scene.getEngine();
  69326. var count = this._enablePosition ? 3 : 2;
  69327. 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 });
  69328. if (!this.isSupported) {
  69329. return;
  69330. }
  69331. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69332. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69333. this._multiRenderTarget.refreshRate = 1;
  69334. this._multiRenderTarget.renderParticles = false;
  69335. this._multiRenderTarget.renderList = null;
  69336. // set default depth value to 1.0 (far away)
  69337. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69338. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69339. });
  69340. // Custom render function
  69341. var renderSubMesh = function (subMesh) {
  69342. var mesh = subMesh.getRenderingMesh();
  69343. var scene = _this._scene;
  69344. var engine = scene.getEngine();
  69345. var material = subMesh.getMaterial();
  69346. if (!material) {
  69347. return;
  69348. }
  69349. // Culling
  69350. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69351. // Managing instances
  69352. var batch = mesh._getInstancesRenderList(subMesh._id);
  69353. if (batch.mustReturn) {
  69354. return;
  69355. }
  69356. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69357. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69358. engine.enableEffect(_this._effect);
  69359. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69360. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69361. _this._effect.setMatrix("view", scene.getViewMatrix());
  69362. // Alpha test
  69363. if (material && material.needAlphaTesting()) {
  69364. var alphaTexture = material.getAlphaTestTexture();
  69365. if (alphaTexture) {
  69366. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69367. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69368. }
  69369. }
  69370. // Bones
  69371. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69372. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69373. }
  69374. // Draw
  69375. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69376. }
  69377. };
  69378. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69379. var index;
  69380. if (depthOnlySubMeshes.length) {
  69381. engine.setColorWrite(false);
  69382. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69383. renderSubMesh(depthOnlySubMeshes.data[index]);
  69384. }
  69385. engine.setColorWrite(true);
  69386. }
  69387. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69388. renderSubMesh(opaqueSubMeshes.data[index]);
  69389. }
  69390. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69391. renderSubMesh(alphaTestSubMeshes.data[index]);
  69392. }
  69393. };
  69394. };
  69395. return GeometryBufferRenderer;
  69396. }());
  69397. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69398. })(BABYLON || (BABYLON = {}));
  69399. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69400. var BABYLON;
  69401. (function (BABYLON) {
  69402. var RefractionPostProcess = /** @class */ (function (_super) {
  69403. __extends(RefractionPostProcess, _super);
  69404. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69405. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69406. _this.color = color;
  69407. _this.depth = depth;
  69408. _this.colorLevel = colorLevel;
  69409. _this._ownRefractionTexture = true;
  69410. _this.onActivateObservable.add(function (cam) {
  69411. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69412. });
  69413. _this.onApplyObservable.add(function (effect) {
  69414. effect.setColor3("baseColor", _this.color);
  69415. effect.setFloat("depth", _this.depth);
  69416. effect.setFloat("colorLevel", _this.colorLevel);
  69417. effect.setTexture("refractionSampler", _this._refTexture);
  69418. });
  69419. return _this;
  69420. }
  69421. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69422. /**
  69423. * Gets or sets the refraction texture
  69424. * Please note that you are responsible for disposing the texture if you set it manually
  69425. */
  69426. get: function () {
  69427. return this._refTexture;
  69428. },
  69429. set: function (value) {
  69430. if (this._refTexture && this._ownRefractionTexture) {
  69431. this._refTexture.dispose();
  69432. }
  69433. this._refTexture = value;
  69434. this._ownRefractionTexture = false;
  69435. },
  69436. enumerable: true,
  69437. configurable: true
  69438. });
  69439. // Methods
  69440. RefractionPostProcess.prototype.dispose = function (camera) {
  69441. if (this._refTexture && this._ownRefractionTexture) {
  69442. this._refTexture.dispose();
  69443. this._refTexture = null;
  69444. }
  69445. _super.prototype.dispose.call(this, camera);
  69446. };
  69447. return RefractionPostProcess;
  69448. }(BABYLON.PostProcess));
  69449. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69450. })(BABYLON || (BABYLON = {}));
  69451. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69452. var BABYLON;
  69453. (function (BABYLON) {
  69454. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69455. __extends(BlackAndWhitePostProcess, _super);
  69456. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69457. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69458. _this.degree = 1;
  69459. _this.onApplyObservable.add(function (effect) {
  69460. effect.setFloat("degree", _this.degree);
  69461. });
  69462. return _this;
  69463. }
  69464. return BlackAndWhitePostProcess;
  69465. }(BABYLON.PostProcess));
  69466. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69467. })(BABYLON || (BABYLON = {}));
  69468. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69469. var BABYLON;
  69470. (function (BABYLON) {
  69471. /**
  69472. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69473. * input texture to perform effects such as edge detection or sharpening
  69474. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69475. */
  69476. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69477. __extends(ConvolutionPostProcess, _super);
  69478. /**
  69479. * Creates a new instance of @see ConvolutionPostProcess
  69480. * @param name The name of the effect.
  69481. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69482. * @param options The required width/height ratio to downsize to before computing the render pass.
  69483. * @param camera The camera to apply the render pass to.
  69484. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69485. * @param engine The engine which the post process will be applied. (default: current engine)
  69486. * @param reusable If the post process can be reused on the same frame. (default: false)
  69487. * @param textureType Type of textures used when performing the post process. (default: 0)
  69488. */
  69489. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69490. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69491. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69492. _this.kernel = kernel;
  69493. _this.onApply = function (effect) {
  69494. effect.setFloat2("screenSize", _this.width, _this.height);
  69495. effect.setArray("kernel", _this.kernel);
  69496. };
  69497. return _this;
  69498. }
  69499. // Statics
  69500. /**
  69501. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69502. */
  69503. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69504. /**
  69505. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69506. */
  69507. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69508. /**
  69509. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69510. */
  69511. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69512. /**
  69513. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69514. */
  69515. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69516. /**
  69517. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69518. */
  69519. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69520. /**
  69521. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69522. */
  69523. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69524. return ConvolutionPostProcess;
  69525. }(BABYLON.PostProcess));
  69526. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69527. })(BABYLON || (BABYLON = {}));
  69528. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69529. var BABYLON;
  69530. (function (BABYLON) {
  69531. var FilterPostProcess = /** @class */ (function (_super) {
  69532. __extends(FilterPostProcess, _super);
  69533. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69534. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69535. _this.kernelMatrix = kernelMatrix;
  69536. _this.onApply = function (effect) {
  69537. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69538. };
  69539. return _this;
  69540. }
  69541. return FilterPostProcess;
  69542. }(BABYLON.PostProcess));
  69543. BABYLON.FilterPostProcess = FilterPostProcess;
  69544. })(BABYLON || (BABYLON = {}));
  69545. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69546. var BABYLON;
  69547. (function (BABYLON) {
  69548. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69549. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69550. __extends(VolumetricLightScatteringPostProcess, _super);
  69551. /**
  69552. * @constructor
  69553. * @param {string} name - The post-process name
  69554. * @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)
  69555. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69556. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69557. * @param {number} samples - The post-process quality, default 100
  69558. * @param {number} samplingMode - The post-process filtering mode
  69559. * @param {BABYLON.Engine} engine - The babylon engine
  69560. * @param {boolean} reusable - If the post-process is reusable
  69561. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69562. */
  69563. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69564. if (samples === void 0) { samples = 100; }
  69565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69566. 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;
  69567. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69568. /**
  69569. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69570. * @type {Vector3}
  69571. */
  69572. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69573. /**
  69574. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69575. * @type {boolean}
  69576. */
  69577. _this.useCustomMeshPosition = false;
  69578. /**
  69579. * If the post-process should inverse the light scattering direction
  69580. * @type {boolean}
  69581. */
  69582. _this.invert = true;
  69583. /**
  69584. * Array containing the excluded meshes not rendered in the internal pass
  69585. */
  69586. _this.excludedMeshes = new Array();
  69587. /**
  69588. * Controls the overall intensity of the post-process
  69589. * @type {number}
  69590. */
  69591. _this.exposure = 0.3;
  69592. /**
  69593. * Dissipates each sample's contribution in range [0, 1]
  69594. * @type {number}
  69595. */
  69596. _this.decay = 0.96815;
  69597. /**
  69598. * Controls the overall intensity of each sample
  69599. * @type {number}
  69600. */
  69601. _this.weight = 0.58767;
  69602. /**
  69603. * Controls the density of each sample
  69604. * @type {number}
  69605. */
  69606. _this.density = 0.926;
  69607. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69608. engine = scene.getEngine();
  69609. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69610. // Configure mesh
  69611. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69612. // Configure
  69613. _this._createPass(scene, ratio.passRatio || ratio);
  69614. _this.onActivate = function (camera) {
  69615. if (!_this.isSupported) {
  69616. _this.dispose(camera);
  69617. }
  69618. _this.onActivate = null;
  69619. };
  69620. _this.onApplyObservable.add(function (effect) {
  69621. _this._updateMeshScreenCoordinates(scene);
  69622. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69623. effect.setFloat("exposure", _this.exposure);
  69624. effect.setFloat("decay", _this.decay);
  69625. effect.setFloat("weight", _this.weight);
  69626. effect.setFloat("density", _this.density);
  69627. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69628. });
  69629. return _this;
  69630. }
  69631. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69632. get: function () {
  69633. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69634. return false;
  69635. },
  69636. set: function (useDiffuseColor) {
  69637. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69638. },
  69639. enumerable: true,
  69640. configurable: true
  69641. });
  69642. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69643. return "VolumetricLightScatteringPostProcess";
  69644. };
  69645. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69646. var mesh = subMesh.getMesh();
  69647. // Render this.mesh as default
  69648. if (mesh === this.mesh && mesh.material) {
  69649. return mesh.material.isReady(mesh);
  69650. }
  69651. var defines = [];
  69652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69653. var material = subMesh.getMaterial();
  69654. // Alpha test
  69655. if (material) {
  69656. if (material.needAlphaTesting()) {
  69657. defines.push("#define ALPHATEST");
  69658. }
  69659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69660. attribs.push(BABYLON.VertexBuffer.UVKind);
  69661. defines.push("#define UV1");
  69662. }
  69663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69664. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69665. defines.push("#define UV2");
  69666. }
  69667. }
  69668. // Bones
  69669. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69672. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69673. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69674. }
  69675. else {
  69676. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69677. }
  69678. // Instances
  69679. if (useInstances) {
  69680. defines.push("#define INSTANCES");
  69681. attribs.push("world0");
  69682. attribs.push("world1");
  69683. attribs.push("world2");
  69684. attribs.push("world3");
  69685. }
  69686. // Get correct effect
  69687. var join = defines.join("\n");
  69688. if (this._cachedDefines !== join) {
  69689. this._cachedDefines = join;
  69690. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69691. }
  69692. return this._volumetricLightScatteringPass.isReady();
  69693. };
  69694. /**
  69695. * Sets the new light position for light scattering effect
  69696. * @param {BABYLON.Vector3} The new custom light position
  69697. */
  69698. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69699. this.customMeshPosition = position;
  69700. };
  69701. /**
  69702. * Returns the light position for light scattering effect
  69703. * @return {BABYLON.Vector3} The custom light position
  69704. */
  69705. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69706. return this.customMeshPosition;
  69707. };
  69708. /**
  69709. * Disposes the internal assets and detaches the post-process from the camera
  69710. */
  69711. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69712. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69713. if (rttIndex !== -1) {
  69714. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69715. }
  69716. this._volumetricLightScatteringRTT.dispose();
  69717. _super.prototype.dispose.call(this, camera);
  69718. };
  69719. /**
  69720. * Returns the render target texture used by the post-process
  69721. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69722. */
  69723. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69724. return this._volumetricLightScatteringRTT;
  69725. };
  69726. // Private methods
  69727. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69728. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69729. return true;
  69730. }
  69731. return false;
  69732. };
  69733. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69734. var _this = this;
  69735. var engine = scene.getEngine();
  69736. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69737. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69738. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69739. this._volumetricLightScatteringRTT.renderList = null;
  69740. this._volumetricLightScatteringRTT.renderParticles = false;
  69741. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69742. var camera = this.getCamera();
  69743. if (camera) {
  69744. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69745. }
  69746. else {
  69747. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69748. }
  69749. // Custom render function for submeshes
  69750. var renderSubMesh = function (subMesh) {
  69751. var mesh = subMesh.getRenderingMesh();
  69752. if (_this._meshExcluded(mesh)) {
  69753. return;
  69754. }
  69755. var material = subMesh.getMaterial();
  69756. if (!material) {
  69757. return;
  69758. }
  69759. var scene = mesh.getScene();
  69760. var engine = scene.getEngine();
  69761. // Culling
  69762. engine.setState(material.backFaceCulling);
  69763. // Managing instances
  69764. var batch = mesh._getInstancesRenderList(subMesh._id);
  69765. if (batch.mustReturn) {
  69766. return;
  69767. }
  69768. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69769. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69770. var effect = _this._volumetricLightScatteringPass;
  69771. if (mesh === _this.mesh) {
  69772. if (subMesh.effect) {
  69773. effect = subMesh.effect;
  69774. }
  69775. else {
  69776. effect = material.getEffect();
  69777. }
  69778. }
  69779. engine.enableEffect(effect);
  69780. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69781. if (mesh === _this.mesh) {
  69782. material.bind(mesh.getWorldMatrix(), mesh);
  69783. }
  69784. else {
  69785. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69786. // Alpha test
  69787. if (material && material.needAlphaTesting()) {
  69788. var alphaTexture = material.getAlphaTestTexture();
  69789. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69790. if (alphaTexture) {
  69791. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69792. }
  69793. }
  69794. // Bones
  69795. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69796. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69797. }
  69798. }
  69799. // Draw
  69800. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69801. }
  69802. };
  69803. // Render target texture callbacks
  69804. var savedSceneClearColor;
  69805. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69806. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69807. savedSceneClearColor = scene.clearColor;
  69808. scene.clearColor = sceneClearColor;
  69809. });
  69810. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69811. scene.clearColor = savedSceneClearColor;
  69812. });
  69813. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69814. var engine = scene.getEngine();
  69815. var index;
  69816. if (depthOnlySubMeshes.length) {
  69817. engine.setColorWrite(false);
  69818. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69819. renderSubMesh(depthOnlySubMeshes.data[index]);
  69820. }
  69821. engine.setColorWrite(true);
  69822. }
  69823. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69824. renderSubMesh(opaqueSubMeshes.data[index]);
  69825. }
  69826. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69827. renderSubMesh(alphaTestSubMeshes.data[index]);
  69828. }
  69829. if (transparentSubMeshes.length) {
  69830. // Sort sub meshes
  69831. for (index = 0; index < transparentSubMeshes.length; index++) {
  69832. var submesh = transparentSubMeshes.data[index];
  69833. var boundingInfo = submesh.getBoundingInfo();
  69834. if (boundingInfo && scene.activeCamera) {
  69835. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69836. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69837. }
  69838. }
  69839. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69840. sortedArray.sort(function (a, b) {
  69841. // Alpha index first
  69842. if (a._alphaIndex > b._alphaIndex) {
  69843. return 1;
  69844. }
  69845. if (a._alphaIndex < b._alphaIndex) {
  69846. return -1;
  69847. }
  69848. // Then distance to camera
  69849. if (a._distanceToCamera < b._distanceToCamera) {
  69850. return 1;
  69851. }
  69852. if (a._distanceToCamera > b._distanceToCamera) {
  69853. return -1;
  69854. }
  69855. return 0;
  69856. });
  69857. // Render sub meshes
  69858. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69859. for (index = 0; index < sortedArray.length; index++) {
  69860. renderSubMesh(sortedArray[index]);
  69861. }
  69862. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69863. }
  69864. };
  69865. };
  69866. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69867. var transform = scene.getTransformMatrix();
  69868. var meshPosition;
  69869. if (this.useCustomMeshPosition) {
  69870. meshPosition = this.customMeshPosition;
  69871. }
  69872. else if (this.attachedNode) {
  69873. meshPosition = this.attachedNode.position;
  69874. }
  69875. else {
  69876. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69877. }
  69878. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69879. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69880. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69881. if (this.invert)
  69882. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69883. };
  69884. // Static methods
  69885. /**
  69886. * Creates a default mesh for the Volumeric Light Scattering post-process
  69887. * @param {string} The mesh name
  69888. * @param {BABYLON.Scene} The scene where to create the mesh
  69889. * @return {BABYLON.Mesh} the default mesh
  69890. */
  69891. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69892. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69893. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69894. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69895. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69896. mesh.material = material;
  69897. return mesh;
  69898. };
  69899. __decorate([
  69900. BABYLON.serializeAsVector3()
  69901. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69902. __decorate([
  69903. BABYLON.serialize()
  69904. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69905. __decorate([
  69906. BABYLON.serialize()
  69907. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69908. __decorate([
  69909. BABYLON.serializeAsMeshReference()
  69910. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69911. __decorate([
  69912. BABYLON.serialize()
  69913. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69914. __decorate([
  69915. BABYLON.serialize()
  69916. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69917. __decorate([
  69918. BABYLON.serialize()
  69919. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69920. __decorate([
  69921. BABYLON.serialize()
  69922. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69923. __decorate([
  69924. BABYLON.serialize()
  69925. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69926. return VolumetricLightScatteringPostProcess;
  69927. }(BABYLON.PostProcess));
  69928. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69929. })(BABYLON || (BABYLON = {}));
  69930. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69931. //
  69932. // This post-process allows the modification of rendered colors by using
  69933. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69934. //
  69935. // The object needs to be provided an url to a texture containing the color
  69936. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69937. // Use an image editing software to tweak the LUT to match your needs.
  69938. //
  69939. // For an example of a color LUT, see here:
  69940. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69941. // For explanations on color grading, see here:
  69942. // http://udn.epicgames.com/Three/ColorGrading.html
  69943. //
  69944. var BABYLON;
  69945. (function (BABYLON) {
  69946. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69947. __extends(ColorCorrectionPostProcess, _super);
  69948. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69949. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69950. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69951. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69952. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69953. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69954. _this.onApply = function (effect) {
  69955. effect.setTexture("colorTable", _this._colorTableTexture);
  69956. };
  69957. return _this;
  69958. }
  69959. return ColorCorrectionPostProcess;
  69960. }(BABYLON.PostProcess));
  69961. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69962. })(BABYLON || (BABYLON = {}));
  69963. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69964. var BABYLON;
  69965. (function (BABYLON) {
  69966. var TonemappingOperator;
  69967. (function (TonemappingOperator) {
  69968. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69969. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69970. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69971. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69972. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69973. ;
  69974. var TonemapPostProcess = /** @class */ (function (_super) {
  69975. __extends(TonemapPostProcess, _super);
  69976. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69978. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69979. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69980. _this._operator = _operator;
  69981. _this.exposureAdjustment = exposureAdjustment;
  69982. var defines = "#define ";
  69983. if (_this._operator === TonemappingOperator.Hable)
  69984. defines += "HABLE_TONEMAPPING";
  69985. else if (_this._operator === TonemappingOperator.Reinhard)
  69986. defines += "REINHARD_TONEMAPPING";
  69987. else if (_this._operator === TonemappingOperator.HejiDawson)
  69988. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69989. else if (_this._operator === TonemappingOperator.Photographic)
  69990. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69991. //sadly a second call to create the effect.
  69992. _this.updateEffect(defines);
  69993. _this.onApply = function (effect) {
  69994. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69995. };
  69996. return _this;
  69997. }
  69998. return TonemapPostProcess;
  69999. }(BABYLON.PostProcess));
  70000. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70001. })(BABYLON || (BABYLON = {}));
  70002. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70003. var BABYLON;
  70004. (function (BABYLON) {
  70005. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70006. __extends(DisplayPassPostProcess, _super);
  70007. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70008. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70009. }
  70010. return DisplayPassPostProcess;
  70011. }(BABYLON.PostProcess));
  70012. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70013. })(BABYLON || (BABYLON = {}));
  70014. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70015. var BABYLON;
  70016. (function (BABYLON) {
  70017. var HighlightsPostProcess = /** @class */ (function (_super) {
  70018. __extends(HighlightsPostProcess, _super);
  70019. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70020. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70021. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70022. }
  70023. return HighlightsPostProcess;
  70024. }(BABYLON.PostProcess));
  70025. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70026. })(BABYLON || (BABYLON = {}));
  70027. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70028. var BABYLON;
  70029. (function (BABYLON) {
  70030. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70031. __extends(ImageProcessingPostProcess, _super);
  70032. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70033. if (camera === void 0) { camera = null; }
  70034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70035. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70036. _this._fromLinearSpace = true;
  70037. /**
  70038. * Defines cache preventing GC.
  70039. */
  70040. _this._defines = {
  70041. IMAGEPROCESSING: false,
  70042. VIGNETTE: false,
  70043. VIGNETTEBLENDMODEMULTIPLY: false,
  70044. VIGNETTEBLENDMODEOPAQUE: false,
  70045. TONEMAPPING: false,
  70046. CONTRAST: false,
  70047. COLORCURVES: false,
  70048. COLORGRADING: false,
  70049. COLORGRADING3D: false,
  70050. FROMLINEARSPACE: false,
  70051. SAMPLER3DGREENDEPTH: false,
  70052. SAMPLER3DBGRMAP: false,
  70053. IMAGEPROCESSINGPOSTPROCESS: false,
  70054. EXPOSURE: false,
  70055. GRAIN: false,
  70056. };
  70057. // Setup the configuration as forced by the constructor. This would then not force the
  70058. // scene materials output in linear space and let untouched the default forward pass.
  70059. if (imageProcessingConfiguration) {
  70060. imageProcessingConfiguration.applyByPostProcess = true;
  70061. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70062. // This will cause the shader to be compiled
  70063. _this.fromLinearSpace = false;
  70064. }
  70065. else {
  70066. _this._attachImageProcessingConfiguration(null, true);
  70067. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70068. }
  70069. _this.onApply = function (effect) {
  70070. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70071. };
  70072. return _this;
  70073. }
  70074. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70075. /**
  70076. * Gets the image processing configuration used either in this material.
  70077. */
  70078. get: function () {
  70079. return this._imageProcessingConfiguration;
  70080. },
  70081. /**
  70082. * Sets the Default image processing configuration used either in the this material.
  70083. *
  70084. * If sets to null, the scene one is in use.
  70085. */
  70086. set: function (value) {
  70087. this._attachImageProcessingConfiguration(value);
  70088. },
  70089. enumerable: true,
  70090. configurable: true
  70091. });
  70092. /**
  70093. * Attaches a new image processing configuration to the PBR Material.
  70094. * @param configuration
  70095. */
  70096. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70097. var _this = this;
  70098. if (doNotBuild === void 0) { doNotBuild = false; }
  70099. if (configuration === this._imageProcessingConfiguration) {
  70100. return;
  70101. }
  70102. // Detaches observer.
  70103. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70104. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70105. }
  70106. // Pick the scene configuration if needed.
  70107. if (!configuration) {
  70108. var scene = null;
  70109. var engine = this.getEngine();
  70110. var camera = this.getCamera();
  70111. if (camera) {
  70112. scene = camera.getScene();
  70113. }
  70114. else if (engine && engine.scenes) {
  70115. var scenes = engine.scenes;
  70116. scene = scenes[scenes.length - 1];
  70117. }
  70118. else {
  70119. scene = BABYLON.Engine.LastCreatedScene;
  70120. }
  70121. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70122. }
  70123. else {
  70124. this._imageProcessingConfiguration = configuration;
  70125. }
  70126. // Attaches observer.
  70127. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70128. _this._updateParameters();
  70129. });
  70130. // Ensure the effect will be rebuilt.
  70131. if (!doNotBuild) {
  70132. this._updateParameters();
  70133. }
  70134. };
  70135. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70136. /**
  70137. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70138. */
  70139. get: function () {
  70140. return this.imageProcessingConfiguration.colorCurves;
  70141. },
  70142. /**
  70143. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70144. */
  70145. set: function (value) {
  70146. this.imageProcessingConfiguration.colorCurves = value;
  70147. },
  70148. enumerable: true,
  70149. configurable: true
  70150. });
  70151. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70152. /**
  70153. * Gets wether the color curves effect is enabled.
  70154. */
  70155. get: function () {
  70156. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70157. },
  70158. /**
  70159. * Sets wether the color curves effect is enabled.
  70160. */
  70161. set: function (value) {
  70162. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70163. },
  70164. enumerable: true,
  70165. configurable: true
  70166. });
  70167. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70168. /**
  70169. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70170. */
  70171. get: function () {
  70172. return this.imageProcessingConfiguration.colorGradingTexture;
  70173. },
  70174. /**
  70175. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70176. */
  70177. set: function (value) {
  70178. this.imageProcessingConfiguration.colorGradingTexture = value;
  70179. },
  70180. enumerable: true,
  70181. configurable: true
  70182. });
  70183. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70184. /**
  70185. * Gets wether the color grading effect is enabled.
  70186. */
  70187. get: function () {
  70188. return this.imageProcessingConfiguration.colorGradingEnabled;
  70189. },
  70190. /**
  70191. * Gets wether the color grading effect is enabled.
  70192. */
  70193. set: function (value) {
  70194. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70195. },
  70196. enumerable: true,
  70197. configurable: true
  70198. });
  70199. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70200. /**
  70201. * Gets exposure used in the effect.
  70202. */
  70203. get: function () {
  70204. return this.imageProcessingConfiguration.exposure;
  70205. },
  70206. /**
  70207. * Sets exposure used in the effect.
  70208. */
  70209. set: function (value) {
  70210. this.imageProcessingConfiguration.exposure = value;
  70211. },
  70212. enumerable: true,
  70213. configurable: true
  70214. });
  70215. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70216. /**
  70217. * Gets wether tonemapping is enabled or not.
  70218. */
  70219. get: function () {
  70220. return this._imageProcessingConfiguration.toneMappingEnabled;
  70221. },
  70222. /**
  70223. * Sets wether tonemapping is enabled or not
  70224. */
  70225. set: function (value) {
  70226. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70227. },
  70228. enumerable: true,
  70229. configurable: true
  70230. });
  70231. ;
  70232. ;
  70233. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70234. /**
  70235. * Gets contrast used in the effect.
  70236. */
  70237. get: function () {
  70238. return this.imageProcessingConfiguration.contrast;
  70239. },
  70240. /**
  70241. * Sets contrast used in the effect.
  70242. */
  70243. set: function (value) {
  70244. this.imageProcessingConfiguration.contrast = value;
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70250. /**
  70251. * Gets Vignette stretch size.
  70252. */
  70253. get: function () {
  70254. return this.imageProcessingConfiguration.vignetteStretch;
  70255. },
  70256. /**
  70257. * Sets Vignette stretch size.
  70258. */
  70259. set: function (value) {
  70260. this.imageProcessingConfiguration.vignetteStretch = value;
  70261. },
  70262. enumerable: true,
  70263. configurable: true
  70264. });
  70265. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70266. /**
  70267. * Gets Vignette centre X Offset.
  70268. */
  70269. get: function () {
  70270. return this.imageProcessingConfiguration.vignetteCentreX;
  70271. },
  70272. /**
  70273. * Sets Vignette centre X Offset.
  70274. */
  70275. set: function (value) {
  70276. this.imageProcessingConfiguration.vignetteCentreX = value;
  70277. },
  70278. enumerable: true,
  70279. configurable: true
  70280. });
  70281. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70282. /**
  70283. * Gets Vignette centre Y Offset.
  70284. */
  70285. get: function () {
  70286. return this.imageProcessingConfiguration.vignetteCentreY;
  70287. },
  70288. /**
  70289. * Sets Vignette centre Y Offset.
  70290. */
  70291. set: function (value) {
  70292. this.imageProcessingConfiguration.vignetteCentreY = value;
  70293. },
  70294. enumerable: true,
  70295. configurable: true
  70296. });
  70297. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70298. /**
  70299. * Gets Vignette weight or intensity of the vignette effect.
  70300. */
  70301. get: function () {
  70302. return this.imageProcessingConfiguration.vignetteWeight;
  70303. },
  70304. /**
  70305. * Sets Vignette weight or intensity of the vignette effect.
  70306. */
  70307. set: function (value) {
  70308. this.imageProcessingConfiguration.vignetteWeight = value;
  70309. },
  70310. enumerable: true,
  70311. configurable: true
  70312. });
  70313. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70314. /**
  70315. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70316. * if vignetteEnabled is set to true.
  70317. */
  70318. get: function () {
  70319. return this.imageProcessingConfiguration.vignetteColor;
  70320. },
  70321. /**
  70322. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70323. * if vignetteEnabled is set to true.
  70324. */
  70325. set: function (value) {
  70326. this.imageProcessingConfiguration.vignetteColor = value;
  70327. },
  70328. enumerable: true,
  70329. configurable: true
  70330. });
  70331. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70332. /**
  70333. * Gets Camera field of view used by the Vignette effect.
  70334. */
  70335. get: function () {
  70336. return this.imageProcessingConfiguration.vignetteCameraFov;
  70337. },
  70338. /**
  70339. * Sets Camera field of view used by the Vignette effect.
  70340. */
  70341. set: function (value) {
  70342. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70343. },
  70344. enumerable: true,
  70345. configurable: true
  70346. });
  70347. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70348. /**
  70349. * Gets the vignette blend mode allowing different kind of effect.
  70350. */
  70351. get: function () {
  70352. return this.imageProcessingConfiguration.vignetteBlendMode;
  70353. },
  70354. /**
  70355. * Sets the vignette blend mode allowing different kind of effect.
  70356. */
  70357. set: function (value) {
  70358. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70359. },
  70360. enumerable: true,
  70361. configurable: true
  70362. });
  70363. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70364. /**
  70365. * Gets wether the vignette effect is enabled.
  70366. */
  70367. get: function () {
  70368. return this.imageProcessingConfiguration.vignetteEnabled;
  70369. },
  70370. /**
  70371. * Sets wether the vignette effect is enabled.
  70372. */
  70373. set: function (value) {
  70374. this.imageProcessingConfiguration.vignetteEnabled = value;
  70375. },
  70376. enumerable: true,
  70377. configurable: true
  70378. });
  70379. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70380. /**
  70381. * Gets wether the grain effect is enabled.
  70382. */
  70383. get: function () {
  70384. return this.imageProcessingConfiguration.grainEnabled;
  70385. },
  70386. /**
  70387. * Sets wether the grain effect is enabled.
  70388. */
  70389. set: function (value) {
  70390. this.imageProcessingConfiguration.grainEnabled = value;
  70391. },
  70392. enumerable: true,
  70393. configurable: true
  70394. });
  70395. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70396. /**
  70397. * Gets the grain effect's intensity.
  70398. */
  70399. get: function () {
  70400. return this.imageProcessingConfiguration.grainIntensity;
  70401. },
  70402. /**
  70403. * Sets the grain effect's intensity.
  70404. */
  70405. set: function (value) {
  70406. this.imageProcessingConfiguration.grainIntensity = value;
  70407. },
  70408. enumerable: true,
  70409. configurable: true
  70410. });
  70411. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70412. /**
  70413. * Gets wether the grain effect is animated.
  70414. */
  70415. get: function () {
  70416. return this.imageProcessingConfiguration.grainAnimated;
  70417. },
  70418. /**
  70419. * Sets wether the grain effect is animated.
  70420. */
  70421. set: function (value) {
  70422. this.imageProcessingConfiguration.grainAnimated = value;
  70423. },
  70424. enumerable: true,
  70425. configurable: true
  70426. });
  70427. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70428. /**
  70429. * Gets wether the input of the processing is in Gamma or Linear Space.
  70430. */
  70431. get: function () {
  70432. return this._fromLinearSpace;
  70433. },
  70434. /**
  70435. * Sets wether the input of the processing is in Gamma or Linear Space.
  70436. */
  70437. set: function (value) {
  70438. if (this._fromLinearSpace === value) {
  70439. return;
  70440. }
  70441. this._fromLinearSpace = value;
  70442. this._updateParameters();
  70443. },
  70444. enumerable: true,
  70445. configurable: true
  70446. });
  70447. ImageProcessingPostProcess.prototype.getClassName = function () {
  70448. return "ImageProcessingPostProcess";
  70449. };
  70450. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70451. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70452. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70453. var defines = "";
  70454. for (var define in this._defines) {
  70455. if (this._defines[define]) {
  70456. defines += "#define " + define + ";\r\n";
  70457. }
  70458. }
  70459. var samplers = ["textureSampler"];
  70460. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70461. var uniforms = ["scale"];
  70462. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70463. this.updateEffect(defines, uniforms, samplers);
  70464. };
  70465. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70466. _super.prototype.dispose.call(this, camera);
  70467. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70468. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70469. }
  70470. this.imageProcessingConfiguration.applyByPostProcess = false;
  70471. };
  70472. __decorate([
  70473. BABYLON.serialize()
  70474. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70475. return ImageProcessingPostProcess;
  70476. }(BABYLON.PostProcess));
  70477. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70478. })(BABYLON || (BABYLON = {}));
  70479. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70480. var BABYLON;
  70481. (function (BABYLON) {
  70482. var Bone = /** @class */ (function (_super) {
  70483. __extends(Bone, _super);
  70484. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70485. if (parentBone === void 0) { parentBone = null; }
  70486. if (localMatrix === void 0) { localMatrix = null; }
  70487. if (restPose === void 0) { restPose = null; }
  70488. if (baseMatrix === void 0) { baseMatrix = null; }
  70489. if (index === void 0) { index = null; }
  70490. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70491. _this.name = name;
  70492. _this.children = new Array();
  70493. _this.animations = new Array();
  70494. // Set this value to map this bone to a different index in the transform matrices.
  70495. // Set this value to -1 to exclude the bone from the transform matrices.
  70496. _this._index = null;
  70497. _this._worldTransform = new BABYLON.Matrix();
  70498. _this._absoluteTransform = new BABYLON.Matrix();
  70499. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70500. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70501. _this._scaleVector = BABYLON.Vector3.One();
  70502. _this._negateScaleChildren = BABYLON.Vector3.One();
  70503. _this._scalingDeterminant = 1;
  70504. _this._skeleton = skeleton;
  70505. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70506. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70507. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70508. _this._index = index;
  70509. skeleton.bones.push(_this);
  70510. _this.setParent(parentBone, false);
  70511. _this._updateDifferenceMatrix();
  70512. return _this;
  70513. }
  70514. Object.defineProperty(Bone.prototype, "_matrix", {
  70515. get: function () {
  70516. return this._localMatrix;
  70517. },
  70518. set: function (val) {
  70519. if (this._localMatrix) {
  70520. this._localMatrix.copyFrom(val);
  70521. }
  70522. else {
  70523. this._localMatrix = val;
  70524. }
  70525. },
  70526. enumerable: true,
  70527. configurable: true
  70528. });
  70529. // Members
  70530. Bone.prototype.getSkeleton = function () {
  70531. return this._skeleton;
  70532. };
  70533. Bone.prototype.getParent = function () {
  70534. return this._parent;
  70535. };
  70536. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70537. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70538. if (this._parent === parent) {
  70539. return;
  70540. }
  70541. if (this._parent) {
  70542. var index = this._parent.children.indexOf(this);
  70543. if (index !== -1) {
  70544. this._parent.children.splice(index, 1);
  70545. }
  70546. }
  70547. this._parent = parent;
  70548. if (this._parent) {
  70549. this._parent.children.push(this);
  70550. }
  70551. if (updateDifferenceMatrix) {
  70552. this._updateDifferenceMatrix();
  70553. }
  70554. };
  70555. Bone.prototype.getLocalMatrix = function () {
  70556. return this._localMatrix;
  70557. };
  70558. Bone.prototype.getBaseMatrix = function () {
  70559. return this._baseMatrix;
  70560. };
  70561. Bone.prototype.getRestPose = function () {
  70562. return this._restPose;
  70563. };
  70564. Bone.prototype.returnToRest = function () {
  70565. this.updateMatrix(this._restPose.clone());
  70566. };
  70567. Bone.prototype.getWorldMatrix = function () {
  70568. return this._worldTransform;
  70569. };
  70570. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70571. return this._invertedAbsoluteTransform;
  70572. };
  70573. Bone.prototype.getAbsoluteTransform = function () {
  70574. return this._absoluteTransform;
  70575. };
  70576. Object.defineProperty(Bone.prototype, "position", {
  70577. // Properties (matches AbstractMesh properties)
  70578. get: function () {
  70579. return this.getPosition();
  70580. },
  70581. set: function (newPosition) {
  70582. this.setPosition(newPosition);
  70583. },
  70584. enumerable: true,
  70585. configurable: true
  70586. });
  70587. Object.defineProperty(Bone.prototype, "rotation", {
  70588. get: function () {
  70589. return this.getRotation();
  70590. },
  70591. set: function (newRotation) {
  70592. this.setRotation(newRotation);
  70593. },
  70594. enumerable: true,
  70595. configurable: true
  70596. });
  70597. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70598. get: function () {
  70599. return this.getRotationQuaternion();
  70600. },
  70601. set: function (newRotation) {
  70602. this.setRotationQuaternion(newRotation);
  70603. },
  70604. enumerable: true,
  70605. configurable: true
  70606. });
  70607. Object.defineProperty(Bone.prototype, "scaling", {
  70608. get: function () {
  70609. return this.getScale();
  70610. },
  70611. set: function (newScaling) {
  70612. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70613. },
  70614. enumerable: true,
  70615. configurable: true
  70616. });
  70617. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70618. /**
  70619. * Gets the animation properties override
  70620. */
  70621. get: function () {
  70622. return this._skeleton.animationPropertiesOverride;
  70623. },
  70624. enumerable: true,
  70625. configurable: true
  70626. });
  70627. // Methods
  70628. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70629. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70630. this._baseMatrix = matrix.clone();
  70631. this._localMatrix = matrix.clone();
  70632. this._skeleton._markAsDirty();
  70633. if (updateDifferenceMatrix) {
  70634. this._updateDifferenceMatrix();
  70635. }
  70636. };
  70637. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70638. if (!rootMatrix) {
  70639. rootMatrix = this._baseMatrix;
  70640. }
  70641. if (this._parent) {
  70642. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70643. }
  70644. else {
  70645. this._absoluteTransform.copyFrom(rootMatrix);
  70646. }
  70647. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70648. for (var index = 0; index < this.children.length; index++) {
  70649. this.children[index]._updateDifferenceMatrix();
  70650. }
  70651. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70652. };
  70653. Bone.prototype.markAsDirty = function () {
  70654. this._currentRenderId++;
  70655. this._skeleton._markAsDirty();
  70656. };
  70657. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70658. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70659. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70660. // all animation may be coming from a library skeleton, so may need to create animation
  70661. if (this.animations.length === 0) {
  70662. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70663. this.animations[0].setKeys([]);
  70664. }
  70665. // get animation info / verify there is such a range from the source bone
  70666. var sourceRange = source.animations[0].getRange(rangeName);
  70667. if (!sourceRange) {
  70668. return false;
  70669. }
  70670. var from = sourceRange.from;
  70671. var to = sourceRange.to;
  70672. var sourceKeys = source.animations[0].getKeys();
  70673. // rescaling prep
  70674. var sourceBoneLength = source.length;
  70675. var sourceParent = source.getParent();
  70676. var parent = this.getParent();
  70677. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70678. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70679. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70680. var destKeys = this.animations[0].getKeys();
  70681. // loop vars declaration
  70682. var orig;
  70683. var origTranslation;
  70684. var mat;
  70685. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70686. orig = sourceKeys[key];
  70687. if (orig.frame >= from && orig.frame <= to) {
  70688. if (rescaleAsRequired) {
  70689. mat = orig.value.clone();
  70690. // scale based on parent ratio, when bone has parent
  70691. if (parentScalingReqd) {
  70692. origTranslation = mat.getTranslation();
  70693. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70694. // scale based on skeleton dimension ratio when root bone, and value is passed
  70695. }
  70696. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70697. origTranslation = mat.getTranslation();
  70698. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70699. // use original when root bone, and no data for skelDimensionsRatio
  70700. }
  70701. else {
  70702. mat = orig.value;
  70703. }
  70704. }
  70705. else {
  70706. mat = orig.value;
  70707. }
  70708. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70709. }
  70710. }
  70711. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70712. return true;
  70713. };
  70714. /**
  70715. * Translate the bone in local or world space.
  70716. * @param vec The amount to translate the bone.
  70717. * @param space The space that the translation is in.
  70718. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70719. */
  70720. Bone.prototype.translate = function (vec, space, mesh) {
  70721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70722. var lm = this.getLocalMatrix();
  70723. if (space == BABYLON.Space.LOCAL) {
  70724. lm.m[12] += vec.x;
  70725. lm.m[13] += vec.y;
  70726. lm.m[14] += vec.z;
  70727. }
  70728. else {
  70729. var wm = null;
  70730. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70731. if (mesh) {
  70732. wm = mesh.getWorldMatrix();
  70733. }
  70734. this._skeleton.computeAbsoluteTransforms();
  70735. var tmat = Bone._tmpMats[0];
  70736. var tvec = Bone._tmpVecs[0];
  70737. if (this._parent) {
  70738. if (mesh && wm) {
  70739. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70740. tmat.multiplyToRef(wm, tmat);
  70741. }
  70742. else {
  70743. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70744. }
  70745. }
  70746. tmat.m[12] = 0;
  70747. tmat.m[13] = 0;
  70748. tmat.m[14] = 0;
  70749. tmat.invert();
  70750. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70751. lm.m[12] += tvec.x;
  70752. lm.m[13] += tvec.y;
  70753. lm.m[14] += tvec.z;
  70754. }
  70755. this.markAsDirty();
  70756. };
  70757. /**
  70758. * Set the postion of the bone in local or world space.
  70759. * @param position The position to set the bone.
  70760. * @param space The space that the position is in.
  70761. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70762. */
  70763. Bone.prototype.setPosition = function (position, space, mesh) {
  70764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70765. var lm = this.getLocalMatrix();
  70766. if (space == BABYLON.Space.LOCAL) {
  70767. lm.m[12] = position.x;
  70768. lm.m[13] = position.y;
  70769. lm.m[14] = position.z;
  70770. }
  70771. else {
  70772. var wm = null;
  70773. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70774. if (mesh) {
  70775. wm = mesh.getWorldMatrix();
  70776. }
  70777. this._skeleton.computeAbsoluteTransforms();
  70778. var tmat = Bone._tmpMats[0];
  70779. var vec = Bone._tmpVecs[0];
  70780. if (this._parent) {
  70781. if (mesh && wm) {
  70782. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70783. tmat.multiplyToRef(wm, tmat);
  70784. }
  70785. else {
  70786. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70787. }
  70788. }
  70789. tmat.invert();
  70790. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70791. lm.m[12] = vec.x;
  70792. lm.m[13] = vec.y;
  70793. lm.m[14] = vec.z;
  70794. }
  70795. this.markAsDirty();
  70796. };
  70797. /**
  70798. * Set the absolute postion of the bone (world space).
  70799. * @param position The position to set the bone.
  70800. * @param mesh The mesh that this bone is attached to.
  70801. */
  70802. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70803. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70804. };
  70805. /**
  70806. * Set the scale of the bone on the x, y and z axes.
  70807. * @param x The scale of the bone on the x axis.
  70808. * @param x The scale of the bone on the y axis.
  70809. * @param z The scale of the bone on the z axis.
  70810. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70811. */
  70812. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70813. if (scaleChildren === void 0) { scaleChildren = false; }
  70814. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70815. if (!scaleChildren) {
  70816. this._negateScaleChildren.x = 1 / x;
  70817. this._negateScaleChildren.y = 1 / y;
  70818. this._negateScaleChildren.z = 1 / z;
  70819. }
  70820. this._syncScaleVector();
  70821. }
  70822. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70823. };
  70824. /**
  70825. * Scale the bone on the x, y and z axes.
  70826. * @param x The amount to scale the bone on the x axis.
  70827. * @param x The amount to scale the bone on the y axis.
  70828. * @param z The amount to scale the bone on the z axis.
  70829. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70830. */
  70831. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70832. if (scaleChildren === void 0) { scaleChildren = false; }
  70833. var locMat = this.getLocalMatrix();
  70834. var origLocMat = Bone._tmpMats[0];
  70835. origLocMat.copyFrom(locMat);
  70836. var origLocMatInv = Bone._tmpMats[1];
  70837. origLocMatInv.copyFrom(origLocMat);
  70838. origLocMatInv.invert();
  70839. var scaleMat = Bone._tmpMats[2];
  70840. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70841. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70842. this._scaleVector.x *= x;
  70843. this._scaleVector.y *= y;
  70844. this._scaleVector.z *= z;
  70845. locMat.multiplyToRef(origLocMatInv, locMat);
  70846. locMat.multiplyToRef(scaleMat, locMat);
  70847. locMat.multiplyToRef(origLocMat, locMat);
  70848. var parent = this.getParent();
  70849. if (parent) {
  70850. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70851. }
  70852. else {
  70853. this.getAbsoluteTransform().copyFrom(locMat);
  70854. }
  70855. var len = this.children.length;
  70856. scaleMat.invert();
  70857. for (var i = 0; i < len; i++) {
  70858. var child = this.children[i];
  70859. var cm = child.getLocalMatrix();
  70860. cm.multiplyToRef(scaleMat, cm);
  70861. var lm = child.getLocalMatrix();
  70862. lm.m[12] *= x;
  70863. lm.m[13] *= y;
  70864. lm.m[14] *= z;
  70865. }
  70866. this.computeAbsoluteTransforms();
  70867. if (scaleChildren) {
  70868. for (var i = 0; i < len; i++) {
  70869. this.children[i].scale(x, y, z, scaleChildren);
  70870. }
  70871. }
  70872. this.markAsDirty();
  70873. };
  70874. /**
  70875. * Set the yaw, pitch, and roll of the bone in local or world space.
  70876. * @param yaw The rotation of the bone on the y axis.
  70877. * @param pitch The rotation of the bone on the x axis.
  70878. * @param roll The rotation of the bone on the z axis.
  70879. * @param space The space that the axes of rotation are in.
  70880. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70881. */
  70882. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70884. var rotMat = Bone._tmpMats[0];
  70885. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70886. var rotMatInv = Bone._tmpMats[1];
  70887. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70888. rotMatInv.multiplyToRef(rotMat, rotMat);
  70889. this._rotateWithMatrix(rotMat, space, mesh);
  70890. };
  70891. /**
  70892. * Rotate the bone on an axis in local or world space.
  70893. * @param axis The axis to rotate the bone on.
  70894. * @param amount The amount to rotate the bone.
  70895. * @param space The space that the axis is in.
  70896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70897. */
  70898. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70900. var rmat = Bone._tmpMats[0];
  70901. rmat.m[12] = 0;
  70902. rmat.m[13] = 0;
  70903. rmat.m[14] = 0;
  70904. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70905. this._rotateWithMatrix(rmat, space, mesh);
  70906. };
  70907. /**
  70908. * Set the rotation of the bone to a particular axis angle in local or world space.
  70909. * @param axis The axis to rotate the bone on.
  70910. * @param angle The angle that the bone should be rotated to.
  70911. * @param space The space that the axis is in.
  70912. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70913. */
  70914. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70915. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70916. var rotMat = Bone._tmpMats[0];
  70917. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70918. var rotMatInv = Bone._tmpMats[1];
  70919. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70920. rotMatInv.multiplyToRef(rotMat, rotMat);
  70921. this._rotateWithMatrix(rotMat, space, mesh);
  70922. };
  70923. /**
  70924. * Set the euler rotation of the bone in local of world space.
  70925. * @param rotation The euler rotation that the bone should be set to.
  70926. * @param space The space that the rotation is in.
  70927. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70928. */
  70929. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70931. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70932. };
  70933. /**
  70934. * Set the quaternion rotation of the bone in local of world space.
  70935. * @param quat The quaternion rotation that the bone should be set to.
  70936. * @param space The space that the rotation is in.
  70937. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70938. */
  70939. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70941. var rotMatInv = Bone._tmpMats[0];
  70942. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70943. var rotMat = Bone._tmpMats[1];
  70944. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70945. rotMatInv.multiplyToRef(rotMat, rotMat);
  70946. this._rotateWithMatrix(rotMat, space, mesh);
  70947. };
  70948. /**
  70949. * Set the rotation matrix of the bone in local of world space.
  70950. * @param rotMat The rotation matrix that the bone should be set to.
  70951. * @param space The space that the rotation is in.
  70952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70953. */
  70954. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70956. var rotMatInv = Bone._tmpMats[0];
  70957. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70958. var rotMat2 = Bone._tmpMats[1];
  70959. rotMat2.copyFrom(rotMat);
  70960. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70961. this._rotateWithMatrix(rotMat2, space, mesh);
  70962. };
  70963. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70965. var lmat = this.getLocalMatrix();
  70966. var lx = lmat.m[12];
  70967. var ly = lmat.m[13];
  70968. var lz = lmat.m[14];
  70969. var parent = this.getParent();
  70970. var parentScale = Bone._tmpMats[3];
  70971. var parentScaleInv = Bone._tmpMats[4];
  70972. if (parent) {
  70973. if (space == BABYLON.Space.WORLD) {
  70974. if (mesh) {
  70975. parentScale.copyFrom(mesh.getWorldMatrix());
  70976. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70977. }
  70978. else {
  70979. parentScale.copyFrom(parent.getAbsoluteTransform());
  70980. }
  70981. }
  70982. else {
  70983. parentScale = parent._scaleMatrix;
  70984. }
  70985. parentScaleInv.copyFrom(parentScale);
  70986. parentScaleInv.invert();
  70987. lmat.multiplyToRef(parentScale, lmat);
  70988. lmat.multiplyToRef(rmat, lmat);
  70989. lmat.multiplyToRef(parentScaleInv, lmat);
  70990. }
  70991. else {
  70992. if (space == BABYLON.Space.WORLD && mesh) {
  70993. parentScale.copyFrom(mesh.getWorldMatrix());
  70994. parentScaleInv.copyFrom(parentScale);
  70995. parentScaleInv.invert();
  70996. lmat.multiplyToRef(parentScale, lmat);
  70997. lmat.multiplyToRef(rmat, lmat);
  70998. lmat.multiplyToRef(parentScaleInv, lmat);
  70999. }
  71000. else {
  71001. lmat.multiplyToRef(rmat, lmat);
  71002. }
  71003. }
  71004. lmat.m[12] = lx;
  71005. lmat.m[13] = ly;
  71006. lmat.m[14] = lz;
  71007. this.computeAbsoluteTransforms();
  71008. this.markAsDirty();
  71009. };
  71010. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71012. if (space == BABYLON.Space.WORLD) {
  71013. var scaleMatrix = Bone._tmpMats[2];
  71014. scaleMatrix.copyFrom(this._scaleMatrix);
  71015. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71016. if (mesh) {
  71017. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71018. var meshScale = Bone._tmpMats[3];
  71019. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71020. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71021. }
  71022. rotMatInv.invert();
  71023. scaleMatrix.m[0] *= this._scalingDeterminant;
  71024. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71025. }
  71026. else {
  71027. rotMatInv.copyFrom(this.getLocalMatrix());
  71028. rotMatInv.invert();
  71029. var scaleMatrix = Bone._tmpMats[2];
  71030. scaleMatrix.copyFrom(this._scaleMatrix);
  71031. if (this._parent) {
  71032. var pscaleMatrix = Bone._tmpMats[3];
  71033. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71034. pscaleMatrix.invert();
  71035. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71036. }
  71037. else {
  71038. scaleMatrix.m[0] *= this._scalingDeterminant;
  71039. }
  71040. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71041. }
  71042. };
  71043. /**
  71044. * Get the scale of the bone
  71045. * @returns the scale of the bone
  71046. */
  71047. Bone.prototype.getScale = function () {
  71048. return this._scaleVector.clone();
  71049. };
  71050. /**
  71051. * Copy the scale of the bone to a vector3.
  71052. * @param result The vector3 to copy the scale to
  71053. */
  71054. Bone.prototype.getScaleToRef = function (result) {
  71055. result.copyFrom(this._scaleVector);
  71056. };
  71057. /**
  71058. * Get the position of the bone in local or world space.
  71059. * @param space The space that the returned position is in.
  71060. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71061. * @returns The position of the bone
  71062. */
  71063. Bone.prototype.getPosition = function (space, mesh) {
  71064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71065. if (mesh === void 0) { mesh = null; }
  71066. var pos = BABYLON.Vector3.Zero();
  71067. this.getPositionToRef(space, mesh, pos);
  71068. return pos;
  71069. };
  71070. /**
  71071. * Copy the position of the bone to a vector3 in local or world space.
  71072. * @param space The space that the returned position is in.
  71073. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71074. * @param result The vector3 to copy the position to.
  71075. */
  71076. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71077. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71078. if (space == BABYLON.Space.LOCAL) {
  71079. var lm = this.getLocalMatrix();
  71080. result.x = lm.m[12];
  71081. result.y = lm.m[13];
  71082. result.z = lm.m[14];
  71083. }
  71084. else {
  71085. var wm = null;
  71086. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71087. if (mesh) {
  71088. wm = mesh.getWorldMatrix();
  71089. }
  71090. this._skeleton.computeAbsoluteTransforms();
  71091. var tmat = Bone._tmpMats[0];
  71092. if (mesh && wm) {
  71093. tmat.copyFrom(this.getAbsoluteTransform());
  71094. tmat.multiplyToRef(wm, tmat);
  71095. }
  71096. else {
  71097. tmat = this.getAbsoluteTransform();
  71098. }
  71099. result.x = tmat.m[12];
  71100. result.y = tmat.m[13];
  71101. result.z = tmat.m[14];
  71102. }
  71103. };
  71104. /**
  71105. * Get the absolute position of the bone (world space).
  71106. * @param mesh The mesh that this bone is attached to.
  71107. * @returns The absolute position of the bone
  71108. */
  71109. Bone.prototype.getAbsolutePosition = function (mesh) {
  71110. if (mesh === void 0) { mesh = null; }
  71111. var pos = BABYLON.Vector3.Zero();
  71112. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71113. return pos;
  71114. };
  71115. /**
  71116. * Copy the absolute position of the bone (world space) to the result param.
  71117. * @param mesh The mesh that this bone is attached to.
  71118. * @param result The vector3 to copy the absolute position to.
  71119. */
  71120. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71121. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71122. };
  71123. /**
  71124. * Compute the absolute transforms of this bone and its children.
  71125. */
  71126. Bone.prototype.computeAbsoluteTransforms = function () {
  71127. if (this._parent) {
  71128. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71129. }
  71130. else {
  71131. this._absoluteTransform.copyFrom(this._localMatrix);
  71132. var poseMatrix = this._skeleton.getPoseMatrix();
  71133. if (poseMatrix) {
  71134. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71135. }
  71136. }
  71137. var children = this.children;
  71138. var len = children.length;
  71139. for (var i = 0; i < len; i++) {
  71140. children[i].computeAbsoluteTransforms();
  71141. }
  71142. };
  71143. Bone.prototype._syncScaleVector = function () {
  71144. var lm = this.getLocalMatrix();
  71145. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71146. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71147. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71148. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71149. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71150. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71151. this._scaleVector.x = xs * Math.sqrt(xsq);
  71152. this._scaleVector.y = ys * Math.sqrt(ysq);
  71153. this._scaleVector.z = zs * Math.sqrt(zsq);
  71154. if (this._parent) {
  71155. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71156. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71157. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71158. }
  71159. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  71160. };
  71161. /**
  71162. * Get the world direction from an axis that is in the local space of the bone.
  71163. * @param localAxis The local direction that is used to compute the world direction.
  71164. * @param mesh The mesh that this bone is attached to.
  71165. * @returns The world direction
  71166. */
  71167. Bone.prototype.getDirection = function (localAxis, mesh) {
  71168. if (mesh === void 0) { mesh = null; }
  71169. var result = BABYLON.Vector3.Zero();
  71170. this.getDirectionToRef(localAxis, mesh, result);
  71171. return result;
  71172. };
  71173. /**
  71174. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71175. * @param localAxis The local direction that is used to compute the world direction.
  71176. * @param mesh The mesh that this bone is attached to.
  71177. * @param result The vector3 that the world direction will be copied to.
  71178. */
  71179. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71180. if (mesh === void 0) { mesh = null; }
  71181. var wm = null;
  71182. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71183. if (mesh) {
  71184. wm = mesh.getWorldMatrix();
  71185. }
  71186. this._skeleton.computeAbsoluteTransforms();
  71187. var mat = Bone._tmpMats[0];
  71188. mat.copyFrom(this.getAbsoluteTransform());
  71189. if (mesh && wm) {
  71190. mat.multiplyToRef(wm, mat);
  71191. }
  71192. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71193. result.normalize();
  71194. };
  71195. /**
  71196. * Get the euler rotation of the bone in local or world space.
  71197. * @param space The space that the rotation should be in.
  71198. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71199. * @returns The euler rotation
  71200. */
  71201. Bone.prototype.getRotation = function (space, mesh) {
  71202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71203. if (mesh === void 0) { mesh = null; }
  71204. var result = BABYLON.Vector3.Zero();
  71205. this.getRotationToRef(space, mesh, result);
  71206. return result;
  71207. };
  71208. /**
  71209. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71210. * @param space The space that the rotation should be in.
  71211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71212. * @param result The vector3 that the rotation should be copied to.
  71213. */
  71214. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71216. if (mesh === void 0) { mesh = null; }
  71217. var quat = Bone._tmpQuat;
  71218. this.getRotationQuaternionToRef(space, mesh, quat);
  71219. quat.toEulerAnglesToRef(result);
  71220. };
  71221. /**
  71222. * Get the quaternion rotation of the bone in either local or world space.
  71223. * @param space The space that the rotation should be in.
  71224. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71225. * @returns The quaternion rotation
  71226. */
  71227. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71229. if (mesh === void 0) { mesh = null; }
  71230. var result = BABYLON.Quaternion.Identity();
  71231. this.getRotationQuaternionToRef(space, mesh, result);
  71232. return result;
  71233. };
  71234. /**
  71235. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71236. * @param space The space that the rotation should be in.
  71237. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71238. * @param result The quaternion that the rotation should be copied to.
  71239. */
  71240. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71241. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71242. if (mesh === void 0) { mesh = null; }
  71243. if (space == BABYLON.Space.LOCAL) {
  71244. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71245. }
  71246. else {
  71247. var mat = Bone._tmpMats[0];
  71248. var amat = this.getAbsoluteTransform();
  71249. if (mesh) {
  71250. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71251. }
  71252. else {
  71253. mat.copyFrom(amat);
  71254. }
  71255. mat.m[0] *= this._scalingDeterminant;
  71256. mat.m[1] *= this._scalingDeterminant;
  71257. mat.m[2] *= this._scalingDeterminant;
  71258. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71259. }
  71260. };
  71261. /**
  71262. * Get the rotation matrix of the bone in local or world space.
  71263. * @param space The space that the rotation should be in.
  71264. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71265. * @returns The rotation matrix
  71266. */
  71267. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71269. var result = BABYLON.Matrix.Identity();
  71270. this.getRotationMatrixToRef(space, mesh, result);
  71271. return result;
  71272. };
  71273. /**
  71274. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71275. * @param space The space that the rotation should be in.
  71276. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71277. * @param result The quaternion that the rotation should be copied to.
  71278. */
  71279. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71280. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71281. if (space == BABYLON.Space.LOCAL) {
  71282. this.getLocalMatrix().getRotationMatrixToRef(result);
  71283. }
  71284. else {
  71285. var mat = Bone._tmpMats[0];
  71286. var amat = this.getAbsoluteTransform();
  71287. if (mesh) {
  71288. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71289. }
  71290. else {
  71291. mat.copyFrom(amat);
  71292. }
  71293. mat.m[0] *= this._scalingDeterminant;
  71294. mat.m[1] *= this._scalingDeterminant;
  71295. mat.m[2] *= this._scalingDeterminant;
  71296. mat.getRotationMatrixToRef(result);
  71297. }
  71298. };
  71299. /**
  71300. * Get the world position of a point that is in the local space of the bone.
  71301. * @param position The local position
  71302. * @param mesh The mesh that this bone is attached to.
  71303. * @returns The world position
  71304. */
  71305. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71306. if (mesh === void 0) { mesh = null; }
  71307. var result = BABYLON.Vector3.Zero();
  71308. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71309. return result;
  71310. };
  71311. /**
  71312. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71313. * @param position The local position
  71314. * @param mesh The mesh that this bone is attached to.
  71315. * @param result The vector3 that the world position should be copied to.
  71316. */
  71317. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71318. if (mesh === void 0) { mesh = null; }
  71319. var wm = null;
  71320. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71321. if (mesh) {
  71322. wm = mesh.getWorldMatrix();
  71323. }
  71324. this._skeleton.computeAbsoluteTransforms();
  71325. var tmat = Bone._tmpMats[0];
  71326. if (mesh && wm) {
  71327. tmat.copyFrom(this.getAbsoluteTransform());
  71328. tmat.multiplyToRef(wm, tmat);
  71329. }
  71330. else {
  71331. tmat = this.getAbsoluteTransform();
  71332. }
  71333. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71334. };
  71335. /**
  71336. * Get the local position of a point that is in world space.
  71337. * @param position The world position
  71338. * @param mesh The mesh that this bone is attached to.
  71339. * @returns The local position
  71340. */
  71341. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71342. if (mesh === void 0) { mesh = null; }
  71343. var result = BABYLON.Vector3.Zero();
  71344. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71345. return result;
  71346. };
  71347. /**
  71348. * Get the local position of a point that is in world space and copy it to the result param.
  71349. * @param position The world position
  71350. * @param mesh The mesh that this bone is attached to.
  71351. * @param result The vector3 that the local position should be copied to.
  71352. */
  71353. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71354. if (mesh === void 0) { mesh = null; }
  71355. var wm = null;
  71356. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71357. if (mesh) {
  71358. wm = mesh.getWorldMatrix();
  71359. }
  71360. this._skeleton.computeAbsoluteTransforms();
  71361. var tmat = Bone._tmpMats[0];
  71362. tmat.copyFrom(this.getAbsoluteTransform());
  71363. if (mesh && wm) {
  71364. tmat.multiplyToRef(wm, tmat);
  71365. }
  71366. tmat.invert();
  71367. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71368. };
  71369. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71370. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71371. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71372. return Bone;
  71373. }(BABYLON.Node));
  71374. BABYLON.Bone = Bone;
  71375. })(BABYLON || (BABYLON = {}));
  71376. //# sourceMappingURL=babylon.bone.js.map
  71377. var BABYLON;
  71378. (function (BABYLON) {
  71379. var BoneIKController = /** @class */ (function () {
  71380. function BoneIKController(mesh, bone, options) {
  71381. this.targetPosition = BABYLON.Vector3.Zero();
  71382. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71383. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71384. this.poleAngle = 0;
  71385. this.slerpAmount = 1;
  71386. this._bone1Quat = BABYLON.Quaternion.Identity();
  71387. this._bone1Mat = BABYLON.Matrix.Identity();
  71388. this._bone2Ang = Math.PI;
  71389. this._maxAngle = Math.PI;
  71390. this._rightHandedSystem = false;
  71391. this._bendAxis = BABYLON.Vector3.Right();
  71392. this._slerping = false;
  71393. this._adjustRoll = 0;
  71394. this._bone2 = bone;
  71395. this._bone1 = bone.getParent();
  71396. if (!this._bone1) {
  71397. return;
  71398. }
  71399. this.mesh = mesh;
  71400. var bonePos = bone.getPosition();
  71401. if (bone.getAbsoluteTransform().determinant() > 0) {
  71402. this._rightHandedSystem = true;
  71403. this._bendAxis.x = 0;
  71404. this._bendAxis.y = 0;
  71405. this._bendAxis.z = -1;
  71406. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71407. this._adjustRoll = Math.PI * .5;
  71408. this._bendAxis.z = 1;
  71409. }
  71410. }
  71411. if (this._bone1.length) {
  71412. var boneScale1 = this._bone1.getScale();
  71413. var boneScale2 = this._bone2.getScale();
  71414. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71415. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71416. }
  71417. else if (this._bone1.children[0]) {
  71418. mesh.computeWorldMatrix(true);
  71419. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71420. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71421. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71422. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71423. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71424. }
  71425. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71426. this.maxAngle = Math.PI;
  71427. if (options) {
  71428. if (options.targetMesh) {
  71429. this.targetMesh = options.targetMesh;
  71430. this.targetMesh.computeWorldMatrix(true);
  71431. }
  71432. if (options.poleTargetMesh) {
  71433. this.poleTargetMesh = options.poleTargetMesh;
  71434. this.poleTargetMesh.computeWorldMatrix(true);
  71435. }
  71436. else if (options.poleTargetBone) {
  71437. this.poleTargetBone = options.poleTargetBone;
  71438. }
  71439. else if (this._bone1.getParent()) {
  71440. this.poleTargetBone = this._bone1.getParent();
  71441. }
  71442. if (options.poleTargetLocalOffset) {
  71443. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71444. }
  71445. if (options.poleAngle) {
  71446. this.poleAngle = options.poleAngle;
  71447. }
  71448. if (options.bendAxis) {
  71449. this._bendAxis.copyFrom(options.bendAxis);
  71450. }
  71451. if (options.maxAngle) {
  71452. this.maxAngle = options.maxAngle;
  71453. }
  71454. if (options.slerpAmount) {
  71455. this.slerpAmount = options.slerpAmount;
  71456. }
  71457. }
  71458. }
  71459. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71460. get: function () {
  71461. return this._maxAngle;
  71462. },
  71463. set: function (value) {
  71464. this._setMaxAngle(value);
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. BoneIKController.prototype._setMaxAngle = function (ang) {
  71470. if (ang < 0) {
  71471. ang = 0;
  71472. }
  71473. if (ang > Math.PI || ang == undefined) {
  71474. ang = Math.PI;
  71475. }
  71476. this._maxAngle = ang;
  71477. var a = this._bone1Length;
  71478. var b = this._bone2Length;
  71479. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71480. };
  71481. BoneIKController.prototype.update = function () {
  71482. var bone1 = this._bone1;
  71483. if (!bone1) {
  71484. return;
  71485. }
  71486. var target = this.targetPosition;
  71487. var poleTarget = this.poleTargetPosition;
  71488. var mat1 = BoneIKController._tmpMats[0];
  71489. var mat2 = BoneIKController._tmpMats[1];
  71490. if (this.targetMesh) {
  71491. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71492. }
  71493. if (this.poleTargetBone) {
  71494. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71495. }
  71496. else if (this.poleTargetMesh) {
  71497. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71498. }
  71499. var bonePos = BoneIKController._tmpVecs[0];
  71500. var zaxis = BoneIKController._tmpVecs[1];
  71501. var xaxis = BoneIKController._tmpVecs[2];
  71502. var yaxis = BoneIKController._tmpVecs[3];
  71503. var upAxis = BoneIKController._tmpVecs[4];
  71504. var _tmpQuat = BoneIKController._tmpQuat;
  71505. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71506. poleTarget.subtractToRef(bonePos, upAxis);
  71507. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71508. upAxis.y = 1;
  71509. }
  71510. else {
  71511. upAxis.normalize();
  71512. }
  71513. target.subtractToRef(bonePos, yaxis);
  71514. yaxis.normalize();
  71515. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71516. zaxis.normalize();
  71517. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71518. xaxis.normalize();
  71519. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71520. var a = this._bone1Length;
  71521. var b = this._bone2Length;
  71522. var c = BABYLON.Vector3.Distance(bonePos, target);
  71523. if (this._maxReach > 0) {
  71524. c = Math.min(this._maxReach, c);
  71525. }
  71526. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71527. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71528. if (acosa > 1) {
  71529. acosa = 1;
  71530. }
  71531. if (acosb > 1) {
  71532. acosb = 1;
  71533. }
  71534. if (acosa < -1) {
  71535. acosa = -1;
  71536. }
  71537. if (acosb < -1) {
  71538. acosb = -1;
  71539. }
  71540. var angA = Math.acos(acosa);
  71541. var angB = Math.acos(acosb);
  71542. var angC = -angA - angB;
  71543. if (this._rightHandedSystem) {
  71544. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71545. mat2.multiplyToRef(mat1, mat1);
  71546. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71547. mat2.multiplyToRef(mat1, mat1);
  71548. }
  71549. else {
  71550. var _tmpVec = BoneIKController._tmpVecs[5];
  71551. _tmpVec.copyFrom(this._bendAxis);
  71552. _tmpVec.x *= -1;
  71553. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71554. mat2.multiplyToRef(mat1, mat1);
  71555. }
  71556. if (this.poleAngle) {
  71557. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71558. mat1.multiplyToRef(mat2, mat1);
  71559. }
  71560. if (this._bone1) {
  71561. if (this.slerpAmount < 1) {
  71562. if (!this._slerping) {
  71563. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71564. }
  71565. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71566. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71567. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71568. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71569. this._slerping = true;
  71570. }
  71571. else {
  71572. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71573. this._bone1Mat.copyFrom(mat1);
  71574. this._slerping = false;
  71575. }
  71576. }
  71577. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71578. this._bone2Ang = angC;
  71579. };
  71580. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71581. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71582. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71583. return BoneIKController;
  71584. }());
  71585. BABYLON.BoneIKController = BoneIKController;
  71586. })(BABYLON || (BABYLON = {}));
  71587. //# sourceMappingURL=babylon.boneIKController.js.map
  71588. var BABYLON;
  71589. (function (BABYLON) {
  71590. var BoneLookController = /** @class */ (function () {
  71591. /**
  71592. * Create a BoneLookController
  71593. * @param mesh the mesh that the bone belongs to
  71594. * @param bone the bone that will be looking to the target
  71595. * @param target the target Vector3 to look at
  71596. * @param settings optional settings:
  71597. * - maxYaw: the maximum angle the bone will yaw to
  71598. * - minYaw: the minimum angle the bone will yaw to
  71599. * - maxPitch: the maximum angle the bone will pitch to
  71600. * - minPitch: the minimum angle the bone will yaw to
  71601. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71602. * - upAxis: the up axis of the coordinate system
  71603. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71604. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71605. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71606. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71607. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71608. * - adjustRoll: used to make an adjustment to the roll of the bone
  71609. **/
  71610. function BoneLookController(mesh, bone, target, options) {
  71611. /**
  71612. * The up axis of the coordinate system that is used when the bone is rotated.
  71613. */
  71614. this.upAxis = BABYLON.Vector3.Up();
  71615. /**
  71616. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71617. */
  71618. this.upAxisSpace = BABYLON.Space.LOCAL;
  71619. /**
  71620. * Used to make an adjustment to the yaw of the bone.
  71621. */
  71622. this.adjustYaw = 0;
  71623. /**
  71624. * Used to make an adjustment to the pitch of the bone.
  71625. */
  71626. this.adjustPitch = 0;
  71627. /**
  71628. * Used to make an adjustment to the roll of the bone.
  71629. */
  71630. this.adjustRoll = 0;
  71631. /**
  71632. * 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).
  71633. */
  71634. this.slerpAmount = 1;
  71635. this._boneQuat = BABYLON.Quaternion.Identity();
  71636. this._slerping = false;
  71637. this._firstFrameSkipped = false;
  71638. this._fowardAxis = BABYLON.Vector3.Forward();
  71639. this.mesh = mesh;
  71640. this.bone = bone;
  71641. this.target = target;
  71642. if (options) {
  71643. if (options.adjustYaw) {
  71644. this.adjustYaw = options.adjustYaw;
  71645. }
  71646. if (options.adjustPitch) {
  71647. this.adjustPitch = options.adjustPitch;
  71648. }
  71649. if (options.adjustRoll) {
  71650. this.adjustRoll = options.adjustRoll;
  71651. }
  71652. if (options.maxYaw != null) {
  71653. this.maxYaw = options.maxYaw;
  71654. }
  71655. else {
  71656. this.maxYaw = Math.PI;
  71657. }
  71658. if (options.minYaw != null) {
  71659. this.minYaw = options.minYaw;
  71660. }
  71661. else {
  71662. this.minYaw = -Math.PI;
  71663. }
  71664. if (options.maxPitch != null) {
  71665. this.maxPitch = options.maxPitch;
  71666. }
  71667. else {
  71668. this.maxPitch = Math.PI;
  71669. }
  71670. if (options.minPitch != null) {
  71671. this.minPitch = options.minPitch;
  71672. }
  71673. else {
  71674. this.minPitch = -Math.PI;
  71675. }
  71676. if (options.slerpAmount != null) {
  71677. this.slerpAmount = options.slerpAmount;
  71678. }
  71679. if (options.upAxis != null) {
  71680. this.upAxis = options.upAxis;
  71681. }
  71682. if (options.upAxisSpace != null) {
  71683. this.upAxisSpace = options.upAxisSpace;
  71684. }
  71685. if (options.yawAxis != null || options.pitchAxis != null) {
  71686. var newYawAxis = BABYLON.Axis.Y;
  71687. var newPitchAxis = BABYLON.Axis.X;
  71688. if (options.yawAxis != null) {
  71689. newYawAxis = options.yawAxis.clone();
  71690. newYawAxis.normalize();
  71691. }
  71692. if (options.pitchAxis != null) {
  71693. newPitchAxis = options.pitchAxis.clone();
  71694. newPitchAxis.normalize();
  71695. }
  71696. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71697. this._transformYawPitch = BABYLON.Matrix.Identity();
  71698. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71699. this._transformYawPitchInv = this._transformYawPitch.clone();
  71700. this._transformYawPitch.invert();
  71701. }
  71702. }
  71703. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71704. this.upAxisSpace = BABYLON.Space.LOCAL;
  71705. }
  71706. }
  71707. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71708. /**
  71709. * Get/set the minimum yaw angle that the bone can look to.
  71710. */
  71711. get: function () {
  71712. return this._minYaw;
  71713. },
  71714. set: function (value) {
  71715. this._minYaw = value;
  71716. this._minYawSin = Math.sin(value);
  71717. this._minYawCos = Math.cos(value);
  71718. if (this._maxYaw != null) {
  71719. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71720. this._yawRange = this._maxYaw - this._minYaw;
  71721. }
  71722. },
  71723. enumerable: true,
  71724. configurable: true
  71725. });
  71726. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71727. /**
  71728. * Get/set the maximum yaw angle that the bone can look to.
  71729. */
  71730. get: function () {
  71731. return this._maxYaw;
  71732. },
  71733. set: function (value) {
  71734. this._maxYaw = value;
  71735. this._maxYawSin = Math.sin(value);
  71736. this._maxYawCos = Math.cos(value);
  71737. if (this._minYaw != null) {
  71738. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71739. this._yawRange = this._maxYaw - this._minYaw;
  71740. }
  71741. },
  71742. enumerable: true,
  71743. configurable: true
  71744. });
  71745. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71746. /**
  71747. * Get/set the minimum pitch angle that the bone can look to.
  71748. */
  71749. get: function () {
  71750. return this._minPitch;
  71751. },
  71752. set: function (value) {
  71753. this._minPitch = value;
  71754. this._minPitchTan = Math.tan(value);
  71755. },
  71756. enumerable: true,
  71757. configurable: true
  71758. });
  71759. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71760. /**
  71761. * Get/set the maximum pitch angle that the bone can look to.
  71762. */
  71763. get: function () {
  71764. return this._maxPitch;
  71765. },
  71766. set: function (value) {
  71767. this._maxPitch = value;
  71768. this._maxPitchTan = Math.tan(value);
  71769. },
  71770. enumerable: true,
  71771. configurable: true
  71772. });
  71773. /**
  71774. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71775. */
  71776. BoneLookController.prototype.update = function () {
  71777. //skip the first frame when slerping so that the mesh rotation is correct
  71778. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71779. this._firstFrameSkipped = true;
  71780. return;
  71781. }
  71782. var bone = this.bone;
  71783. var bonePos = BoneLookController._tmpVecs[0];
  71784. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71785. var target = this.target;
  71786. var _tmpMat1 = BoneLookController._tmpMats[0];
  71787. var _tmpMat2 = BoneLookController._tmpMats[1];
  71788. var mesh = this.mesh;
  71789. var parentBone = bone.getParent();
  71790. var upAxis = BoneLookController._tmpVecs[1];
  71791. upAxis.copyFrom(this.upAxis);
  71792. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71793. if (this._transformYawPitch) {
  71794. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71795. }
  71796. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71797. }
  71798. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71799. mesh.getDirectionToRef(upAxis, upAxis);
  71800. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71801. upAxis.normalize();
  71802. }
  71803. }
  71804. var checkYaw = false;
  71805. var checkPitch = false;
  71806. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71807. checkYaw = true;
  71808. }
  71809. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71810. checkPitch = true;
  71811. }
  71812. if (checkYaw || checkPitch) {
  71813. var spaceMat = BoneLookController._tmpMats[2];
  71814. var spaceMatInv = BoneLookController._tmpMats[3];
  71815. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71816. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71817. }
  71818. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71819. spaceMat.copyFrom(mesh.getWorldMatrix());
  71820. }
  71821. else {
  71822. var forwardAxis = BoneLookController._tmpVecs[2];
  71823. forwardAxis.copyFrom(this._fowardAxis);
  71824. if (this._transformYawPitch) {
  71825. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71826. }
  71827. if (parentBone) {
  71828. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71829. }
  71830. else {
  71831. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71832. }
  71833. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71834. rightAxis.normalize();
  71835. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71836. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71837. }
  71838. spaceMat.invertToRef(spaceMatInv);
  71839. var xzlen = null;
  71840. if (checkPitch) {
  71841. var localTarget = BoneLookController._tmpVecs[3];
  71842. target.subtractToRef(bonePos, localTarget);
  71843. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71844. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71845. var pitch = Math.atan2(localTarget.y, xzlen);
  71846. var newPitch = pitch;
  71847. if (pitch > this._maxPitch) {
  71848. localTarget.y = this._maxPitchTan * xzlen;
  71849. newPitch = this._maxPitch;
  71850. }
  71851. else if (pitch < this._minPitch) {
  71852. localTarget.y = this._minPitchTan * xzlen;
  71853. newPitch = this._minPitch;
  71854. }
  71855. if (pitch != newPitch) {
  71856. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71857. localTarget.addInPlace(bonePos);
  71858. target = localTarget;
  71859. }
  71860. }
  71861. if (checkYaw) {
  71862. var localTarget = BoneLookController._tmpVecs[4];
  71863. target.subtractToRef(bonePos, localTarget);
  71864. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71865. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71866. var newYaw = yaw;
  71867. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71868. if (xzlen == null) {
  71869. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71870. }
  71871. if (this._yawRange > Math.PI) {
  71872. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71873. localTarget.z = this._maxYawCos * xzlen;
  71874. localTarget.x = this._maxYawSin * xzlen;
  71875. newYaw = this._maxYaw;
  71876. }
  71877. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71878. localTarget.z = this._minYawCos * xzlen;
  71879. localTarget.x = this._minYawSin * xzlen;
  71880. newYaw = this._minYaw;
  71881. }
  71882. }
  71883. else {
  71884. if (yaw > this._maxYaw) {
  71885. localTarget.z = this._maxYawCos * xzlen;
  71886. localTarget.x = this._maxYawSin * xzlen;
  71887. newYaw = this._maxYaw;
  71888. }
  71889. else if (yaw < this._minYaw) {
  71890. localTarget.z = this._minYawCos * xzlen;
  71891. localTarget.x = this._minYawSin * xzlen;
  71892. newYaw = this._minYaw;
  71893. }
  71894. }
  71895. }
  71896. if (this._slerping && this._yawRange > Math.PI) {
  71897. //are we going to be crossing into the min/max region?
  71898. var boneFwd = BoneLookController._tmpVecs[8];
  71899. boneFwd.copyFrom(BABYLON.Axis.Z);
  71900. if (this._transformYawPitch) {
  71901. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71902. }
  71903. var boneRotMat = BoneLookController._tmpMats[4];
  71904. this._boneQuat.toRotationMatrix(boneRotMat);
  71905. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71906. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71907. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71908. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71909. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71910. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71911. if (angBtwTar > angBtwMidYaw) {
  71912. if (xzlen == null) {
  71913. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71914. }
  71915. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71916. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71917. if (angBtwMin < angBtwMax) {
  71918. newYaw = boneYaw + Math.PI * .75;
  71919. localTarget.z = Math.cos(newYaw) * xzlen;
  71920. localTarget.x = Math.sin(newYaw) * xzlen;
  71921. }
  71922. else {
  71923. newYaw = boneYaw - Math.PI * .75;
  71924. localTarget.z = Math.cos(newYaw) * xzlen;
  71925. localTarget.x = Math.sin(newYaw) * xzlen;
  71926. }
  71927. }
  71928. }
  71929. if (yaw != newYaw) {
  71930. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71931. localTarget.addInPlace(bonePos);
  71932. target = localTarget;
  71933. }
  71934. }
  71935. }
  71936. var zaxis = BoneLookController._tmpVecs[5];
  71937. var xaxis = BoneLookController._tmpVecs[6];
  71938. var yaxis = BoneLookController._tmpVecs[7];
  71939. var _tmpQuat = BoneLookController._tmpQuat;
  71940. target.subtractToRef(bonePos, zaxis);
  71941. zaxis.normalize();
  71942. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71943. xaxis.normalize();
  71944. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71945. yaxis.normalize();
  71946. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71947. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71948. return;
  71949. }
  71950. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71951. return;
  71952. }
  71953. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71954. return;
  71955. }
  71956. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71957. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71958. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71959. }
  71960. if (this.slerpAmount < 1) {
  71961. if (!this._slerping) {
  71962. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71963. }
  71964. if (this._transformYawPitch) {
  71965. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71966. }
  71967. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71968. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71969. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71970. this._slerping = true;
  71971. }
  71972. else {
  71973. if (this._transformYawPitch) {
  71974. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71975. }
  71976. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71977. this._slerping = false;
  71978. }
  71979. };
  71980. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71981. var angDiff = ang2 - ang1;
  71982. angDiff %= Math.PI * 2;
  71983. if (angDiff > Math.PI) {
  71984. angDiff -= Math.PI * 2;
  71985. }
  71986. else if (angDiff < -Math.PI) {
  71987. angDiff += Math.PI * 2;
  71988. }
  71989. return angDiff;
  71990. };
  71991. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71992. ang1 %= (2 * Math.PI);
  71993. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71994. ang2 %= (2 * Math.PI);
  71995. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71996. var ab = 0;
  71997. if (ang1 < ang2) {
  71998. ab = ang2 - ang1;
  71999. }
  72000. else {
  72001. ab = ang1 - ang2;
  72002. }
  72003. if (ab > Math.PI) {
  72004. ab = Math.PI * 2 - ab;
  72005. }
  72006. return ab;
  72007. };
  72008. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72009. ang %= (2 * Math.PI);
  72010. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72011. ang1 %= (2 * Math.PI);
  72012. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72013. ang2 %= (2 * Math.PI);
  72014. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72015. if (ang1 < ang2) {
  72016. if (ang > ang1 && ang < ang2) {
  72017. return true;
  72018. }
  72019. }
  72020. else {
  72021. if (ang > ang2 && ang < ang1) {
  72022. return true;
  72023. }
  72024. }
  72025. return false;
  72026. };
  72027. 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()];
  72028. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72029. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72030. return BoneLookController;
  72031. }());
  72032. BABYLON.BoneLookController = BoneLookController;
  72033. })(BABYLON || (BABYLON = {}));
  72034. //# sourceMappingURL=babylon.boneLookController.js.map
  72035. var BABYLON;
  72036. (function (BABYLON) {
  72037. var Skeleton = /** @class */ (function () {
  72038. function Skeleton(name, id, scene) {
  72039. this.name = name;
  72040. this.id = id;
  72041. this.bones = new Array();
  72042. this.needInitialSkinMatrix = false;
  72043. this._isDirty = true;
  72044. this._meshesWithPoseMatrix = new Array();
  72045. this._identity = BABYLON.Matrix.Identity();
  72046. this._ranges = {};
  72047. this._lastAbsoluteTransformsUpdateId = -1;
  72048. /**
  72049. * Specifies if the skeleton should be serialized.
  72050. */
  72051. this.doNotSerialize = false;
  72052. // Events
  72053. /**
  72054. * An event triggered before computing the skeleton's matrices
  72055. * @type {BABYLON.Observable}
  72056. */
  72057. this.onBeforeComputeObservable = new BABYLON.Observable();
  72058. this.bones = [];
  72059. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72060. scene.skeletons.push(this);
  72061. //make sure it will recalculate the matrix next time prepare is called.
  72062. this._isDirty = true;
  72063. }
  72064. // Members
  72065. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72066. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72067. return mesh._bonesTransformMatrices;
  72068. }
  72069. if (!this._transformMatrices) {
  72070. this.prepare();
  72071. }
  72072. return this._transformMatrices;
  72073. };
  72074. Skeleton.prototype.getScene = function () {
  72075. return this._scene;
  72076. };
  72077. // Methods
  72078. /**
  72079. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72080. */
  72081. Skeleton.prototype.toString = function (fullDetails) {
  72082. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72083. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72084. if (fullDetails) {
  72085. ret += ", Ranges: {";
  72086. var first = true;
  72087. for (var name_1 in this._ranges) {
  72088. if (first) {
  72089. ret += ", ";
  72090. first = false;
  72091. }
  72092. ret += name_1;
  72093. }
  72094. ret += "}";
  72095. }
  72096. return ret;
  72097. };
  72098. /**
  72099. * Get bone's index searching by name
  72100. * @param {string} name is bone's name to search for
  72101. * @return {number} Indice of the bone. Returns -1 if not found
  72102. */
  72103. Skeleton.prototype.getBoneIndexByName = function (name) {
  72104. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72105. if (this.bones[boneIndex].name === name) {
  72106. return boneIndex;
  72107. }
  72108. }
  72109. return -1;
  72110. };
  72111. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72112. // check name not already in use
  72113. if (!this._ranges[name]) {
  72114. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72115. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72116. if (this.bones[i].animations[0]) {
  72117. this.bones[i].animations[0].createRange(name, from, to);
  72118. }
  72119. }
  72120. }
  72121. };
  72122. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72123. if (deleteFrames === void 0) { deleteFrames = true; }
  72124. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72125. if (this.bones[i].animations[0]) {
  72126. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72127. }
  72128. }
  72129. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72130. };
  72131. Skeleton.prototype.getAnimationRange = function (name) {
  72132. return this._ranges[name];
  72133. };
  72134. /**
  72135. * Returns as an Array, all AnimationRanges defined on this skeleton
  72136. */
  72137. Skeleton.prototype.getAnimationRanges = function () {
  72138. var animationRanges = [];
  72139. var name;
  72140. var i = 0;
  72141. for (name in this._ranges) {
  72142. animationRanges[i] = this._ranges[name];
  72143. i++;
  72144. }
  72145. return animationRanges;
  72146. };
  72147. /**
  72148. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72149. */
  72150. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72151. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72152. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72153. return false;
  72154. }
  72155. var ret = true;
  72156. var frameOffset = this._getHighestAnimationFrame() + 1;
  72157. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72158. var boneDict = {};
  72159. var sourceBones = source.bones;
  72160. var nBones;
  72161. var i;
  72162. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72163. boneDict[sourceBones[i].name] = sourceBones[i];
  72164. }
  72165. if (this.bones.length !== sourceBones.length) {
  72166. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72167. ret = false;
  72168. }
  72169. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72170. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72171. var boneName = this.bones[i].name;
  72172. var sourceBone = boneDict[boneName];
  72173. if (sourceBone) {
  72174. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72175. }
  72176. else {
  72177. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72178. ret = false;
  72179. }
  72180. }
  72181. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72182. var range = source.getAnimationRange(name);
  72183. if (range) {
  72184. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72185. }
  72186. return ret;
  72187. };
  72188. Skeleton.prototype.returnToRest = function () {
  72189. for (var index = 0; index < this.bones.length; index++) {
  72190. this.bones[index].returnToRest();
  72191. }
  72192. };
  72193. Skeleton.prototype._getHighestAnimationFrame = function () {
  72194. var ret = 0;
  72195. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72196. if (this.bones[i].animations[0]) {
  72197. var highest = this.bones[i].animations[0].getHighestFrame();
  72198. if (ret < highest) {
  72199. ret = highest;
  72200. }
  72201. }
  72202. }
  72203. return ret;
  72204. };
  72205. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72206. var range = this.getAnimationRange(name);
  72207. if (!range) {
  72208. return null;
  72209. }
  72210. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72211. };
  72212. Skeleton.prototype._markAsDirty = function () {
  72213. this._isDirty = true;
  72214. };
  72215. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72216. this._meshesWithPoseMatrix.push(mesh);
  72217. };
  72218. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72219. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72220. if (index > -1) {
  72221. this._meshesWithPoseMatrix.splice(index, 1);
  72222. }
  72223. };
  72224. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72225. this.onBeforeComputeObservable.notifyObservers(this);
  72226. for (var index = 0; index < this.bones.length; index++) {
  72227. var bone = this.bones[index];
  72228. var parentBone = bone.getParent();
  72229. if (parentBone) {
  72230. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72231. }
  72232. else {
  72233. if (initialSkinMatrix) {
  72234. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72235. }
  72236. else {
  72237. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72238. }
  72239. }
  72240. if (bone._index !== -1) {
  72241. var mappedIndex = bone._index === null ? index : bone._index;
  72242. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72243. }
  72244. }
  72245. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72246. };
  72247. Skeleton.prototype.prepare = function () {
  72248. if (!this._isDirty) {
  72249. return;
  72250. }
  72251. if (this.needInitialSkinMatrix) {
  72252. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72253. var mesh = this._meshesWithPoseMatrix[index];
  72254. var poseMatrix = mesh.getPoseMatrix();
  72255. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72256. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72257. }
  72258. if (this._synchronizedWithMesh !== mesh) {
  72259. this._synchronizedWithMesh = mesh;
  72260. // Prepare bones
  72261. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72262. var bone = this.bones[boneIndex];
  72263. if (!bone.getParent()) {
  72264. var matrix = bone.getBaseMatrix();
  72265. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72266. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72267. }
  72268. }
  72269. }
  72270. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72271. }
  72272. }
  72273. else {
  72274. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72275. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72276. }
  72277. this._computeTransformMatrices(this._transformMatrices, null);
  72278. }
  72279. this._isDirty = false;
  72280. this._scene._activeBones.addCount(this.bones.length, false);
  72281. };
  72282. Skeleton.prototype.getAnimatables = function () {
  72283. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72284. this._animatables = [];
  72285. for (var index = 0; index < this.bones.length; index++) {
  72286. this._animatables.push(this.bones[index]);
  72287. }
  72288. }
  72289. return this._animatables;
  72290. };
  72291. Skeleton.prototype.clone = function (name, id) {
  72292. var result = new Skeleton(name, id || name, this._scene);
  72293. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72294. for (var index = 0; index < this.bones.length; index++) {
  72295. var source = this.bones[index];
  72296. var parentBone = null;
  72297. var parent_1 = source.getParent();
  72298. if (parent_1) {
  72299. var parentIndex = this.bones.indexOf(parent_1);
  72300. parentBone = result.bones[parentIndex];
  72301. }
  72302. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72303. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72304. }
  72305. if (this._ranges) {
  72306. result._ranges = {};
  72307. for (var rangeName in this._ranges) {
  72308. var range = this._ranges[rangeName];
  72309. if (range) {
  72310. result._ranges[rangeName] = range.clone();
  72311. }
  72312. }
  72313. }
  72314. this._isDirty = true;
  72315. return result;
  72316. };
  72317. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72318. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72319. this.bones.forEach(function (bone) {
  72320. bone.animations.forEach(function (animation) {
  72321. animation.enableBlending = true;
  72322. animation.blendingSpeed = blendingSpeed;
  72323. });
  72324. });
  72325. };
  72326. Skeleton.prototype.dispose = function () {
  72327. this._meshesWithPoseMatrix = [];
  72328. // Animations
  72329. this.getScene().stopAnimation(this);
  72330. // Remove from scene
  72331. this.getScene().removeSkeleton(this);
  72332. };
  72333. Skeleton.prototype.serialize = function () {
  72334. var serializationObject = {};
  72335. serializationObject.name = this.name;
  72336. serializationObject.id = this.id;
  72337. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72338. serializationObject.bones = [];
  72339. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72340. for (var index = 0; index < this.bones.length; index++) {
  72341. var bone = this.bones[index];
  72342. var parent_2 = bone.getParent();
  72343. var serializedBone = {
  72344. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72345. name: bone.name,
  72346. matrix: bone.getBaseMatrix().toArray(),
  72347. rest: bone.getRestPose().toArray()
  72348. };
  72349. serializationObject.bones.push(serializedBone);
  72350. if (bone.length) {
  72351. serializedBone.length = bone.length;
  72352. }
  72353. if (bone.animations && bone.animations.length > 0) {
  72354. serializedBone.animation = bone.animations[0].serialize();
  72355. }
  72356. serializationObject.ranges = [];
  72357. for (var name in this._ranges) {
  72358. var source = this._ranges[name];
  72359. if (!source) {
  72360. continue;
  72361. }
  72362. var range = {};
  72363. range.name = name;
  72364. range.from = source.from;
  72365. range.to = source.to;
  72366. serializationObject.ranges.push(range);
  72367. }
  72368. }
  72369. return serializationObject;
  72370. };
  72371. Skeleton.Parse = function (parsedSkeleton, scene) {
  72372. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72373. if (parsedSkeleton.dimensionsAtRest) {
  72374. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72375. }
  72376. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72377. var index;
  72378. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72379. var parsedBone = parsedSkeleton.bones[index];
  72380. var parentBone = null;
  72381. if (parsedBone.parentBoneIndex > -1) {
  72382. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72383. }
  72384. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72385. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72386. if (parsedBone.length) {
  72387. bone.length = parsedBone.length;
  72388. }
  72389. if (parsedBone.animation) {
  72390. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72391. }
  72392. }
  72393. // placed after bones, so createAnimationRange can cascade down
  72394. if (parsedSkeleton.ranges) {
  72395. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72396. var data = parsedSkeleton.ranges[index];
  72397. skeleton.createAnimationRange(data.name, data.from, data.to);
  72398. }
  72399. }
  72400. return skeleton;
  72401. };
  72402. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72403. if (forceUpdate === void 0) { forceUpdate = false; }
  72404. var renderId = this._scene.getRenderId();
  72405. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72406. this.bones[0].computeAbsoluteTransforms();
  72407. this._lastAbsoluteTransformsUpdateId = renderId;
  72408. }
  72409. };
  72410. Skeleton.prototype.getPoseMatrix = function () {
  72411. var poseMatrix = null;
  72412. if (this._meshesWithPoseMatrix.length > 0) {
  72413. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72414. }
  72415. return poseMatrix;
  72416. };
  72417. Skeleton.prototype.sortBones = function () {
  72418. var bones = new Array();
  72419. var visited = new Array(this.bones.length);
  72420. for (var index = 0; index < this.bones.length; index++) {
  72421. this._sortBones(index, bones, visited);
  72422. }
  72423. this.bones = bones;
  72424. };
  72425. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72426. if (visited[index]) {
  72427. return;
  72428. }
  72429. visited[index] = true;
  72430. var bone = this.bones[index];
  72431. if (bone._index === undefined) {
  72432. bone._index = index;
  72433. }
  72434. var parentBone = bone.getParent();
  72435. if (parentBone) {
  72436. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72437. }
  72438. bones.push(bone);
  72439. };
  72440. return Skeleton;
  72441. }());
  72442. BABYLON.Skeleton = Skeleton;
  72443. })(BABYLON || (BABYLON = {}));
  72444. //# sourceMappingURL=babylon.skeleton.js.map
  72445. var BABYLON;
  72446. (function (BABYLON) {
  72447. var SphericalPolynomial = /** @class */ (function () {
  72448. function SphericalPolynomial() {
  72449. this.x = BABYLON.Vector3.Zero();
  72450. this.y = BABYLON.Vector3.Zero();
  72451. this.z = BABYLON.Vector3.Zero();
  72452. this.xx = BABYLON.Vector3.Zero();
  72453. this.yy = BABYLON.Vector3.Zero();
  72454. this.zz = BABYLON.Vector3.Zero();
  72455. this.xy = BABYLON.Vector3.Zero();
  72456. this.yz = BABYLON.Vector3.Zero();
  72457. this.zx = BABYLON.Vector3.Zero();
  72458. }
  72459. SphericalPolynomial.prototype.addAmbient = function (color) {
  72460. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72461. this.xx = this.xx.add(colorVector);
  72462. this.yy = this.yy.add(colorVector);
  72463. this.zz = this.zz.add(colorVector);
  72464. };
  72465. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72466. var result = new SphericalPolynomial();
  72467. result.x = harmonics.L11.scale(1.02333);
  72468. result.y = harmonics.L1_1.scale(1.02333);
  72469. result.z = harmonics.L10.scale(1.02333);
  72470. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72471. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72472. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72473. result.yz = harmonics.L2_1.scale(0.858086);
  72474. result.zx = harmonics.L21.scale(0.858086);
  72475. result.xy = harmonics.L2_2.scale(0.858086);
  72476. result.scale(1.0 / Math.PI);
  72477. return result;
  72478. };
  72479. SphericalPolynomial.prototype.scale = function (scale) {
  72480. this.x = this.x.scale(scale);
  72481. this.y = this.y.scale(scale);
  72482. this.z = this.z.scale(scale);
  72483. this.xx = this.xx.scale(scale);
  72484. this.yy = this.yy.scale(scale);
  72485. this.zz = this.zz.scale(scale);
  72486. this.yz = this.yz.scale(scale);
  72487. this.zx = this.zx.scale(scale);
  72488. this.xy = this.xy.scale(scale);
  72489. };
  72490. return SphericalPolynomial;
  72491. }());
  72492. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72493. var SphericalHarmonics = /** @class */ (function () {
  72494. function SphericalHarmonics() {
  72495. this.L00 = BABYLON.Vector3.Zero();
  72496. this.L1_1 = BABYLON.Vector3.Zero();
  72497. this.L10 = BABYLON.Vector3.Zero();
  72498. this.L11 = BABYLON.Vector3.Zero();
  72499. this.L2_2 = BABYLON.Vector3.Zero();
  72500. this.L2_1 = BABYLON.Vector3.Zero();
  72501. this.L20 = BABYLON.Vector3.Zero();
  72502. this.L21 = BABYLON.Vector3.Zero();
  72503. this.L22 = BABYLON.Vector3.Zero();
  72504. }
  72505. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72506. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72507. var c = colorVector.scale(deltaSolidAngle);
  72508. this.L00 = this.L00.add(c.scale(0.282095));
  72509. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72510. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72511. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72512. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72513. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72514. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72515. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72516. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72517. };
  72518. SphericalHarmonics.prototype.scale = function (scale) {
  72519. this.L00 = this.L00.scale(scale);
  72520. this.L1_1 = this.L1_1.scale(scale);
  72521. this.L10 = this.L10.scale(scale);
  72522. this.L11 = this.L11.scale(scale);
  72523. this.L2_2 = this.L2_2.scale(scale);
  72524. this.L2_1 = this.L2_1.scale(scale);
  72525. this.L20 = this.L20.scale(scale);
  72526. this.L21 = this.L21.scale(scale);
  72527. this.L22 = this.L22.scale(scale);
  72528. };
  72529. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72530. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72531. //
  72532. // E_lm = A_l * L_lm
  72533. //
  72534. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72535. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72536. // the scaling factors are given in equation 9.
  72537. // Constant (Band 0)
  72538. this.L00 = this.L00.scale(3.141593);
  72539. // Linear (Band 1)
  72540. this.L1_1 = this.L1_1.scale(2.094395);
  72541. this.L10 = this.L10.scale(2.094395);
  72542. this.L11 = this.L11.scale(2.094395);
  72543. // Quadratic (Band 2)
  72544. this.L2_2 = this.L2_2.scale(0.785398);
  72545. this.L2_1 = this.L2_1.scale(0.785398);
  72546. this.L20 = this.L20.scale(0.785398);
  72547. this.L21 = this.L21.scale(0.785398);
  72548. this.L22 = this.L22.scale(0.785398);
  72549. };
  72550. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72551. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72552. // L = (1/pi) * E * rho
  72553. //
  72554. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72555. this.scale(1.0 / Math.PI);
  72556. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72557. // (The pixel shader must apply albedo after texture fetches, etc).
  72558. };
  72559. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72560. var result = new SphericalHarmonics();
  72561. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72562. result.L1_1 = polynomial.y.scale(0.977204);
  72563. result.L10 = polynomial.z.scale(0.977204);
  72564. result.L11 = polynomial.x.scale(0.977204);
  72565. result.L2_2 = polynomial.xy.scale(1.16538);
  72566. result.L2_1 = polynomial.yz.scale(1.16538);
  72567. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72568. result.L21 = polynomial.zx.scale(1.16538);
  72569. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72570. result.scale(Math.PI);
  72571. return result;
  72572. };
  72573. return SphericalHarmonics;
  72574. }());
  72575. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72576. })(BABYLON || (BABYLON = {}));
  72577. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72578. var BABYLON;
  72579. (function (BABYLON) {
  72580. var FileFaceOrientation = /** @class */ (function () {
  72581. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72582. this.name = name;
  72583. this.worldAxisForNormal = worldAxisForNormal;
  72584. this.worldAxisForFileX = worldAxisForFileX;
  72585. this.worldAxisForFileY = worldAxisForFileY;
  72586. }
  72587. return FileFaceOrientation;
  72588. }());
  72589. ;
  72590. /**
  72591. * Helper class dealing with the extraction of spherical polynomial dataArray
  72592. * from a cube map.
  72593. */
  72594. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72595. function CubeMapToSphericalPolynomialTools() {
  72596. }
  72597. /**
  72598. * Converts a texture to the according Spherical Polynomial data.
  72599. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72600. *
  72601. * @param texture The texture to extract the information from.
  72602. * @return The Spherical Polynomial data.
  72603. */
  72604. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72605. if (!texture.isCube) {
  72606. // Only supports cube Textures currently.
  72607. return null;
  72608. }
  72609. var size = texture.getSize().width;
  72610. var right = texture.readPixels(0);
  72611. var left = texture.readPixels(1);
  72612. var up;
  72613. var down;
  72614. if (texture.isRenderTarget) {
  72615. up = texture.readPixels(3);
  72616. down = texture.readPixels(2);
  72617. }
  72618. else {
  72619. up = texture.readPixels(2);
  72620. down = texture.readPixels(3);
  72621. }
  72622. var front = texture.readPixels(4);
  72623. var back = texture.readPixels(5);
  72624. var gammaSpace = texture.gammaSpace;
  72625. // Always read as RGBA.
  72626. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72627. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72628. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72629. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72630. }
  72631. var cubeInfo = {
  72632. size: size,
  72633. right: right,
  72634. left: left,
  72635. up: up,
  72636. down: down,
  72637. front: front,
  72638. back: back,
  72639. format: format,
  72640. type: type,
  72641. gammaSpace: gammaSpace,
  72642. };
  72643. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72644. };
  72645. /**
  72646. * Converts a cubemap to the according Spherical Polynomial data.
  72647. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72648. *
  72649. * @param cubeInfo The Cube map to extract the information from.
  72650. * @return The Spherical Polynomial data.
  72651. */
  72652. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72653. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72654. var totalSolidAngle = 0.0;
  72655. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72656. var du = 2.0 / cubeInfo.size;
  72657. var dv = du;
  72658. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72659. var minUV = du * 0.5 - 1.0;
  72660. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72661. var fileFace = this.FileFaces[faceIndex];
  72662. var dataArray = cubeInfo[fileFace.name];
  72663. var v = minUV;
  72664. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72665. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72666. // Because SP is still linear, so summation is fine in that basis.
  72667. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72668. for (var y = 0; y < cubeInfo.size; y++) {
  72669. var u = minUV;
  72670. for (var x = 0; x < cubeInfo.size; x++) {
  72671. // World direction (not normalised)
  72672. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72673. worldDirection.normalize();
  72674. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72675. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72676. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72677. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72678. // Handle Integer types.
  72679. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72680. r /= 255;
  72681. g /= 255;
  72682. b /= 255;
  72683. }
  72684. // Handle Gamma space textures.
  72685. if (cubeInfo.gammaSpace) {
  72686. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72687. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72688. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72689. }
  72690. var color = new BABYLON.Color3(r, g, b);
  72691. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72692. totalSolidAngle += deltaSolidAngle;
  72693. u += du;
  72694. }
  72695. v += dv;
  72696. }
  72697. }
  72698. // Solid angle for entire sphere is 4*pi
  72699. var sphereSolidAngle = 4.0 * Math.PI;
  72700. // Adjust the solid angle to allow for how many faces we processed.
  72701. var facesProcessed = 6.0;
  72702. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72703. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72704. // This is needed because the numerical integration over the cube uses a
  72705. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72706. // and also to compensate for accumulative error due to float precision in the summation.
  72707. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72708. sphericalHarmonics.scale(correctionFactor);
  72709. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72710. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72711. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72712. };
  72713. CubeMapToSphericalPolynomialTools.FileFaces = [
  72714. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72715. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72716. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72717. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72718. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72719. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72720. ];
  72721. return CubeMapToSphericalPolynomialTools;
  72722. }());
  72723. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72724. })(BABYLON || (BABYLON = {}));
  72725. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72726. var BABYLON;
  72727. (function (BABYLON) {
  72728. /**
  72729. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72730. */
  72731. var PanoramaToCubeMapTools = /** @class */ (function () {
  72732. function PanoramaToCubeMapTools() {
  72733. }
  72734. /**
  72735. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72736. *
  72737. * @param float32Array The source data.
  72738. * @param inputWidth The width of the input panorama.
  72739. * @param inputhHeight The height of the input panorama.
  72740. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72741. * @return The cubemap data
  72742. */
  72743. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72744. if (!float32Array) {
  72745. throw "ConvertPanoramaToCubemap: input cannot be null";
  72746. }
  72747. if (float32Array.length != inputWidth * inputHeight * 3) {
  72748. throw "ConvertPanoramaToCubemap: input size is wrong";
  72749. }
  72750. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72751. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72752. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72753. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72754. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72755. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72756. return {
  72757. front: textureFront,
  72758. back: textureBack,
  72759. left: textureLeft,
  72760. right: textureRight,
  72761. up: textureUp,
  72762. down: textureDown,
  72763. size: size,
  72764. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72765. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72766. gammaSpace: false,
  72767. };
  72768. };
  72769. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72770. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72771. var textureArray = new Float32Array(buffer);
  72772. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72773. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72774. var dy = 1 / texSize;
  72775. var fy = 0;
  72776. for (var y = 0; y < texSize; y++) {
  72777. var xv1 = faceData[0];
  72778. var xv2 = faceData[2];
  72779. for (var x = 0; x < texSize; x++) {
  72780. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72781. v.normalize();
  72782. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72783. // 3 channels per pixels
  72784. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72785. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72786. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72787. xv1 = xv1.add(rotDX1);
  72788. xv2 = xv2.add(rotDX2);
  72789. }
  72790. fy += dy;
  72791. }
  72792. return textureArray;
  72793. };
  72794. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72795. var theta = Math.atan2(vDir.z, vDir.x);
  72796. var phi = Math.acos(vDir.y);
  72797. while (theta < -Math.PI)
  72798. theta += 2 * Math.PI;
  72799. while (theta > Math.PI)
  72800. theta -= 2 * Math.PI;
  72801. var dx = theta / Math.PI;
  72802. var dy = phi / Math.PI;
  72803. // recenter.
  72804. dx = dx * 0.5 + 0.5;
  72805. var px = Math.round(dx * inputWidth);
  72806. if (px < 0)
  72807. px = 0;
  72808. else if (px >= inputWidth)
  72809. px = inputWidth - 1;
  72810. var py = Math.round(dy * inputHeight);
  72811. if (py < 0)
  72812. py = 0;
  72813. else if (py >= inputHeight)
  72814. py = inputHeight - 1;
  72815. var inputY = (inputHeight - py - 1);
  72816. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72817. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72818. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72819. return {
  72820. r: r,
  72821. g: g,
  72822. b: b
  72823. };
  72824. };
  72825. PanoramaToCubeMapTools.FACE_FRONT = [
  72826. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72827. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72828. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72829. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72830. ];
  72831. PanoramaToCubeMapTools.FACE_BACK = [
  72832. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72833. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72834. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72835. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72836. ];
  72837. PanoramaToCubeMapTools.FACE_RIGHT = [
  72838. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72839. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72840. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72841. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72842. ];
  72843. PanoramaToCubeMapTools.FACE_LEFT = [
  72844. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72845. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72846. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72847. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72848. ];
  72849. PanoramaToCubeMapTools.FACE_DOWN = [
  72850. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72851. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72852. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72853. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72854. ];
  72855. PanoramaToCubeMapTools.FACE_UP = [
  72856. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72857. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72858. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72859. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72860. ];
  72861. return PanoramaToCubeMapTools;
  72862. }());
  72863. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72864. })(BABYLON || (BABYLON = {}));
  72865. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72866. var BABYLON;
  72867. (function (BABYLON) {
  72868. ;
  72869. /**
  72870. * This groups tools to convert HDR texture to native colors array.
  72871. */
  72872. var HDRTools = /** @class */ (function () {
  72873. function HDRTools() {
  72874. }
  72875. HDRTools.Ldexp = function (mantissa, exponent) {
  72876. if (exponent > 1023) {
  72877. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72878. }
  72879. if (exponent < -1074) {
  72880. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72881. }
  72882. return mantissa * Math.pow(2, exponent);
  72883. };
  72884. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72885. if (exponent > 0) {
  72886. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72887. float32array[index + 0] = red * exponent;
  72888. float32array[index + 1] = green * exponent;
  72889. float32array[index + 2] = blue * exponent;
  72890. }
  72891. else {
  72892. float32array[index + 0] = 0;
  72893. float32array[index + 1] = 0;
  72894. float32array[index + 2] = 0;
  72895. }
  72896. };
  72897. HDRTools.readStringLine = function (uint8array, startIndex) {
  72898. var line = "";
  72899. var character = "";
  72900. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72901. character = String.fromCharCode(uint8array[i]);
  72902. if (character == "\n") {
  72903. break;
  72904. }
  72905. line += character;
  72906. }
  72907. return line;
  72908. };
  72909. /**
  72910. * Reads header information from an RGBE texture stored in a native array.
  72911. * More information on this format are available here:
  72912. * https://en.wikipedia.org/wiki/RGBE_image_format
  72913. *
  72914. * @param uint8array The binary file stored in native array.
  72915. * @return The header information.
  72916. */
  72917. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72918. var height = 0;
  72919. var width = 0;
  72920. var line = this.readStringLine(uint8array, 0);
  72921. if (line[0] != '#' || line[1] != '?') {
  72922. throw "Bad HDR Format.";
  72923. }
  72924. var endOfHeader = false;
  72925. var findFormat = false;
  72926. var lineIndex = 0;
  72927. do {
  72928. lineIndex += (line.length + 1);
  72929. line = this.readStringLine(uint8array, lineIndex);
  72930. if (line == "FORMAT=32-bit_rle_rgbe") {
  72931. findFormat = true;
  72932. }
  72933. else if (line.length == 0) {
  72934. endOfHeader = true;
  72935. }
  72936. } while (!endOfHeader);
  72937. if (!findFormat) {
  72938. throw "HDR Bad header format, unsupported FORMAT";
  72939. }
  72940. lineIndex += (line.length + 1);
  72941. line = this.readStringLine(uint8array, lineIndex);
  72942. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72943. var match = sizeRegexp.exec(line);
  72944. // TODO. Support +Y and -X if needed.
  72945. if (!match || match.length < 3) {
  72946. throw "HDR Bad header format, no size";
  72947. }
  72948. width = parseInt(match[2]);
  72949. height = parseInt(match[1]);
  72950. if (width < 8 || width > 0x7fff) {
  72951. throw "HDR Bad header format, unsupported size";
  72952. }
  72953. lineIndex += (line.length + 1);
  72954. return {
  72955. height: height,
  72956. width: width,
  72957. dataPosition: lineIndex
  72958. };
  72959. };
  72960. /**
  72961. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72962. * This RGBE texture needs to store the information as a panorama.
  72963. *
  72964. * More information on this format are available here:
  72965. * https://en.wikipedia.org/wiki/RGBE_image_format
  72966. *
  72967. * @param buffer The binary file stored in an array buffer.
  72968. * @param size The expected size of the extracted cubemap.
  72969. * @return The Cube Map information.
  72970. */
  72971. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72972. var uint8array = new Uint8Array(buffer);
  72973. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72974. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72975. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72976. return cubeMapData;
  72977. };
  72978. /**
  72979. * Returns the pixels data extracted from an RGBE texture.
  72980. * This pixels will be stored left to right up to down in the R G B order in one array.
  72981. *
  72982. * More information on this format are available here:
  72983. * https://en.wikipedia.org/wiki/RGBE_image_format
  72984. *
  72985. * @param uint8array The binary file stored in an array buffer.
  72986. * @param hdrInfo The header information of the file.
  72987. * @return The pixels data in RGB right to left up to down order.
  72988. */
  72989. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72990. // Keep for multi format supports.
  72991. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72992. };
  72993. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72994. var num_scanlines = hdrInfo.height;
  72995. var scanline_width = hdrInfo.width;
  72996. var a, b, c, d, count;
  72997. var dataIndex = hdrInfo.dataPosition;
  72998. var index = 0, endIndex = 0, i = 0;
  72999. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73000. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73001. // 3 channels of 4 bytes per pixel in float.
  73002. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73003. var resultArray = new Float32Array(resultBuffer);
  73004. // read in each successive scanline
  73005. while (num_scanlines > 0) {
  73006. a = uint8array[dataIndex++];
  73007. b = uint8array[dataIndex++];
  73008. c = uint8array[dataIndex++];
  73009. d = uint8array[dataIndex++];
  73010. if (a != 2 || b != 2 || (c & 0x80)) {
  73011. // this file is not run length encoded
  73012. throw "HDR Bad header format, not RLE";
  73013. }
  73014. if (((c << 8) | d) != scanline_width) {
  73015. throw "HDR Bad header format, wrong scan line width";
  73016. }
  73017. index = 0;
  73018. // read each of the four channels for the scanline into the buffer
  73019. for (i = 0; i < 4; i++) {
  73020. endIndex = (i + 1) * scanline_width;
  73021. while (index < endIndex) {
  73022. a = uint8array[dataIndex++];
  73023. b = uint8array[dataIndex++];
  73024. if (a > 128) {
  73025. // a run of the same value
  73026. count = a - 128;
  73027. if ((count == 0) || (count > endIndex - index)) {
  73028. throw "HDR Bad Format, bad scanline data (run)";
  73029. }
  73030. while (count-- > 0) {
  73031. scanLineArray[index++] = b;
  73032. }
  73033. }
  73034. else {
  73035. // a non-run
  73036. count = a;
  73037. if ((count == 0) || (count > endIndex - index)) {
  73038. throw "HDR Bad Format, bad scanline data (non-run)";
  73039. }
  73040. scanLineArray[index++] = b;
  73041. if (--count > 0) {
  73042. for (var j = 0; j < count; j++) {
  73043. scanLineArray[index++] = uint8array[dataIndex++];
  73044. }
  73045. }
  73046. }
  73047. }
  73048. }
  73049. // now convert data from buffer into floats
  73050. for (i = 0; i < scanline_width; i++) {
  73051. a = scanLineArray[i];
  73052. b = scanLineArray[i + scanline_width];
  73053. c = scanLineArray[i + 2 * scanline_width];
  73054. d = scanLineArray[i + 3 * scanline_width];
  73055. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73056. }
  73057. num_scanlines--;
  73058. }
  73059. return resultArray;
  73060. };
  73061. return HDRTools;
  73062. }());
  73063. BABYLON.HDRTools = HDRTools;
  73064. })(BABYLON || (BABYLON = {}));
  73065. //# sourceMappingURL=babylon.hdr.js.map
  73066. var BABYLON;
  73067. (function (BABYLON) {
  73068. /**
  73069. * This represents a texture coming from an HDR input.
  73070. *
  73071. * The only supported format is currently panorama picture stored in RGBE format.
  73072. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73073. */
  73074. var HDRCubeTexture = /** @class */ (function (_super) {
  73075. __extends(HDRCubeTexture, _super);
  73076. /**
  73077. * Instantiates an HDRTexture from the following parameters.
  73078. *
  73079. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73080. * @param scene The scene the texture will be used in
  73081. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  73082. * @param noMipmap Forces to not generate the mipmap if true
  73083. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73084. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  73085. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73086. */
  73087. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73088. if (noMipmap === void 0) { noMipmap = false; }
  73089. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73090. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73091. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73092. if (onLoad === void 0) { onLoad = null; }
  73093. if (onError === void 0) { onError = null; }
  73094. var _this = _super.call(this, scene) || this;
  73095. _this._useInGammaSpace = false;
  73096. _this._generateHarmonics = true;
  73097. _this._isBABYLONPreprocessed = false;
  73098. _this._onLoad = null;
  73099. _this._onError = null;
  73100. /**
  73101. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73102. */
  73103. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73104. /**
  73105. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73106. * This is usefull at run time to apply the good shader.
  73107. */
  73108. _this.isPMREM = false;
  73109. _this._isBlocking = true;
  73110. /**
  73111. * Gets or sets the center of the bounding box associated with the cube texture
  73112. * It must define where the camera used to render the texture was set
  73113. */
  73114. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73115. if (!url) {
  73116. return _this;
  73117. }
  73118. _this.name = url;
  73119. _this.url = url;
  73120. _this.hasAlpha = false;
  73121. _this.isCube = true;
  73122. _this._textureMatrix = BABYLON.Matrix.Identity();
  73123. _this._onLoad = onLoad;
  73124. _this._onError = onError;
  73125. _this.gammaSpace = false;
  73126. var caps = scene.getEngine().getCaps();
  73127. if (size) {
  73128. _this._isBABYLONPreprocessed = false;
  73129. _this._noMipmap = noMipmap;
  73130. _this._size = size;
  73131. _this._useInGammaSpace = useInGammaSpace;
  73132. _this._usePMREMGenerator = usePMREMGenerator &&
  73133. caps.textureLOD &&
  73134. caps.textureFloat &&
  73135. !_this._useInGammaSpace;
  73136. }
  73137. else {
  73138. _this._isBABYLONPreprocessed = true;
  73139. _this._noMipmap = false;
  73140. _this._useInGammaSpace = false;
  73141. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73142. !_this._useInGammaSpace;
  73143. }
  73144. _this.isPMREM = _this._usePMREMGenerator;
  73145. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73146. if (!_this._texture) {
  73147. if (!scene.useDelayedTextureLoading) {
  73148. _this.loadTexture();
  73149. }
  73150. else {
  73151. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73152. }
  73153. }
  73154. return _this;
  73155. }
  73156. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73157. /**
  73158. * Gets wether or not the texture is blocking during loading.
  73159. */
  73160. get: function () {
  73161. return this._isBlocking;
  73162. },
  73163. /**
  73164. * Sets wether or not the texture is blocking during loading.
  73165. */
  73166. set: function (value) {
  73167. this._isBlocking = value;
  73168. },
  73169. enumerable: true,
  73170. configurable: true
  73171. });
  73172. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73173. get: function () {
  73174. return this._boundingBoxSize;
  73175. },
  73176. /**
  73177. * Gets or sets the size of the bounding box associated with the cube texture
  73178. * When defined, the cubemap will switch to local mode
  73179. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73180. * @example https://www.babylonjs-playground.com/#RNASML
  73181. */
  73182. set: function (value) {
  73183. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73184. return;
  73185. }
  73186. this._boundingBoxSize = value;
  73187. var scene = this.getScene();
  73188. if (scene) {
  73189. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73190. }
  73191. },
  73192. enumerable: true,
  73193. configurable: true
  73194. });
  73195. /**
  73196. * Occurs when the file is a preprocessed .babylon.hdr file.
  73197. */
  73198. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73199. var _this = this;
  73200. var mipLevels = 0;
  73201. var floatArrayView = null;
  73202. var scene = this.getScene();
  73203. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73204. var mips = new Array();
  73205. if (!floatArrayView) {
  73206. return mips;
  73207. }
  73208. var startIndex = 30;
  73209. for (var level = 0; level < mipLevels; level++) {
  73210. mips.push([]);
  73211. // Fill each pixel of the mip level.
  73212. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73213. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73214. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73215. mips[level].push(faceData);
  73216. startIndex += faceSize;
  73217. }
  73218. }
  73219. return mips;
  73220. } : null;
  73221. var callback = function (buffer) {
  73222. var scene = _this.getScene();
  73223. if (!scene) {
  73224. return null;
  73225. }
  73226. // Create Native Array Views
  73227. var intArrayView = new Int32Array(buffer);
  73228. floatArrayView = new Float32Array(buffer);
  73229. // Fill header.
  73230. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73231. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73232. // Update Texture Information.
  73233. if (!_this._texture) {
  73234. return null;
  73235. }
  73236. _this._texture.updateSize(_this._size, _this._size);
  73237. // Fill polynomial information.
  73238. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73239. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73240. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73241. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73242. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73243. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73244. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73245. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73246. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73247. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73248. _this.sphericalPolynomial = sphericalPolynomial;
  73249. // Fill pixel data.
  73250. mipLevels = intArrayView[29]; // Number of mip levels.
  73251. var startIndex = 30;
  73252. var data = [];
  73253. var faceSize = Math.pow(_this._size, 2) * 3;
  73254. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73255. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73256. startIndex += faceSize;
  73257. }
  73258. var results = [];
  73259. var byteArray = null;
  73260. // Push each faces.
  73261. for (var k = 0; k < 6; k++) {
  73262. var dataFace = null;
  73263. // To be deprecated.
  73264. if (version === 1) {
  73265. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73266. dataFace = data[j];
  73267. }
  73268. // If special cases.
  73269. if (!mipmapGenerator && dataFace) {
  73270. if (!scene.getEngine().getCaps().textureFloat) {
  73271. // 3 channels of 1 bytes per pixel in bytes.
  73272. var byteBuffer = new ArrayBuffer(faceSize);
  73273. byteArray = new Uint8Array(byteBuffer);
  73274. }
  73275. for (var i = 0; i < _this._size * _this._size; i++) {
  73276. // Put in gamma space if requested.
  73277. if (_this._useInGammaSpace) {
  73278. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73279. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73280. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73281. }
  73282. // Convert to int texture for fallback.
  73283. if (byteArray) {
  73284. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73285. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73286. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73287. // May use luminance instead if the result is not accurate.
  73288. var max = Math.max(Math.max(r, g), b);
  73289. if (max > 255) {
  73290. var scale = 255 / max;
  73291. r *= scale;
  73292. g *= scale;
  73293. b *= scale;
  73294. }
  73295. byteArray[(i * 3) + 0] = r;
  73296. byteArray[(i * 3) + 1] = g;
  73297. byteArray[(i * 3) + 2] = b;
  73298. }
  73299. }
  73300. }
  73301. // Fill the array accordingly.
  73302. if (byteArray) {
  73303. results.push(byteArray);
  73304. }
  73305. else {
  73306. results.push(dataFace);
  73307. }
  73308. }
  73309. return results;
  73310. };
  73311. if (scene) {
  73312. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  73313. }
  73314. };
  73315. /**
  73316. * Occurs when the file is raw .hdr file.
  73317. */
  73318. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73319. var _this = this;
  73320. var callback = function (buffer) {
  73321. var scene = _this.getScene();
  73322. if (!scene) {
  73323. return null;
  73324. }
  73325. // Extract the raw linear data.
  73326. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73327. // Generate harmonics if needed.
  73328. if (_this._generateHarmonics) {
  73329. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73330. _this.sphericalPolynomial = sphericalPolynomial;
  73331. }
  73332. var results = [];
  73333. var byteArray = null;
  73334. // Push each faces.
  73335. for (var j = 0; j < 6; j++) {
  73336. // Create uintarray fallback.
  73337. if (!scene.getEngine().getCaps().textureFloat) {
  73338. // 3 channels of 1 bytes per pixel in bytes.
  73339. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73340. byteArray = new Uint8Array(byteBuffer);
  73341. }
  73342. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73343. // If special cases.
  73344. if (_this._useInGammaSpace || byteArray) {
  73345. for (var i = 0; i < _this._size * _this._size; i++) {
  73346. // Put in gamma space if requested.
  73347. if (_this._useInGammaSpace) {
  73348. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73349. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73350. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73351. }
  73352. // Convert to int texture for fallback.
  73353. if (byteArray) {
  73354. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73355. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73356. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73357. // May use luminance instead if the result is not accurate.
  73358. var max = Math.max(Math.max(r, g), b);
  73359. if (max > 255) {
  73360. var scale = 255 / max;
  73361. r *= scale;
  73362. g *= scale;
  73363. b *= scale;
  73364. }
  73365. byteArray[(i * 3) + 0] = r;
  73366. byteArray[(i * 3) + 1] = g;
  73367. byteArray[(i * 3) + 2] = b;
  73368. }
  73369. }
  73370. }
  73371. if (byteArray) {
  73372. results.push(byteArray);
  73373. }
  73374. else {
  73375. results.push(dataFace);
  73376. }
  73377. }
  73378. return results;
  73379. };
  73380. var mipmapGenerator = null;
  73381. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73382. // if (!this._noMipmap &&
  73383. // this._usePMREMGenerator) {
  73384. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73385. // // Custom setup of the generator matching with the PBR shader values.
  73386. // var generator = new BABYLON.PMREMGenerator(data,
  73387. // this._size,
  73388. // this._size,
  73389. // 0,
  73390. // 3,
  73391. // this.getScene().getEngine().getCaps().textureFloat,
  73392. // 2048,
  73393. // 0.25,
  73394. // false,
  73395. // true);
  73396. // return generator.filterCubeMap();
  73397. // };
  73398. // }
  73399. var scene = this.getScene();
  73400. if (scene) {
  73401. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  73402. }
  73403. };
  73404. /**
  73405. * Starts the loading process of the texture.
  73406. */
  73407. HDRCubeTexture.prototype.loadTexture = function () {
  73408. if (this._isBABYLONPreprocessed) {
  73409. this.loadBabylonTexture();
  73410. }
  73411. else {
  73412. this.loadHDRTexture();
  73413. }
  73414. };
  73415. HDRCubeTexture.prototype.clone = function () {
  73416. var scene = this.getScene();
  73417. if (!scene) {
  73418. return this;
  73419. }
  73420. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73421. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73422. // Base texture
  73423. newTexture.level = this.level;
  73424. newTexture.wrapU = this.wrapU;
  73425. newTexture.wrapV = this.wrapV;
  73426. newTexture.coordinatesIndex = this.coordinatesIndex;
  73427. newTexture.coordinatesMode = this.coordinatesMode;
  73428. return newTexture;
  73429. };
  73430. // Methods
  73431. HDRCubeTexture.prototype.delayLoad = function () {
  73432. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73433. return;
  73434. }
  73435. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73436. this._texture = this._getFromCache(this.url, this._noMipmap);
  73437. if (!this._texture) {
  73438. this.loadTexture();
  73439. }
  73440. };
  73441. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73442. return this._textureMatrix;
  73443. };
  73444. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73445. this._textureMatrix = value;
  73446. };
  73447. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73448. var texture = null;
  73449. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73450. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73451. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73452. texture.name = parsedTexture.name;
  73453. texture.hasAlpha = parsedTexture.hasAlpha;
  73454. texture.level = parsedTexture.level;
  73455. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73456. texture.isBlocking = parsedTexture.isBlocking;
  73457. }
  73458. if (texture) {
  73459. if (parsedTexture.boundingBoxPosition) {
  73460. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73461. }
  73462. if (parsedTexture.boundingBoxSize) {
  73463. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73464. }
  73465. }
  73466. return texture;
  73467. };
  73468. HDRCubeTexture.prototype.serialize = function () {
  73469. if (!this.name) {
  73470. return null;
  73471. }
  73472. var serializationObject = {};
  73473. serializationObject.name = this.name;
  73474. serializationObject.hasAlpha = this.hasAlpha;
  73475. serializationObject.isCube = true;
  73476. serializationObject.level = this.level;
  73477. serializationObject.size = this._size;
  73478. serializationObject.coordinatesMode = this.coordinatesMode;
  73479. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73480. serializationObject.generateHarmonics = this._generateHarmonics;
  73481. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73482. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73483. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73484. serializationObject.noMipmap = this._noMipmap;
  73485. serializationObject.isBlocking = this._isBlocking;
  73486. return serializationObject;
  73487. };
  73488. /**
  73489. * Saves as a file the data contained in the texture in a binary format.
  73490. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73491. * as the spherical used in the lighting.
  73492. * @param url The HDR file url.
  73493. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73494. * @param onError Method called if any error happens during download.
  73495. * @return The packed binary data.
  73496. */
  73497. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73498. if (onError === void 0) { onError = null; }
  73499. var callback = function (buffer) {
  73500. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73501. // Returns a URL you can use as a href.
  73502. var objUrl = window.URL.createObjectURL(data);
  73503. // Simulates a link to it and click to dowload.
  73504. var a = document.createElement("a");
  73505. document.body.appendChild(a);
  73506. a.style.display = "none";
  73507. a.href = objUrl;
  73508. a.download = "envmap.babylon.hdr";
  73509. a.click();
  73510. };
  73511. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73512. };
  73513. /**
  73514. * Serializes the data contained in the texture in a binary format.
  73515. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73516. * as the spherical used in the lighting.
  73517. * @param url The HDR file url.
  73518. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73519. * @param onError Method called if any error happens during download.
  73520. * @return The packed binary data.
  73521. */
  73522. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73523. if (onError === void 0) { onError = null; }
  73524. // Needs the url tho create the texture.
  73525. if (!url) {
  73526. return;
  73527. }
  73528. // Check Power of two size.
  73529. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73530. return;
  73531. }
  73532. // Coming Back in 3.x.
  73533. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73534. };
  73535. HDRCubeTexture._facesMapping = [
  73536. "right",
  73537. "left",
  73538. "up",
  73539. "down",
  73540. "front",
  73541. "back"
  73542. ];
  73543. return HDRCubeTexture;
  73544. }(BABYLON.BaseTexture));
  73545. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73546. })(BABYLON || (BABYLON = {}));
  73547. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73548. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73549. // Huge respect for a such great lib.
  73550. // Earcut license:
  73551. // Copyright (c) 2016, Mapbox
  73552. //
  73553. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73554. // with or without fee is hereby granted, provided that the above copyright notice
  73555. // and this permission notice appear in all copies.
  73556. //
  73557. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73558. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73559. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73560. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73561. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73562. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73563. // THIS SOFTWARE.
  73564. var Earcut;
  73565. (function (Earcut) {
  73566. /**
  73567. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73568. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73569. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  73570. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73571. */
  73572. function earcut(data, holeIndices, dim) {
  73573. dim = dim || 2;
  73574. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73575. if (!outerNode)
  73576. return triangles;
  73577. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73578. if (hasHoles)
  73579. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73580. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73581. if (data.length > 80 * dim) {
  73582. minX = maxX = data[0];
  73583. minY = maxY = data[1];
  73584. for (var i = dim; i < outerLen; i += dim) {
  73585. x = data[i];
  73586. y = data[i + 1];
  73587. if (x < minX)
  73588. minX = x;
  73589. if (y < minY)
  73590. minY = y;
  73591. if (x > maxX)
  73592. maxX = x;
  73593. if (y > maxY)
  73594. maxY = y;
  73595. }
  73596. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73597. size = Math.max(maxX - minX, maxY - minY);
  73598. }
  73599. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73600. return triangles;
  73601. }
  73602. Earcut.earcut = earcut;
  73603. var Node = /** @class */ (function () {
  73604. function Node(i, x, y) {
  73605. this.i = i;
  73606. this.x = x;
  73607. this.y = y;
  73608. this.prev = null;
  73609. this.next = null;
  73610. this.z = null;
  73611. this.prevZ = null;
  73612. this.nextZ = null;
  73613. this.steiner = false;
  73614. }
  73615. return Node;
  73616. }());
  73617. // create a circular doubly linked list from polygon points in the specified winding order
  73618. function linkedList(data, start, end, dim, clockwise) {
  73619. var i, last = null;
  73620. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73621. for (i = start; i < end; i += dim)
  73622. last = insertNode(i, data[i], data[i + 1], last);
  73623. }
  73624. else {
  73625. for (i = end - dim; i >= start; i -= dim)
  73626. last = insertNode(i, data[i], data[i + 1], last);
  73627. }
  73628. if (last && equals(last, last.next)) {
  73629. removeNode(last);
  73630. last = last.next;
  73631. }
  73632. return last;
  73633. }
  73634. // eliminate colinear or duplicate points
  73635. function filterPoints(start, end) {
  73636. if (!start)
  73637. return start;
  73638. if (!end)
  73639. end = start;
  73640. var p = start, again;
  73641. do {
  73642. again = false;
  73643. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73644. removeNode(p);
  73645. p = end = p.prev;
  73646. if (p === p.next)
  73647. return undefined;
  73648. again = true;
  73649. }
  73650. else {
  73651. p = p.next;
  73652. }
  73653. } while (again || p !== end);
  73654. return end;
  73655. }
  73656. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73657. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73658. if (!ear)
  73659. return;
  73660. // interlink polygon nodes in z-order
  73661. if (!pass && size)
  73662. indexCurve(ear, minX, minY, size);
  73663. var stop = ear, prev, next;
  73664. // iterate through ears, slicing them one by one
  73665. while (ear.prev !== ear.next) {
  73666. prev = ear.prev;
  73667. next = ear.next;
  73668. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73669. // cut off the triangle
  73670. triangles.push(prev.i / dim);
  73671. triangles.push(ear.i / dim);
  73672. triangles.push(next.i / dim);
  73673. removeNode(ear);
  73674. // skipping the next vertice leads to less sliver triangles
  73675. ear = next.next;
  73676. stop = next.next;
  73677. continue;
  73678. }
  73679. ear = next;
  73680. // if we looped through the whole remaining polygon and can't find any more ears
  73681. if (ear === stop) {
  73682. // try filtering points and slicing again
  73683. if (!pass) {
  73684. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73685. // if this didn't work, try curing all small self-intersections locally
  73686. }
  73687. else if (pass === 1) {
  73688. ear = cureLocalIntersections(ear, triangles, dim);
  73689. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73690. // as a last resort, try splitting the remaining polygon into two
  73691. }
  73692. else if (pass === 2) {
  73693. splitEarcut(ear, triangles, dim, minX, minY, size);
  73694. }
  73695. break;
  73696. }
  73697. }
  73698. }
  73699. // check whether a polygon node forms a valid ear with adjacent nodes
  73700. function isEar(ear) {
  73701. var a = ear.prev, b = ear, c = ear.next;
  73702. if (area(a, b, c) >= 0)
  73703. return false; // reflex, can't be an ear
  73704. // now make sure we don't have other points inside the potential ear
  73705. var p = ear.next.next;
  73706. while (p !== ear.prev) {
  73707. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73708. area(p.prev, p, p.next) >= 0)
  73709. return false;
  73710. p = p.next;
  73711. }
  73712. return true;
  73713. }
  73714. function isEarHashed(ear, minX, minY, size) {
  73715. var a = ear.prev, b = ear, c = ear.next;
  73716. if (area(a, b, c) >= 0)
  73717. return false; // reflex, can't be an ear
  73718. // triangle bbox; min & max are calculated like this for speed
  73719. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  73720. // z-order range for the current triangle bbox;
  73721. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73722. // first look for points inside the triangle in increasing z-order
  73723. var p = ear.nextZ;
  73724. while (p && p.z <= maxZ) {
  73725. if (p !== ear.prev &&
  73726. p !== ear.next &&
  73727. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73728. area(p.prev, p, p.next) >= 0)
  73729. return false;
  73730. p = p.nextZ;
  73731. }
  73732. // then look for points in decreasing z-order
  73733. p = ear.prevZ;
  73734. while (p && p.z >= minZ) {
  73735. if (p !== ear.prev &&
  73736. p !== ear.next &&
  73737. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73738. area(p.prev, p, p.next) >= 0)
  73739. return false;
  73740. p = p.prevZ;
  73741. }
  73742. return true;
  73743. }
  73744. // go through all polygon nodes and cure small local self-intersections
  73745. function cureLocalIntersections(start, triangles, dim) {
  73746. var p = start;
  73747. do {
  73748. var a = p.prev, b = p.next.next;
  73749. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73750. triangles.push(a.i / dim);
  73751. triangles.push(p.i / dim);
  73752. triangles.push(b.i / dim);
  73753. // remove two nodes involved
  73754. removeNode(p);
  73755. removeNode(p.next);
  73756. p = start = b;
  73757. }
  73758. p = p.next;
  73759. } while (p !== start);
  73760. return p;
  73761. }
  73762. // try splitting polygon into two and triangulate them independently
  73763. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73764. // look for a valid diagonal that divides the polygon into two
  73765. var a = start;
  73766. do {
  73767. var b = a.next.next;
  73768. while (b !== a.prev) {
  73769. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73770. // split the polygon in two by the diagonal
  73771. var c = splitPolygon(a, b);
  73772. // filter colinear points around the cuts
  73773. a = filterPoints(a, a.next);
  73774. c = filterPoints(c, c.next);
  73775. // run earcut on each half
  73776. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73777. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73778. return;
  73779. }
  73780. b = b.next;
  73781. }
  73782. a = a.next;
  73783. } while (a !== start);
  73784. }
  73785. // link every hole into the outer loop, producing a single-ring polygon without holes
  73786. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73787. var queue = [], i, len, start, end, list;
  73788. for (i = 0, len = holeIndices.length; i < len; i++) {
  73789. start = holeIndices[i] * dim;
  73790. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73791. list = linkedList(data, start, end, dim, false);
  73792. if (list === list.next)
  73793. list.steiner = true;
  73794. queue.push(getLeftmost(list));
  73795. }
  73796. queue.sort(compareX);
  73797. // process holes from left to right
  73798. for (i = 0; i < queue.length; i++) {
  73799. eliminateHole(queue[i], outerNode);
  73800. outerNode = filterPoints(outerNode, outerNode.next);
  73801. }
  73802. return outerNode;
  73803. }
  73804. function compareX(a, b) {
  73805. return a.x - b.x;
  73806. }
  73807. // find a bridge between vertices that connects hole with an outer ring and and link it
  73808. function eliminateHole(hole, outerNode) {
  73809. outerNode = findHoleBridge(hole, outerNode);
  73810. if (outerNode) {
  73811. var b = splitPolygon(outerNode, hole);
  73812. filterPoints(b, b.next);
  73813. }
  73814. }
  73815. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73816. function findHoleBridge(hole, outerNode) {
  73817. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73818. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73819. // segment's endpoint with lesser x will be potential connection point
  73820. do {
  73821. if (hy <= p.y && hy >= p.next.y) {
  73822. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73823. if (x <= hx && x > qx) {
  73824. qx = x;
  73825. if (x === hx) {
  73826. if (hy === p.y)
  73827. return p;
  73828. if (hy === p.next.y)
  73829. return p.next;
  73830. }
  73831. m = p.x < p.next.x ? p : p.next;
  73832. }
  73833. }
  73834. p = p.next;
  73835. } while (p !== outerNode);
  73836. if (!m)
  73837. return null;
  73838. if (hx === qx)
  73839. return m.prev; // hole touches outer segment; pick lower endpoint
  73840. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73841. // if there are no points found, we have a valid connection;
  73842. // otherwise choose the point of the minimum angle with the ray as connection point
  73843. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73844. p = m.next;
  73845. while (p !== stop) {
  73846. if (hx >= p.x &&
  73847. p.x >= mx &&
  73848. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73849. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73850. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73851. m = p;
  73852. tanMin = tan;
  73853. }
  73854. }
  73855. p = p.next;
  73856. }
  73857. return m;
  73858. }
  73859. // interlink polygon nodes in z-order
  73860. function indexCurve(start, minX, minY, size) {
  73861. var p = start;
  73862. do {
  73863. if (p.z === null)
  73864. p.z = zOrder(p.x, p.y, minX, minY, size);
  73865. p.prevZ = p.prev;
  73866. p.nextZ = p.next;
  73867. p = p.next;
  73868. } while (p !== start);
  73869. p.prevZ.nextZ = null;
  73870. p.prevZ = null;
  73871. sortLinked(p);
  73872. }
  73873. // Simon Tatham's linked list merge sort algorithm
  73874. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73875. function sortLinked(list) {
  73876. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73877. do {
  73878. p = list;
  73879. list = null;
  73880. tail = null;
  73881. numMerges = 0;
  73882. while (p) {
  73883. numMerges++;
  73884. q = p;
  73885. pSize = 0;
  73886. for (i = 0; i < inSize; i++) {
  73887. pSize++;
  73888. q = q.nextZ;
  73889. if (!q)
  73890. break;
  73891. }
  73892. qSize = inSize;
  73893. while (pSize > 0 || (qSize > 0 && q)) {
  73894. if (pSize === 0) {
  73895. e = q;
  73896. q = q.nextZ;
  73897. qSize--;
  73898. }
  73899. else if (qSize === 0 || !q) {
  73900. e = p;
  73901. p = p.nextZ;
  73902. pSize--;
  73903. }
  73904. else if (p.z <= q.z) {
  73905. e = p;
  73906. p = p.nextZ;
  73907. pSize--;
  73908. }
  73909. else {
  73910. e = q;
  73911. q = q.nextZ;
  73912. qSize--;
  73913. }
  73914. if (tail)
  73915. tail.nextZ = e;
  73916. else
  73917. list = e;
  73918. e.prevZ = tail;
  73919. tail = e;
  73920. }
  73921. p = q;
  73922. }
  73923. tail.nextZ = null;
  73924. inSize *= 2;
  73925. } while (numMerges > 1);
  73926. return list;
  73927. }
  73928. // z-order of a point given coords and size of the data bounding box
  73929. function zOrder(x, y, minX, minY, size) {
  73930. // coords are transformed into non-negative 15-bit integer range
  73931. x = 32767 * (x - minX) / size;
  73932. y = 32767 * (y - minY) / size;
  73933. x = (x | (x << 8)) & 0x00FF00FF;
  73934. x = (x | (x << 4)) & 0x0F0F0F0F;
  73935. x = (x | (x << 2)) & 0x33333333;
  73936. x = (x | (x << 1)) & 0x55555555;
  73937. y = (y | (y << 8)) & 0x00FF00FF;
  73938. y = (y | (y << 4)) & 0x0F0F0F0F;
  73939. y = (y | (y << 2)) & 0x33333333;
  73940. y = (y | (y << 1)) & 0x55555555;
  73941. return x | (y << 1);
  73942. }
  73943. // find the leftmost node of a polygon ring
  73944. function getLeftmost(start) {
  73945. var p = start, leftmost = start;
  73946. do {
  73947. if (p.x < leftmost.x)
  73948. leftmost = p;
  73949. p = p.next;
  73950. } while (p !== start);
  73951. return leftmost;
  73952. }
  73953. // check if a point lies within a convex triangle
  73954. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73955. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73956. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73957. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73958. }
  73959. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73960. function isValidDiagonal(a, b) {
  73961. return a.next.i !== b.i &&
  73962. a.prev.i !== b.i &&
  73963. !intersectsPolygon(a, b) &&
  73964. locallyInside(a, b) &&
  73965. locallyInside(b, a) &&
  73966. middleInside(a, b);
  73967. }
  73968. // signed area of a triangle
  73969. function area(p, q, r) {
  73970. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73971. }
  73972. // check if two points are equal
  73973. function equals(p1, p2) {
  73974. return p1.x === p2.x && p1.y === p2.y;
  73975. }
  73976. // check if two segments intersect
  73977. function intersects(p1, q1, p2, q2) {
  73978. if ((equals(p1, q1) && equals(p2, q2)) ||
  73979. (equals(p1, q2) && equals(p2, q1)))
  73980. return true;
  73981. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73982. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73983. }
  73984. // check if a polygon diagonal intersects any polygon segments
  73985. function intersectsPolygon(a, b) {
  73986. var p = a;
  73987. do {
  73988. if (p.i !== a.i &&
  73989. p.next.i !== a.i &&
  73990. p.i !== b.i &&
  73991. p.next.i !== b.i &&
  73992. intersects(p, p.next, a, b))
  73993. return true;
  73994. p = p.next;
  73995. } while (p !== a);
  73996. return false;
  73997. }
  73998. // check if a polygon diagonal is locally inside the polygon
  73999. function locallyInside(a, b) {
  74000. return area(a.prev, a, a.next) < 0
  74001. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74002. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74003. }
  74004. // check if the middle point of a polygon diagonal is inside the polygon
  74005. function middleInside(a, b) {
  74006. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74007. do {
  74008. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74009. inside = !inside;
  74010. p = p.next;
  74011. } while (p !== a);
  74012. return inside;
  74013. }
  74014. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74015. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74016. function splitPolygon(a, b) {
  74017. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  74018. a.next = b;
  74019. b.prev = a;
  74020. a2.next = an;
  74021. an.prev = a2;
  74022. b2.next = a2;
  74023. a2.prev = b2;
  74024. bp.next = b2;
  74025. b2.prev = bp;
  74026. return b2;
  74027. }
  74028. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74029. function insertNode(i, x, y, last) {
  74030. var p = new Node(i, x, y);
  74031. if (!last) {
  74032. p.prev = p;
  74033. p.next = p;
  74034. }
  74035. else {
  74036. p.next = last.next;
  74037. p.prev = last;
  74038. last.next.prev = p;
  74039. last.next = p;
  74040. }
  74041. return p;
  74042. }
  74043. function removeNode(p) {
  74044. p.next.prev = p.prev;
  74045. p.prev.next = p.next;
  74046. if (p.prevZ)
  74047. p.prevZ.nextZ = p.nextZ;
  74048. if (p.nextZ)
  74049. p.nextZ.prevZ = p.prevZ;
  74050. }
  74051. /**
  74052. * return a percentage difference between the polygon area and its triangulation area;
  74053. * used to verify correctness of triangulation
  74054. */
  74055. function deviation(data, holeIndices, dim, triangles) {
  74056. var hasHoles = holeIndices && holeIndices.length;
  74057. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74058. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74059. if (hasHoles) {
  74060. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74061. var start = holeIndices[i] * dim;
  74062. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74063. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74064. }
  74065. }
  74066. var trianglesArea = 0;
  74067. for (i = 0; i < triangles.length; i += 3) {
  74068. var a = triangles[i] * dim;
  74069. var b = triangles[i + 1] * dim;
  74070. var c = triangles[i + 2] * dim;
  74071. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74072. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74073. }
  74074. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74075. }
  74076. Earcut.deviation = deviation;
  74077. ;
  74078. function signedArea(data, start, end, dim) {
  74079. var sum = 0;
  74080. for (var i = start, j = end - dim; i < end; i += dim) {
  74081. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74082. j = i;
  74083. }
  74084. return sum;
  74085. }
  74086. /**
  74087. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74088. */
  74089. function flatten(data) {
  74090. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74091. for (var i = 0; i < data.length; i++) {
  74092. for (var j = 0; j < data[i].length; j++) {
  74093. for (var d = 0; d < dim; d++)
  74094. result.vertices.push(data[i][j][d]);
  74095. }
  74096. if (i > 0) {
  74097. holeIndex += data[i - 1].length;
  74098. result.holes.push(holeIndex);
  74099. }
  74100. }
  74101. return result;
  74102. }
  74103. Earcut.flatten = flatten;
  74104. ;
  74105. })(Earcut || (Earcut = {}));
  74106. //# sourceMappingURL=babylon.earcut.js.map
  74107. var BABYLON;
  74108. (function (BABYLON) {
  74109. var IndexedVector2 = /** @class */ (function (_super) {
  74110. __extends(IndexedVector2, _super);
  74111. function IndexedVector2(original, index) {
  74112. var _this = _super.call(this, original.x, original.y) || this;
  74113. _this.index = index;
  74114. return _this;
  74115. }
  74116. return IndexedVector2;
  74117. }(BABYLON.Vector2));
  74118. var PolygonPoints = /** @class */ (function () {
  74119. function PolygonPoints() {
  74120. this.elements = new Array();
  74121. }
  74122. PolygonPoints.prototype.add = function (originalPoints) {
  74123. var _this = this;
  74124. var result = new Array();
  74125. originalPoints.forEach(function (point) {
  74126. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74127. var newPoint = new IndexedVector2(point, _this.elements.length);
  74128. result.push(newPoint);
  74129. _this.elements.push(newPoint);
  74130. }
  74131. });
  74132. return result;
  74133. };
  74134. PolygonPoints.prototype.computeBounds = function () {
  74135. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74136. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74137. this.elements.forEach(function (point) {
  74138. // x
  74139. if (point.x < lmin.x) {
  74140. lmin.x = point.x;
  74141. }
  74142. else if (point.x > lmax.x) {
  74143. lmax.x = point.x;
  74144. }
  74145. // y
  74146. if (point.y < lmin.y) {
  74147. lmin.y = point.y;
  74148. }
  74149. else if (point.y > lmax.y) {
  74150. lmax.y = point.y;
  74151. }
  74152. });
  74153. return {
  74154. min: lmin,
  74155. max: lmax,
  74156. width: lmax.x - lmin.x,
  74157. height: lmax.y - lmin.y
  74158. };
  74159. };
  74160. return PolygonPoints;
  74161. }());
  74162. var Polygon = /** @class */ (function () {
  74163. function Polygon() {
  74164. }
  74165. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74166. return [
  74167. new BABYLON.Vector2(xmin, ymin),
  74168. new BABYLON.Vector2(xmax, ymin),
  74169. new BABYLON.Vector2(xmax, ymax),
  74170. new BABYLON.Vector2(xmin, ymax)
  74171. ];
  74172. };
  74173. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74174. if (cx === void 0) { cx = 0; }
  74175. if (cy === void 0) { cy = 0; }
  74176. if (numberOfSides === void 0) { numberOfSides = 32; }
  74177. var result = new Array();
  74178. var angle = 0;
  74179. var increment = (Math.PI * 2) / numberOfSides;
  74180. for (var i = 0; i < numberOfSides; i++) {
  74181. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74182. angle -= increment;
  74183. }
  74184. return result;
  74185. };
  74186. Polygon.Parse = function (input) {
  74187. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74188. var i, result = [];
  74189. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74190. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74191. }
  74192. return result;
  74193. };
  74194. Polygon.StartingAt = function (x, y) {
  74195. return BABYLON.Path2.StartingAt(x, y);
  74196. };
  74197. return Polygon;
  74198. }());
  74199. BABYLON.Polygon = Polygon;
  74200. var PolygonMeshBuilder = /** @class */ (function () {
  74201. function PolygonMeshBuilder(name, contours, scene) {
  74202. this._points = new PolygonPoints();
  74203. this._outlinepoints = new PolygonPoints();
  74204. this._holes = new Array();
  74205. this._epoints = new Array();
  74206. this._eholes = new Array();
  74207. this._name = name;
  74208. this._scene = scene;
  74209. var points;
  74210. if (contours instanceof BABYLON.Path2) {
  74211. points = contours.getPoints();
  74212. }
  74213. else {
  74214. points = contours;
  74215. }
  74216. this._addToepoint(points);
  74217. this._points.add(points);
  74218. this._outlinepoints.add(points);
  74219. }
  74220. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74221. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74222. var p = points_1[_i];
  74223. this._epoints.push(p.x, p.y);
  74224. }
  74225. };
  74226. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74227. this._points.add(hole);
  74228. var holepoints = new PolygonPoints();
  74229. holepoints.add(hole);
  74230. this._holes.push(holepoints);
  74231. this._eholes.push(this._epoints.length / 2);
  74232. this._addToepoint(hole);
  74233. return this;
  74234. };
  74235. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74236. var _this = this;
  74237. if (updatable === void 0) { updatable = false; }
  74238. if (depth === void 0) { depth = 0; }
  74239. var result = new BABYLON.Mesh(this._name, this._scene);
  74240. var normals = new Array();
  74241. var positions = new Array();
  74242. var uvs = new Array();
  74243. var bounds = this._points.computeBounds();
  74244. this._points.elements.forEach(function (p) {
  74245. normals.push(0, 1.0, 0);
  74246. positions.push(p.x, 0, p.y);
  74247. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74248. });
  74249. var indices = new Array();
  74250. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74251. for (var i = 0; i < res.length; i++) {
  74252. indices.push(res[i]);
  74253. }
  74254. if (depth > 0) {
  74255. var positionscount = (positions.length / 3); //get the current pointcount
  74256. this._points.elements.forEach(function (p) {
  74257. normals.push(0, -1.0, 0);
  74258. positions.push(p.x, -depth, p.y);
  74259. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74260. });
  74261. var totalCount = indices.length;
  74262. for (var i = 0; i < totalCount; i += 3) {
  74263. var i0 = indices[i + 0];
  74264. var i1 = indices[i + 1];
  74265. var i2 = indices[i + 2];
  74266. indices.push(i2 + positionscount);
  74267. indices.push(i1 + positionscount);
  74268. indices.push(i0 + positionscount);
  74269. }
  74270. //Add the sides
  74271. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74272. this._holes.forEach(function (hole) {
  74273. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74274. });
  74275. }
  74276. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74277. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74278. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74279. result.setIndices(indices);
  74280. return result;
  74281. };
  74282. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74283. var StartIndex = positions.length / 3;
  74284. var ulength = 0;
  74285. for (var i = 0; i < points.elements.length; i++) {
  74286. var p = points.elements[i];
  74287. var p1;
  74288. if ((i + 1) > points.elements.length - 1) {
  74289. p1 = points.elements[0];
  74290. }
  74291. else {
  74292. p1 = points.elements[i + 1];
  74293. }
  74294. positions.push(p.x, 0, p.y);
  74295. positions.push(p.x, -depth, p.y);
  74296. positions.push(p1.x, 0, p1.y);
  74297. positions.push(p1.x, -depth, p1.y);
  74298. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74299. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74300. var v3 = v2.subtract(v1);
  74301. var v4 = new BABYLON.Vector3(0, 1, 0);
  74302. var vn = BABYLON.Vector3.Cross(v3, v4);
  74303. vn = vn.normalize();
  74304. uvs.push(ulength / bounds.width, 0);
  74305. uvs.push(ulength / bounds.width, 1);
  74306. ulength += v3.length();
  74307. uvs.push((ulength / bounds.width), 0);
  74308. uvs.push((ulength / bounds.width), 1);
  74309. if (!flip) {
  74310. normals.push(-vn.x, -vn.y, -vn.z);
  74311. normals.push(-vn.x, -vn.y, -vn.z);
  74312. normals.push(-vn.x, -vn.y, -vn.z);
  74313. normals.push(-vn.x, -vn.y, -vn.z);
  74314. indices.push(StartIndex);
  74315. indices.push(StartIndex + 1);
  74316. indices.push(StartIndex + 2);
  74317. indices.push(StartIndex + 1);
  74318. indices.push(StartIndex + 3);
  74319. indices.push(StartIndex + 2);
  74320. }
  74321. else {
  74322. normals.push(vn.x, vn.y, vn.z);
  74323. normals.push(vn.x, vn.y, vn.z);
  74324. normals.push(vn.x, vn.y, vn.z);
  74325. normals.push(vn.x, vn.y, vn.z);
  74326. indices.push(StartIndex);
  74327. indices.push(StartIndex + 2);
  74328. indices.push(StartIndex + 1);
  74329. indices.push(StartIndex + 1);
  74330. indices.push(StartIndex + 2);
  74331. indices.push(StartIndex + 3);
  74332. }
  74333. StartIndex += 4;
  74334. }
  74335. ;
  74336. };
  74337. return PolygonMeshBuilder;
  74338. }());
  74339. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74340. })(BABYLON || (BABYLON = {}));
  74341. //# sourceMappingURL=babylon.polygonMesh.js.map
  74342. var BABYLON;
  74343. (function (BABYLON) {
  74344. // Unique ID when we import meshes from Babylon to CSG
  74345. var currentCSGMeshId = 0;
  74346. // # class Vertex
  74347. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74348. // one to provide additional features like texture coordinates and vertex
  74349. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74350. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74351. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74352. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74353. // is not used anywhere else.
  74354. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74355. var Vertex = /** @class */ (function () {
  74356. function Vertex(pos, normal, uv) {
  74357. this.pos = pos;
  74358. this.normal = normal;
  74359. this.uv = uv;
  74360. }
  74361. Vertex.prototype.clone = function () {
  74362. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74363. };
  74364. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74365. // orientation of a polygon is flipped.
  74366. Vertex.prototype.flip = function () {
  74367. this.normal = this.normal.scale(-1);
  74368. };
  74369. // Create a new vertex between this vertex and `other` by linearly
  74370. // interpolating all properties using a parameter of `t`. Subclasses should
  74371. // override this to interpolate additional properties.
  74372. Vertex.prototype.interpolate = function (other, t) {
  74373. 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));
  74374. };
  74375. return Vertex;
  74376. }());
  74377. // # class Plane
  74378. // Represents a plane in 3D space.
  74379. var Plane = /** @class */ (function () {
  74380. function Plane(normal, w) {
  74381. this.normal = normal;
  74382. this.w = w;
  74383. }
  74384. Plane.FromPoints = function (a, b, c) {
  74385. var v0 = c.subtract(a);
  74386. var v1 = b.subtract(a);
  74387. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74388. return null;
  74389. }
  74390. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74391. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74392. };
  74393. Plane.prototype.clone = function () {
  74394. return new Plane(this.normal.clone(), this.w);
  74395. };
  74396. Plane.prototype.flip = function () {
  74397. this.normal.scaleInPlace(-1);
  74398. this.w = -this.w;
  74399. };
  74400. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74401. // fragments in the appropriate lists. Coplanar polygons go into either
  74402. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74403. // respect to this plane. Polygons in front or in back of this plane go into
  74404. // either `front` or `back`.
  74405. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74406. var COPLANAR = 0;
  74407. var FRONT = 1;
  74408. var BACK = 2;
  74409. var SPANNING = 3;
  74410. // Classify each point as well as the entire polygon into one of the above
  74411. // four classes.
  74412. var polygonType = 0;
  74413. var types = [];
  74414. var i;
  74415. var t;
  74416. for (i = 0; i < polygon.vertices.length; i++) {
  74417. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74418. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74419. polygonType |= type;
  74420. types.push(type);
  74421. }
  74422. // Put the polygon in the correct list, splitting it when necessary.
  74423. switch (polygonType) {
  74424. case COPLANAR:
  74425. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74426. break;
  74427. case FRONT:
  74428. front.push(polygon);
  74429. break;
  74430. case BACK:
  74431. back.push(polygon);
  74432. break;
  74433. case SPANNING:
  74434. var f = [], b = [];
  74435. for (i = 0; i < polygon.vertices.length; i++) {
  74436. var j = (i + 1) % polygon.vertices.length;
  74437. var ti = types[i], tj = types[j];
  74438. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74439. if (ti !== BACK)
  74440. f.push(vi);
  74441. if (ti !== FRONT)
  74442. b.push(ti !== BACK ? vi.clone() : vi);
  74443. if ((ti | tj) === SPANNING) {
  74444. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74445. var v = vi.interpolate(vj, t);
  74446. f.push(v);
  74447. b.push(v.clone());
  74448. }
  74449. }
  74450. var poly;
  74451. if (f.length >= 3) {
  74452. poly = new Polygon(f, polygon.shared);
  74453. if (poly.plane)
  74454. front.push(poly);
  74455. }
  74456. if (b.length >= 3) {
  74457. poly = new Polygon(b, polygon.shared);
  74458. if (poly.plane)
  74459. back.push(poly);
  74460. }
  74461. break;
  74462. }
  74463. };
  74464. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74465. // point is on the plane.
  74466. Plane.EPSILON = 1e-5;
  74467. return Plane;
  74468. }());
  74469. // # class Polygon
  74470. // Represents a convex polygon. The vertices used to initialize a polygon must
  74471. // be coplanar and form a convex loop.
  74472. //
  74473. // Each convex polygon has a `shared` property, which is shared between all
  74474. // polygons that are clones of each other or were split from the same polygon.
  74475. // This can be used to define per-polygon properties (such as surface color).
  74476. var Polygon = /** @class */ (function () {
  74477. function Polygon(vertices, shared) {
  74478. this.vertices = vertices;
  74479. this.shared = shared;
  74480. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74481. }
  74482. Polygon.prototype.clone = function () {
  74483. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74484. return new Polygon(vertices, this.shared);
  74485. };
  74486. Polygon.prototype.flip = function () {
  74487. this.vertices.reverse().map(function (v) { v.flip(); });
  74488. this.plane.flip();
  74489. };
  74490. return Polygon;
  74491. }());
  74492. // # class Node
  74493. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74494. // by picking a polygon to split along. That polygon (and all other coplanar
  74495. // polygons) are added directly to that node and the other polygons are added to
  74496. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74497. // no distinction between internal and leaf nodes.
  74498. var Node = /** @class */ (function () {
  74499. function Node(polygons) {
  74500. this.plane = null;
  74501. this.front = null;
  74502. this.back = null;
  74503. this.polygons = new Array();
  74504. if (polygons) {
  74505. this.build(polygons);
  74506. }
  74507. }
  74508. Node.prototype.clone = function () {
  74509. var node = new Node();
  74510. node.plane = this.plane && this.plane.clone();
  74511. node.front = this.front && this.front.clone();
  74512. node.back = this.back && this.back.clone();
  74513. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74514. return node;
  74515. };
  74516. // Convert solid space to empty space and empty space to solid space.
  74517. Node.prototype.invert = function () {
  74518. for (var i = 0; i < this.polygons.length; i++) {
  74519. this.polygons[i].flip();
  74520. }
  74521. if (this.plane) {
  74522. this.plane.flip();
  74523. }
  74524. if (this.front) {
  74525. this.front.invert();
  74526. }
  74527. if (this.back) {
  74528. this.back.invert();
  74529. }
  74530. var temp = this.front;
  74531. this.front = this.back;
  74532. this.back = temp;
  74533. };
  74534. // Recursively remove all polygons in `polygons` that are inside this BSP
  74535. // tree.
  74536. Node.prototype.clipPolygons = function (polygons) {
  74537. if (!this.plane)
  74538. return polygons.slice();
  74539. var front = new Array(), back = new Array();
  74540. for (var i = 0; i < polygons.length; i++) {
  74541. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74542. }
  74543. if (this.front) {
  74544. front = this.front.clipPolygons(front);
  74545. }
  74546. if (this.back) {
  74547. back = this.back.clipPolygons(back);
  74548. }
  74549. else {
  74550. back = [];
  74551. }
  74552. return front.concat(back);
  74553. };
  74554. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74555. // `bsp`.
  74556. Node.prototype.clipTo = function (bsp) {
  74557. this.polygons = bsp.clipPolygons(this.polygons);
  74558. if (this.front)
  74559. this.front.clipTo(bsp);
  74560. if (this.back)
  74561. this.back.clipTo(bsp);
  74562. };
  74563. // Return a list of all polygons in this BSP tree.
  74564. Node.prototype.allPolygons = function () {
  74565. var polygons = this.polygons.slice();
  74566. if (this.front)
  74567. polygons = polygons.concat(this.front.allPolygons());
  74568. if (this.back)
  74569. polygons = polygons.concat(this.back.allPolygons());
  74570. return polygons;
  74571. };
  74572. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74573. // new polygons are filtered down to the bottom of the tree and become new
  74574. // nodes there. Each set of polygons is partitioned using the first polygon
  74575. // (no heuristic is used to pick a good split).
  74576. Node.prototype.build = function (polygons) {
  74577. if (!polygons.length)
  74578. return;
  74579. if (!this.plane)
  74580. this.plane = polygons[0].plane.clone();
  74581. var front = new Array(), back = new Array();
  74582. for (var i = 0; i < polygons.length; i++) {
  74583. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74584. }
  74585. if (front.length) {
  74586. if (!this.front)
  74587. this.front = new Node();
  74588. this.front.build(front);
  74589. }
  74590. if (back.length) {
  74591. if (!this.back)
  74592. this.back = new Node();
  74593. this.back.build(back);
  74594. }
  74595. };
  74596. return Node;
  74597. }());
  74598. var CSG = /** @class */ (function () {
  74599. function CSG() {
  74600. this.polygons = new Array();
  74601. }
  74602. // Convert BABYLON.Mesh to BABYLON.CSG
  74603. CSG.FromMesh = function (mesh) {
  74604. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74605. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74606. if (mesh instanceof BABYLON.Mesh) {
  74607. mesh.computeWorldMatrix(true);
  74608. matrix = mesh.getWorldMatrix();
  74609. meshPosition = mesh.position.clone();
  74610. meshRotation = mesh.rotation.clone();
  74611. if (mesh.rotationQuaternion) {
  74612. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74613. }
  74614. meshScaling = mesh.scaling.clone();
  74615. }
  74616. else {
  74617. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74618. }
  74619. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74620. var subMeshes = mesh.subMeshes;
  74621. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74622. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74623. vertices = [];
  74624. for (var j = 0; j < 3; j++) {
  74625. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74626. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74627. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74628. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74629. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74630. vertex = new Vertex(position, normal, uv);
  74631. vertices.push(vertex);
  74632. }
  74633. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74634. // To handle the case of degenerated triangle
  74635. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74636. if (polygon.plane)
  74637. polygons.push(polygon);
  74638. }
  74639. }
  74640. var csg = CSG.FromPolygons(polygons);
  74641. csg.matrix = matrix;
  74642. csg.position = meshPosition;
  74643. csg.rotation = meshRotation;
  74644. csg.scaling = meshScaling;
  74645. csg.rotationQuaternion = meshRotationQuaternion;
  74646. currentCSGMeshId++;
  74647. return csg;
  74648. };
  74649. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74650. CSG.FromPolygons = function (polygons) {
  74651. var csg = new CSG();
  74652. csg.polygons = polygons;
  74653. return csg;
  74654. };
  74655. CSG.prototype.clone = function () {
  74656. var csg = new CSG();
  74657. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74658. csg.copyTransformAttributes(this);
  74659. return csg;
  74660. };
  74661. CSG.prototype.union = function (csg) {
  74662. var a = new Node(this.clone().polygons);
  74663. var b = new Node(csg.clone().polygons);
  74664. a.clipTo(b);
  74665. b.clipTo(a);
  74666. b.invert();
  74667. b.clipTo(a);
  74668. b.invert();
  74669. a.build(b.allPolygons());
  74670. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74671. };
  74672. CSG.prototype.unionInPlace = function (csg) {
  74673. var a = new Node(this.polygons);
  74674. var b = new Node(csg.polygons);
  74675. a.clipTo(b);
  74676. b.clipTo(a);
  74677. b.invert();
  74678. b.clipTo(a);
  74679. b.invert();
  74680. a.build(b.allPolygons());
  74681. this.polygons = a.allPolygons();
  74682. };
  74683. CSG.prototype.subtract = function (csg) {
  74684. var a = new Node(this.clone().polygons);
  74685. var b = new Node(csg.clone().polygons);
  74686. a.invert();
  74687. a.clipTo(b);
  74688. b.clipTo(a);
  74689. b.invert();
  74690. b.clipTo(a);
  74691. b.invert();
  74692. a.build(b.allPolygons());
  74693. a.invert();
  74694. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74695. };
  74696. CSG.prototype.subtractInPlace = function (csg) {
  74697. var a = new Node(this.polygons);
  74698. var b = new Node(csg.polygons);
  74699. a.invert();
  74700. a.clipTo(b);
  74701. b.clipTo(a);
  74702. b.invert();
  74703. b.clipTo(a);
  74704. b.invert();
  74705. a.build(b.allPolygons());
  74706. a.invert();
  74707. this.polygons = a.allPolygons();
  74708. };
  74709. CSG.prototype.intersect = function (csg) {
  74710. var a = new Node(this.clone().polygons);
  74711. var b = new Node(csg.clone().polygons);
  74712. a.invert();
  74713. b.clipTo(a);
  74714. b.invert();
  74715. a.clipTo(b);
  74716. b.clipTo(a);
  74717. a.build(b.allPolygons());
  74718. a.invert();
  74719. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74720. };
  74721. CSG.prototype.intersectInPlace = function (csg) {
  74722. var a = new Node(this.polygons);
  74723. var b = new Node(csg.polygons);
  74724. a.invert();
  74725. b.clipTo(a);
  74726. b.invert();
  74727. a.clipTo(b);
  74728. b.clipTo(a);
  74729. a.build(b.allPolygons());
  74730. a.invert();
  74731. this.polygons = a.allPolygons();
  74732. };
  74733. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74734. // not modified.
  74735. CSG.prototype.inverse = function () {
  74736. var csg = this.clone();
  74737. csg.inverseInPlace();
  74738. return csg;
  74739. };
  74740. CSG.prototype.inverseInPlace = function () {
  74741. this.polygons.map(function (p) { p.flip(); });
  74742. };
  74743. // This is used to keep meshes transformations so they can be restored
  74744. // when we build back a Babylon Mesh
  74745. // NB : All CSG operations are performed in world coordinates
  74746. CSG.prototype.copyTransformAttributes = function (csg) {
  74747. this.matrix = csg.matrix;
  74748. this.position = csg.position;
  74749. this.rotation = csg.rotation;
  74750. this.scaling = csg.scaling;
  74751. this.rotationQuaternion = csg.rotationQuaternion;
  74752. return this;
  74753. };
  74754. // Build Raw mesh from CSG
  74755. // Coordinates here are in world space
  74756. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74757. var matrix = this.matrix.clone();
  74758. matrix.invert();
  74759. 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;
  74760. if (keepSubMeshes) {
  74761. // Sort Polygons, since subMeshes are indices range
  74762. polygons.sort(function (a, b) {
  74763. if (a.shared.meshId === b.shared.meshId) {
  74764. return a.shared.subMeshId - b.shared.subMeshId;
  74765. }
  74766. else {
  74767. return a.shared.meshId - b.shared.meshId;
  74768. }
  74769. });
  74770. }
  74771. for (var i = 0, il = polygons.length; i < il; i++) {
  74772. polygon = polygons[i];
  74773. // Building SubMeshes
  74774. if (!subMesh_dict[polygon.shared.meshId]) {
  74775. subMesh_dict[polygon.shared.meshId] = {};
  74776. }
  74777. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74778. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74779. indexStart: +Infinity,
  74780. indexEnd: -Infinity,
  74781. materialIndex: polygon.shared.materialIndex
  74782. };
  74783. }
  74784. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74785. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74786. polygonIndices[0] = 0;
  74787. polygonIndices[1] = j - 1;
  74788. polygonIndices[2] = j;
  74789. for (var k = 0; k < 3; k++) {
  74790. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74791. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74792. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74793. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74794. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74795. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74796. // Check if 2 points can be merged
  74797. if (!(typeof vertex_idx !== 'undefined' &&
  74798. normals[vertex_idx * 3] === localNormal.x &&
  74799. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74800. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74801. uvs[vertex_idx * 2] === uv.x &&
  74802. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74803. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74804. uvs.push(uv.x, uv.y);
  74805. normals.push(normal.x, normal.y, normal.z);
  74806. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74807. }
  74808. indices.push(vertex_idx);
  74809. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74810. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74811. currentIndex++;
  74812. }
  74813. }
  74814. }
  74815. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74816. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74817. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74818. mesh.setIndices(indices, null);
  74819. if (keepSubMeshes) {
  74820. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74821. var materialIndexOffset = 0, materialMaxIndex;
  74822. mesh.subMeshes = new Array();
  74823. for (var m in subMesh_dict) {
  74824. materialMaxIndex = -1;
  74825. for (var sm in subMesh_dict[m]) {
  74826. subMesh_obj = subMesh_dict[m][sm];
  74827. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74828. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74829. }
  74830. materialIndexOffset += ++materialMaxIndex;
  74831. }
  74832. }
  74833. return mesh;
  74834. };
  74835. // Build Mesh from CSG taking material and transforms into account
  74836. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74837. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74838. mesh.material = material;
  74839. mesh.position.copyFrom(this.position);
  74840. mesh.rotation.copyFrom(this.rotation);
  74841. if (this.rotationQuaternion) {
  74842. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74843. }
  74844. mesh.scaling.copyFrom(this.scaling);
  74845. mesh.computeWorldMatrix(true);
  74846. return mesh;
  74847. };
  74848. return CSG;
  74849. }());
  74850. BABYLON.CSG = CSG;
  74851. })(BABYLON || (BABYLON = {}));
  74852. //# sourceMappingURL=babylon.csg.js.map
  74853. var BABYLON;
  74854. (function (BABYLON) {
  74855. var LensFlare = /** @class */ (function () {
  74856. function LensFlare(size, position, color, imgUrl, system) {
  74857. this.size = size;
  74858. this.position = position;
  74859. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74860. this.color = color || new BABYLON.Color3(1, 1, 1);
  74861. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74862. this._system = system;
  74863. system.lensFlares.push(this);
  74864. }
  74865. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74866. return new LensFlare(size, position, color, imgUrl, system);
  74867. };
  74868. LensFlare.prototype.dispose = function () {
  74869. if (this.texture) {
  74870. this.texture.dispose();
  74871. }
  74872. // Remove from scene
  74873. var index = this._system.lensFlares.indexOf(this);
  74874. this._system.lensFlares.splice(index, 1);
  74875. };
  74876. ;
  74877. return LensFlare;
  74878. }());
  74879. BABYLON.LensFlare = LensFlare;
  74880. })(BABYLON || (BABYLON = {}));
  74881. //# sourceMappingURL=babylon.lensFlare.js.map
  74882. var BABYLON;
  74883. (function (BABYLON) {
  74884. var LensFlareSystem = /** @class */ (function () {
  74885. function LensFlareSystem(name, emitter, scene) {
  74886. this.name = name;
  74887. this.lensFlares = new Array();
  74888. this.borderLimit = 300;
  74889. this.viewportBorder = 0;
  74890. this.layerMask = 0x0FFFFFFF;
  74891. this._vertexBuffers = {};
  74892. this._isEnabled = true;
  74893. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74894. this._emitter = emitter;
  74895. this.id = name;
  74896. scene.lensFlareSystems.push(this);
  74897. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74898. var engine = scene.getEngine();
  74899. // VBO
  74900. var vertices = [];
  74901. vertices.push(1, 1);
  74902. vertices.push(-1, 1);
  74903. vertices.push(-1, -1);
  74904. vertices.push(1, -1);
  74905. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74906. // Indices
  74907. var indices = [];
  74908. indices.push(0);
  74909. indices.push(1);
  74910. indices.push(2);
  74911. indices.push(0);
  74912. indices.push(2);
  74913. indices.push(3);
  74914. this._indexBuffer = engine.createIndexBuffer(indices);
  74915. // Effects
  74916. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74917. }
  74918. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74919. get: function () {
  74920. return this._isEnabled;
  74921. },
  74922. set: function (value) {
  74923. this._isEnabled = value;
  74924. },
  74925. enumerable: true,
  74926. configurable: true
  74927. });
  74928. LensFlareSystem.prototype.getScene = function () {
  74929. return this._scene;
  74930. };
  74931. LensFlareSystem.prototype.getEmitter = function () {
  74932. return this._emitter;
  74933. };
  74934. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74935. this._emitter = newEmitter;
  74936. };
  74937. LensFlareSystem.prototype.getEmitterPosition = function () {
  74938. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74939. };
  74940. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74941. var position = this.getEmitterPosition();
  74942. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74943. this._positionX = position.x;
  74944. this._positionY = position.y;
  74945. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74946. if (this.viewportBorder > 0) {
  74947. globalViewport.x -= this.viewportBorder;
  74948. globalViewport.y -= this.viewportBorder;
  74949. globalViewport.width += this.viewportBorder * 2;
  74950. globalViewport.height += this.viewportBorder * 2;
  74951. position.x += this.viewportBorder;
  74952. position.y += this.viewportBorder;
  74953. this._positionX += this.viewportBorder;
  74954. this._positionY += this.viewportBorder;
  74955. }
  74956. if (position.z > 0) {
  74957. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74958. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74959. return true;
  74960. }
  74961. return true;
  74962. }
  74963. return false;
  74964. };
  74965. LensFlareSystem.prototype._isVisible = function () {
  74966. if (!this._isEnabled || !this._scene.activeCamera) {
  74967. return false;
  74968. }
  74969. var emitterPosition = this.getEmitterPosition();
  74970. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74971. var distance = direction.length();
  74972. direction.normalize();
  74973. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74974. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74975. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74976. };
  74977. LensFlareSystem.prototype.render = function () {
  74978. if (!this._effect.isReady() || !this._scene.activeCamera)
  74979. return false;
  74980. var engine = this._scene.getEngine();
  74981. var viewport = this._scene.activeCamera.viewport;
  74982. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74983. // Position
  74984. if (!this.computeEffectivePosition(globalViewport)) {
  74985. return false;
  74986. }
  74987. // Visibility
  74988. if (!this._isVisible()) {
  74989. return false;
  74990. }
  74991. // Intensity
  74992. var awayX;
  74993. var awayY;
  74994. if (this._positionX < this.borderLimit + globalViewport.x) {
  74995. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74996. }
  74997. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74998. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74999. }
  75000. else {
  75001. awayX = 0;
  75002. }
  75003. if (this._positionY < this.borderLimit + globalViewport.y) {
  75004. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75005. }
  75006. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75007. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75008. }
  75009. else {
  75010. awayY = 0;
  75011. }
  75012. var away = (awayX > awayY) ? awayX : awayY;
  75013. away -= this.viewportBorder;
  75014. if (away > this.borderLimit) {
  75015. away = this.borderLimit;
  75016. }
  75017. var intensity = 1.0 - (away / this.borderLimit);
  75018. if (intensity < 0) {
  75019. return false;
  75020. }
  75021. if (intensity > 1.0) {
  75022. intensity = 1.0;
  75023. }
  75024. if (this.viewportBorder > 0) {
  75025. globalViewport.x += this.viewportBorder;
  75026. globalViewport.y += this.viewportBorder;
  75027. globalViewport.width -= this.viewportBorder * 2;
  75028. globalViewport.height -= this.viewportBorder * 2;
  75029. this._positionX -= this.viewportBorder;
  75030. this._positionY -= this.viewportBorder;
  75031. }
  75032. // Position
  75033. var centerX = globalViewport.x + globalViewport.width / 2;
  75034. var centerY = globalViewport.y + globalViewport.height / 2;
  75035. var distX = centerX - this._positionX;
  75036. var distY = centerY - this._positionY;
  75037. // Effects
  75038. engine.enableEffect(this._effect);
  75039. engine.setState(false);
  75040. engine.setDepthBuffer(false);
  75041. // VBOs
  75042. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75043. // Flares
  75044. for (var index = 0; index < this.lensFlares.length; index++) {
  75045. var flare = this.lensFlares[index];
  75046. engine.setAlphaMode(flare.alphaMode);
  75047. var x = centerX - (distX * flare.position);
  75048. var y = centerY - (distY * flare.position);
  75049. var cw = flare.size;
  75050. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75051. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75052. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75053. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75054. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75055. // Texture
  75056. this._effect.setTexture("textureSampler", flare.texture);
  75057. // Color
  75058. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75059. // Draw order
  75060. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75061. }
  75062. engine.setDepthBuffer(true);
  75063. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75064. return true;
  75065. };
  75066. LensFlareSystem.prototype.dispose = function () {
  75067. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75068. if (vertexBuffer) {
  75069. vertexBuffer.dispose();
  75070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75071. }
  75072. if (this._indexBuffer) {
  75073. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75074. this._indexBuffer = null;
  75075. }
  75076. while (this.lensFlares.length) {
  75077. this.lensFlares[0].dispose();
  75078. }
  75079. // Remove from scene
  75080. var index = this._scene.lensFlareSystems.indexOf(this);
  75081. this._scene.lensFlareSystems.splice(index, 1);
  75082. };
  75083. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75084. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75085. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75086. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75087. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75088. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75089. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75090. var parsedFlare = parsedLensFlareSystem.flares[index];
  75091. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75092. }
  75093. return lensFlareSystem;
  75094. };
  75095. LensFlareSystem.prototype.serialize = function () {
  75096. var serializationObject = {};
  75097. serializationObject.id = this.id;
  75098. serializationObject.name = this.name;
  75099. serializationObject.emitterId = this.getEmitter().id;
  75100. serializationObject.borderLimit = this.borderLimit;
  75101. serializationObject.flares = [];
  75102. for (var index = 0; index < this.lensFlares.length; index++) {
  75103. var flare = this.lensFlares[index];
  75104. serializationObject.flares.push({
  75105. size: flare.size,
  75106. position: flare.position,
  75107. color: flare.color.asArray(),
  75108. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75109. });
  75110. }
  75111. return serializationObject;
  75112. };
  75113. return LensFlareSystem;
  75114. }());
  75115. BABYLON.LensFlareSystem = LensFlareSystem;
  75116. })(BABYLON || (BABYLON = {}));
  75117. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75118. var BABYLON;
  75119. (function (BABYLON) {
  75120. /**
  75121. * This is a holder class for the physics joint created by the physics plugin.
  75122. * It holds a set of functions to control the underlying joint.
  75123. */
  75124. var PhysicsJoint = /** @class */ (function () {
  75125. function PhysicsJoint(type, jointData) {
  75126. this.type = type;
  75127. this.jointData = jointData;
  75128. jointData.nativeParams = jointData.nativeParams || {};
  75129. }
  75130. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75131. get: function () {
  75132. return this._physicsJoint;
  75133. },
  75134. set: function (newJoint) {
  75135. if (this._physicsJoint) {
  75136. //remove from the wolrd
  75137. }
  75138. this._physicsJoint = newJoint;
  75139. },
  75140. enumerable: true,
  75141. configurable: true
  75142. });
  75143. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75144. set: function (physicsPlugin) {
  75145. this._physicsPlugin = physicsPlugin;
  75146. },
  75147. enumerable: true,
  75148. configurable: true
  75149. });
  75150. /**
  75151. * Execute a function that is physics-plugin specific.
  75152. * @param {Function} func the function that will be executed.
  75153. * It accepts two parameters: the physics world and the physics joint.
  75154. */
  75155. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75156. func(this._physicsPlugin.world, this._physicsJoint);
  75157. };
  75158. //TODO check if the native joints are the same
  75159. //Joint Types
  75160. PhysicsJoint.DistanceJoint = 0;
  75161. PhysicsJoint.HingeJoint = 1;
  75162. PhysicsJoint.BallAndSocketJoint = 2;
  75163. PhysicsJoint.WheelJoint = 3;
  75164. PhysicsJoint.SliderJoint = 4;
  75165. //OIMO
  75166. PhysicsJoint.PrismaticJoint = 5;
  75167. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75168. PhysicsJoint.UniversalJoint = 6;
  75169. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75170. //Cannon
  75171. //Similar to a Ball-Joint. Different in params
  75172. PhysicsJoint.PointToPointJoint = 8;
  75173. //Cannon only at the moment
  75174. PhysicsJoint.SpringJoint = 9;
  75175. PhysicsJoint.LockJoint = 10;
  75176. return PhysicsJoint;
  75177. }());
  75178. BABYLON.PhysicsJoint = PhysicsJoint;
  75179. /**
  75180. * A class representing a physics distance joint.
  75181. */
  75182. var DistanceJoint = /** @class */ (function (_super) {
  75183. __extends(DistanceJoint, _super);
  75184. function DistanceJoint(jointData) {
  75185. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75186. }
  75187. /**
  75188. * Update the predefined distance.
  75189. */
  75190. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75191. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75192. };
  75193. return DistanceJoint;
  75194. }(PhysicsJoint));
  75195. BABYLON.DistanceJoint = DistanceJoint;
  75196. var MotorEnabledJoint = /** @class */ (function (_super) {
  75197. __extends(MotorEnabledJoint, _super);
  75198. function MotorEnabledJoint(type, jointData) {
  75199. return _super.call(this, type, jointData) || this;
  75200. }
  75201. /**
  75202. * Set the motor values.
  75203. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75204. * @param {number} force the force to apply
  75205. * @param {number} maxForce max force for this motor.
  75206. */
  75207. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75208. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75209. };
  75210. /**
  75211. * Set the motor's limits.
  75212. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75213. */
  75214. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75215. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75216. };
  75217. return MotorEnabledJoint;
  75218. }(PhysicsJoint));
  75219. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75220. /**
  75221. * This class represents a single hinge physics joint
  75222. */
  75223. var HingeJoint = /** @class */ (function (_super) {
  75224. __extends(HingeJoint, _super);
  75225. function HingeJoint(jointData) {
  75226. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75227. }
  75228. /**
  75229. * Set the motor values.
  75230. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75231. * @param {number} force the force to apply
  75232. * @param {number} maxForce max force for this motor.
  75233. */
  75234. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75235. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75236. };
  75237. /**
  75238. * Set the motor's limits.
  75239. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75240. */
  75241. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75242. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75243. };
  75244. return HingeJoint;
  75245. }(MotorEnabledJoint));
  75246. BABYLON.HingeJoint = HingeJoint;
  75247. /**
  75248. * This class represents a dual hinge physics joint (same as wheel joint)
  75249. */
  75250. var Hinge2Joint = /** @class */ (function (_super) {
  75251. __extends(Hinge2Joint, _super);
  75252. function Hinge2Joint(jointData) {
  75253. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75254. }
  75255. /**
  75256. * Set the motor values.
  75257. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75258. * @param {number} force the force to apply
  75259. * @param {number} maxForce max force for this motor.
  75260. * @param {motorIndex} the motor's index, 0 or 1.
  75261. */
  75262. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75263. if (motorIndex === void 0) { motorIndex = 0; }
  75264. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75265. };
  75266. /**
  75267. * Set the motor limits.
  75268. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75269. * @param {number} upperLimit the upper limit
  75270. * @param {number} lowerLimit lower limit
  75271. * @param {motorIndex} the motor's index, 0 or 1.
  75272. */
  75273. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75274. if (motorIndex === void 0) { motorIndex = 0; }
  75275. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75276. };
  75277. return Hinge2Joint;
  75278. }(MotorEnabledJoint));
  75279. BABYLON.Hinge2Joint = Hinge2Joint;
  75280. })(BABYLON || (BABYLON = {}));
  75281. //# sourceMappingURL=babylon.physicsJoint.js.map
  75282. var BABYLON;
  75283. (function (BABYLON) {
  75284. var PhysicsImpostor = /** @class */ (function () {
  75285. function PhysicsImpostor(object, type, _options, _scene) {
  75286. if (_options === void 0) { _options = { mass: 0 }; }
  75287. var _this = this;
  75288. this.object = object;
  75289. this.type = type;
  75290. this._options = _options;
  75291. this._scene = _scene;
  75292. this._bodyUpdateRequired = false;
  75293. this._onBeforePhysicsStepCallbacks = new Array();
  75294. this._onAfterPhysicsStepCallbacks = new Array();
  75295. this._onPhysicsCollideCallbacks = [];
  75296. this._deltaPosition = BABYLON.Vector3.Zero();
  75297. this._isDisposed = false;
  75298. //temp variables for parent rotation calculations
  75299. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75300. this._tmpQuat = new BABYLON.Quaternion();
  75301. this._tmpQuat2 = new BABYLON.Quaternion();
  75302. /**
  75303. * this function is executed by the physics engine.
  75304. */
  75305. this.beforeStep = function () {
  75306. if (!_this._physicsEngine) {
  75307. return;
  75308. }
  75309. _this.object.translate(_this._deltaPosition, -1);
  75310. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75311. _this.object.computeWorldMatrix(false);
  75312. if (_this.object.parent && _this.object.rotationQuaternion) {
  75313. _this.getParentsRotation();
  75314. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75315. }
  75316. else {
  75317. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75318. }
  75319. if (!_this._options.disableBidirectionalTransformation) {
  75320. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75321. }
  75322. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75323. func(_this);
  75324. });
  75325. };
  75326. /**
  75327. * this function is executed by the physics engine.
  75328. */
  75329. this.afterStep = function () {
  75330. if (!_this._physicsEngine) {
  75331. return;
  75332. }
  75333. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75334. func(_this);
  75335. });
  75336. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75337. // object has now its world rotation. needs to be converted to local.
  75338. if (_this.object.parent && _this.object.rotationQuaternion) {
  75339. _this.getParentsRotation();
  75340. _this._tmpQuat.conjugateInPlace();
  75341. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75342. }
  75343. // take the position set and make it the absolute position of this object.
  75344. _this.object.setAbsolutePosition(_this.object.position);
  75345. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75346. _this.object.translate(_this._deltaPosition, 1);
  75347. };
  75348. /**
  75349. * Legacy collision detection event support
  75350. */
  75351. this.onCollideEvent = null;
  75352. //event and body object due to cannon's event-based architecture.
  75353. this.onCollide = function (e) {
  75354. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75355. return;
  75356. }
  75357. if (!_this._physicsEngine) {
  75358. return;
  75359. }
  75360. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75361. if (otherImpostor) {
  75362. // Legacy collision detection event support
  75363. if (_this.onCollideEvent) {
  75364. _this.onCollideEvent(_this, otherImpostor);
  75365. }
  75366. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75367. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75368. }).forEach(function (obj) {
  75369. obj.callback(_this, otherImpostor);
  75370. });
  75371. }
  75372. };
  75373. //sanity check!
  75374. if (!this.object) {
  75375. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75376. return;
  75377. }
  75378. //legacy support for old syntax.
  75379. if (!this._scene && object.getScene) {
  75380. this._scene = object.getScene();
  75381. }
  75382. if (!this._scene) {
  75383. return;
  75384. }
  75385. this._physicsEngine = this._scene.getPhysicsEngine();
  75386. if (!this._physicsEngine) {
  75387. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75388. }
  75389. else {
  75390. //set the object's quaternion, if not set
  75391. if (!this.object.rotationQuaternion) {
  75392. if (this.object.rotation) {
  75393. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75394. }
  75395. else {
  75396. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75397. }
  75398. }
  75399. //default options params
  75400. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75401. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75402. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75403. this._joints = [];
  75404. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75405. if (!this.object.parent || this._options.ignoreParent) {
  75406. this._init();
  75407. }
  75408. else if (this.object.parent.physicsImpostor) {
  75409. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75410. }
  75411. }
  75412. }
  75413. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75414. get: function () {
  75415. return this._isDisposed;
  75416. },
  75417. enumerable: true,
  75418. configurable: true
  75419. });
  75420. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75421. get: function () {
  75422. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75423. },
  75424. set: function (value) {
  75425. this.setMass(value);
  75426. },
  75427. enumerable: true,
  75428. configurable: true
  75429. });
  75430. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75431. get: function () {
  75432. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75433. },
  75434. set: function (value) {
  75435. if (!this._physicsEngine) {
  75436. return;
  75437. }
  75438. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75444. get: function () {
  75445. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75446. },
  75447. set: function (value) {
  75448. if (!this._physicsEngine) {
  75449. return;
  75450. }
  75451. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75452. },
  75453. enumerable: true,
  75454. configurable: true
  75455. });
  75456. /**
  75457. * This function will completly initialize this impostor.
  75458. * It will create a new body - but only if this mesh has no parent.
  75459. * If it has, this impostor will not be used other than to define the impostor
  75460. * of the child mesh.
  75461. */
  75462. PhysicsImpostor.prototype._init = function () {
  75463. if (!this._physicsEngine) {
  75464. return;
  75465. }
  75466. this._physicsEngine.removeImpostor(this);
  75467. this.physicsBody = null;
  75468. this._parent = this._parent || this._getPhysicsParent();
  75469. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75470. this._physicsEngine.addImpostor(this);
  75471. }
  75472. };
  75473. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75474. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75475. var parentMesh = this.object.parent;
  75476. return parentMesh.physicsImpostor;
  75477. }
  75478. return null;
  75479. };
  75480. /**
  75481. * Should a new body be generated.
  75482. */
  75483. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75484. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75485. };
  75486. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75487. this.forceUpdate();
  75488. };
  75489. /**
  75490. * Force a regeneration of this or the parent's impostor's body.
  75491. * Use under cautious - This will remove all joints already implemented.
  75492. */
  75493. PhysicsImpostor.prototype.forceUpdate = function () {
  75494. this._init();
  75495. if (this.parent && !this._options.ignoreParent) {
  75496. this.parent.forceUpdate();
  75497. }
  75498. };
  75499. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75500. /*public get mesh(): AbstractMesh {
  75501. return this._mesh;
  75502. }*/
  75503. /**
  75504. * Gets the body that holds this impostor. Either its own, or its parent.
  75505. */
  75506. get: function () {
  75507. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75508. },
  75509. /**
  75510. * Set the physics body. Used mainly by the physics engine/plugin
  75511. */
  75512. set: function (physicsBody) {
  75513. if (this._physicsBody && this._physicsEngine) {
  75514. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75515. }
  75516. this._physicsBody = physicsBody;
  75517. this.resetUpdateFlags();
  75518. },
  75519. enumerable: true,
  75520. configurable: true
  75521. });
  75522. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75523. get: function () {
  75524. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75525. },
  75526. set: function (value) {
  75527. this._parent = value;
  75528. },
  75529. enumerable: true,
  75530. configurable: true
  75531. });
  75532. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75533. this._bodyUpdateRequired = false;
  75534. };
  75535. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75536. if (this.object.getBoundingInfo) {
  75537. var q = this.object.rotationQuaternion;
  75538. //reset rotation
  75539. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75540. //calculate the world matrix with no rotation
  75541. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75542. var boundingInfo = this.object.getBoundingInfo();
  75543. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75544. //bring back the rotation
  75545. this.object.rotationQuaternion = q;
  75546. //calculate the world matrix with the new rotation
  75547. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75548. return size;
  75549. }
  75550. else {
  75551. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75552. }
  75553. };
  75554. PhysicsImpostor.prototype.getObjectCenter = function () {
  75555. if (this.object.getBoundingInfo) {
  75556. var boundingInfo = this.object.getBoundingInfo();
  75557. return boundingInfo.boundingBox.centerWorld;
  75558. }
  75559. else {
  75560. return this.object.position;
  75561. }
  75562. };
  75563. /**
  75564. * Get a specific parametes from the options parameter.
  75565. */
  75566. PhysicsImpostor.prototype.getParam = function (paramName) {
  75567. return this._options[paramName];
  75568. };
  75569. /**
  75570. * Sets a specific parameter in the options given to the physics plugin
  75571. */
  75572. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75573. this._options[paramName] = value;
  75574. this._bodyUpdateRequired = true;
  75575. };
  75576. /**
  75577. * Specifically change the body's mass option. Won't recreate the physics body object
  75578. */
  75579. PhysicsImpostor.prototype.setMass = function (mass) {
  75580. if (this.getParam("mass") !== mass) {
  75581. this.setParam("mass", mass);
  75582. }
  75583. if (this._physicsEngine) {
  75584. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75585. }
  75586. };
  75587. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75588. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75589. };
  75590. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75591. if (this._physicsEngine) {
  75592. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75593. }
  75594. };
  75595. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75596. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75597. };
  75598. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75599. if (this._physicsEngine) {
  75600. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75601. }
  75602. };
  75603. /**
  75604. * Execute a function with the physics plugin native code.
  75605. * Provide a function the will have two variables - the world object and the physics body object.
  75606. */
  75607. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75608. if (this._physicsEngine) {
  75609. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75610. }
  75611. };
  75612. /**
  75613. * Register a function that will be executed before the physics world is stepping forward.
  75614. */
  75615. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75616. this._onBeforePhysicsStepCallbacks.push(func);
  75617. };
  75618. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75619. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75620. if (index > -1) {
  75621. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75622. }
  75623. else {
  75624. BABYLON.Tools.Warn("Function to remove was not found");
  75625. }
  75626. };
  75627. /**
  75628. * Register a function that will be executed after the physics step
  75629. */
  75630. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75631. this._onAfterPhysicsStepCallbacks.push(func);
  75632. };
  75633. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75634. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75635. if (index > -1) {
  75636. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75637. }
  75638. else {
  75639. BABYLON.Tools.Warn("Function to remove was not found");
  75640. }
  75641. };
  75642. /**
  75643. * register a function that will be executed when this impostor collides against a different body.
  75644. */
  75645. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75646. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75647. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75648. };
  75649. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75650. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75651. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75652. if (index > -1) {
  75653. this._onPhysicsCollideCallbacks.splice(index, 1);
  75654. }
  75655. else {
  75656. BABYLON.Tools.Warn("Function to remove was not found");
  75657. }
  75658. };
  75659. PhysicsImpostor.prototype.getParentsRotation = function () {
  75660. var parent = this.object.parent;
  75661. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75662. while (parent) {
  75663. if (parent.rotationQuaternion) {
  75664. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75665. }
  75666. else {
  75667. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75668. }
  75669. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75670. parent = parent.parent;
  75671. }
  75672. return this._tmpQuat;
  75673. };
  75674. /**
  75675. * Apply a force
  75676. */
  75677. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75678. if (this._physicsEngine) {
  75679. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75680. }
  75681. return this;
  75682. };
  75683. /**
  75684. * Apply an impulse
  75685. */
  75686. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75687. if (this._physicsEngine) {
  75688. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75689. }
  75690. return this;
  75691. };
  75692. /**
  75693. * A help function to create a joint.
  75694. */
  75695. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75696. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75697. this.addJoint(otherImpostor, joint);
  75698. return this;
  75699. };
  75700. /**
  75701. * Add a joint to this impostor with a different impostor.
  75702. */
  75703. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75704. this._joints.push({
  75705. otherImpostor: otherImpostor,
  75706. joint: joint
  75707. });
  75708. if (this._physicsEngine) {
  75709. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75710. }
  75711. return this;
  75712. };
  75713. /**
  75714. * Will keep this body still, in a sleep mode.
  75715. */
  75716. PhysicsImpostor.prototype.sleep = function () {
  75717. if (this._physicsEngine) {
  75718. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75719. }
  75720. return this;
  75721. };
  75722. /**
  75723. * Wake the body up.
  75724. */
  75725. PhysicsImpostor.prototype.wakeUp = function () {
  75726. if (this._physicsEngine) {
  75727. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75728. }
  75729. return this;
  75730. };
  75731. PhysicsImpostor.prototype.clone = function (newObject) {
  75732. if (!newObject)
  75733. return null;
  75734. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75735. };
  75736. PhysicsImpostor.prototype.dispose = function () {
  75737. var _this = this;
  75738. //no dispose if no physics engine is available.
  75739. if (!this._physicsEngine) {
  75740. return;
  75741. }
  75742. this._joints.forEach(function (j) {
  75743. if (_this._physicsEngine) {
  75744. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75745. }
  75746. });
  75747. //dispose the physics body
  75748. this._physicsEngine.removeImpostor(this);
  75749. if (this.parent) {
  75750. this.parent.forceUpdate();
  75751. }
  75752. else {
  75753. /*this._object.getChildMeshes().forEach(function(mesh) {
  75754. if (mesh.physicsImpostor) {
  75755. if (disposeChildren) {
  75756. mesh.physicsImpostor.dispose();
  75757. mesh.physicsImpostor = null;
  75758. }
  75759. }
  75760. })*/
  75761. }
  75762. this._isDisposed = true;
  75763. };
  75764. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75765. this._deltaPosition.copyFrom(position);
  75766. };
  75767. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75768. if (!this._deltaRotation) {
  75769. this._deltaRotation = new BABYLON.Quaternion();
  75770. }
  75771. this._deltaRotation.copyFrom(rotation);
  75772. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75773. };
  75774. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75775. if (this._physicsEngine) {
  75776. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75777. }
  75778. return this;
  75779. };
  75780. PhysicsImpostor.prototype.getRadius = function () {
  75781. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75782. };
  75783. /**
  75784. * Sync a bone with this impostor
  75785. * @param bone The bone to sync to the impostor.
  75786. * @param boneMesh The mesh that the bone is influencing.
  75787. * @param jointPivot The pivot of the joint / bone in local space.
  75788. * @param distToJoint Optional distance from the impostor to the joint.
  75789. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75790. */
  75791. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75792. var tempVec = PhysicsImpostor._tmpVecs[0];
  75793. var mesh = this.object;
  75794. if (mesh.rotationQuaternion) {
  75795. if (adjustRotation) {
  75796. var tempQuat = PhysicsImpostor._tmpQuat;
  75797. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75798. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75799. }
  75800. else {
  75801. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75802. }
  75803. }
  75804. tempVec.x = 0;
  75805. tempVec.y = 0;
  75806. tempVec.z = 0;
  75807. if (jointPivot) {
  75808. tempVec.x = jointPivot.x;
  75809. tempVec.y = jointPivot.y;
  75810. tempVec.z = jointPivot.z;
  75811. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75812. if (distToJoint === undefined || distToJoint === null) {
  75813. distToJoint = jointPivot.length();
  75814. }
  75815. tempVec.x *= distToJoint;
  75816. tempVec.y *= distToJoint;
  75817. tempVec.z *= distToJoint;
  75818. }
  75819. if (bone.getParent()) {
  75820. tempVec.addInPlace(mesh.getAbsolutePosition());
  75821. bone.setAbsolutePosition(tempVec, boneMesh);
  75822. }
  75823. else {
  75824. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75825. boneMesh.position.x -= tempVec.x;
  75826. boneMesh.position.y -= tempVec.y;
  75827. boneMesh.position.z -= tempVec.z;
  75828. }
  75829. };
  75830. /**
  75831. * Sync impostor to a bone
  75832. * @param bone The bone that the impostor will be synced to.
  75833. * @param boneMesh The mesh that the bone is influencing.
  75834. * @param jointPivot The pivot of the joint / bone in local space.
  75835. * @param distToJoint Optional distance from the impostor to the joint.
  75836. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75837. * @param boneAxis Optional vector3 axis the bone is aligned with
  75838. */
  75839. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75840. var mesh = this.object;
  75841. if (mesh.rotationQuaternion) {
  75842. if (adjustRotation) {
  75843. var tempQuat = PhysicsImpostor._tmpQuat;
  75844. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75845. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75846. }
  75847. else {
  75848. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75849. }
  75850. }
  75851. var pos = PhysicsImpostor._tmpVecs[0];
  75852. var boneDir = PhysicsImpostor._tmpVecs[1];
  75853. if (!boneAxis) {
  75854. boneAxis = PhysicsImpostor._tmpVecs[2];
  75855. boneAxis.x = 0;
  75856. boneAxis.y = 1;
  75857. boneAxis.z = 0;
  75858. }
  75859. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75860. bone.getAbsolutePositionToRef(boneMesh, pos);
  75861. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75862. distToJoint = jointPivot.length();
  75863. }
  75864. if (distToJoint !== undefined && distToJoint !== null) {
  75865. pos.x += boneDir.x * distToJoint;
  75866. pos.y += boneDir.y * distToJoint;
  75867. pos.z += boneDir.z * distToJoint;
  75868. }
  75869. mesh.setAbsolutePosition(pos);
  75870. };
  75871. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75872. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75873. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75874. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75875. //Impostor types
  75876. PhysicsImpostor.NoImpostor = 0;
  75877. PhysicsImpostor.SphereImpostor = 1;
  75878. PhysicsImpostor.BoxImpostor = 2;
  75879. PhysicsImpostor.PlaneImpostor = 3;
  75880. PhysicsImpostor.MeshImpostor = 4;
  75881. PhysicsImpostor.CylinderImpostor = 7;
  75882. PhysicsImpostor.ParticleImpostor = 8;
  75883. PhysicsImpostor.HeightmapImpostor = 9;
  75884. return PhysicsImpostor;
  75885. }());
  75886. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75887. })(BABYLON || (BABYLON = {}));
  75888. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75889. var BABYLON;
  75890. (function (BABYLON) {
  75891. var PhysicsEngine = /** @class */ (function () {
  75892. function PhysicsEngine(gravity, _physicsPlugin) {
  75893. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75894. this._physicsPlugin = _physicsPlugin;
  75895. //new methods and parameters
  75896. this._impostors = [];
  75897. this._joints = [];
  75898. if (!this._physicsPlugin.isSupported()) {
  75899. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75900. + "Please make sure it is included.");
  75901. }
  75902. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75903. this.setGravity(gravity);
  75904. this.setTimeStep();
  75905. }
  75906. PhysicsEngine.prototype.setGravity = function (gravity) {
  75907. this.gravity = gravity;
  75908. this._physicsPlugin.setGravity(this.gravity);
  75909. };
  75910. /**
  75911. * Set the time step of the physics engine.
  75912. * default is 1/60.
  75913. * To slow it down, enter 1/600 for example.
  75914. * To speed it up, 1/30
  75915. * @param {number} newTimeStep the new timestep to apply to this world.
  75916. */
  75917. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75918. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75919. this._physicsPlugin.setTimeStep(newTimeStep);
  75920. };
  75921. /**
  75922. * Get the time step of the physics engine.
  75923. */
  75924. PhysicsEngine.prototype.getTimeStep = function () {
  75925. return this._physicsPlugin.getTimeStep();
  75926. };
  75927. PhysicsEngine.prototype.dispose = function () {
  75928. this._impostors.forEach(function (impostor) {
  75929. impostor.dispose();
  75930. });
  75931. this._physicsPlugin.dispose();
  75932. };
  75933. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75934. return this._physicsPlugin.name;
  75935. };
  75936. /**
  75937. * Adding a new impostor for the impostor tracking.
  75938. * This will be done by the impostor itself.
  75939. * @param {PhysicsImpostor} impostor the impostor to add
  75940. */
  75941. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75942. impostor.uniqueId = this._impostors.push(impostor);
  75943. //if no parent, generate the body
  75944. if (!impostor.parent) {
  75945. this._physicsPlugin.generatePhysicsBody(impostor);
  75946. }
  75947. };
  75948. /**
  75949. * Remove an impostor from the engine.
  75950. * This impostor and its mesh will not longer be updated by the physics engine.
  75951. * @param {PhysicsImpostor} impostor the impostor to remove
  75952. */
  75953. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75954. var index = this._impostors.indexOf(impostor);
  75955. if (index > -1) {
  75956. var removed = this._impostors.splice(index, 1);
  75957. //Is it needed?
  75958. if (removed.length) {
  75959. //this will also remove it from the world.
  75960. removed[0].physicsBody = null;
  75961. }
  75962. }
  75963. };
  75964. /**
  75965. * Add a joint to the physics engine
  75966. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75967. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75968. * @param {PhysicsJoint} the joint that will connect both impostors.
  75969. */
  75970. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75971. var impostorJoint = {
  75972. mainImpostor: mainImpostor,
  75973. connectedImpostor: connectedImpostor,
  75974. joint: joint
  75975. };
  75976. joint.physicsPlugin = this._physicsPlugin;
  75977. this._joints.push(impostorJoint);
  75978. this._physicsPlugin.generateJoint(impostorJoint);
  75979. };
  75980. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75981. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75982. return (impostorJoint.connectedImpostor === connectedImpostor
  75983. && impostorJoint.joint === joint
  75984. && impostorJoint.mainImpostor === mainImpostor);
  75985. });
  75986. if (matchingJoints.length) {
  75987. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75988. //TODO remove it from the list as well
  75989. }
  75990. };
  75991. /**
  75992. * Called by the scene. no need to call it.
  75993. */
  75994. PhysicsEngine.prototype._step = function (delta) {
  75995. var _this = this;
  75996. //check if any mesh has no body / requires an update
  75997. this._impostors.forEach(function (impostor) {
  75998. if (impostor.isBodyInitRequired()) {
  75999. _this._physicsPlugin.generatePhysicsBody(impostor);
  76000. }
  76001. });
  76002. if (delta > 0.1) {
  76003. delta = 0.1;
  76004. }
  76005. else if (delta <= 0) {
  76006. delta = 1.0 / 60.0;
  76007. }
  76008. this._physicsPlugin.executeStep(delta, this._impostors);
  76009. };
  76010. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76011. return this._physicsPlugin;
  76012. };
  76013. PhysicsEngine.prototype.getImpostors = function () {
  76014. return this._impostors;
  76015. };
  76016. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76017. for (var i = 0; i < this._impostors.length; ++i) {
  76018. if (this._impostors[i].object === object) {
  76019. return this._impostors[i];
  76020. }
  76021. }
  76022. return null;
  76023. };
  76024. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76025. for (var i = 0; i < this._impostors.length; ++i) {
  76026. if (this._impostors[i].physicsBody === body) {
  76027. return this._impostors[i];
  76028. }
  76029. }
  76030. return null;
  76031. };
  76032. // Statics
  76033. PhysicsEngine.Epsilon = 0.001;
  76034. return PhysicsEngine;
  76035. }());
  76036. BABYLON.PhysicsEngine = PhysicsEngine;
  76037. })(BABYLON || (BABYLON = {}));
  76038. //# sourceMappingURL=babylon.physicsEngine.js.map
  76039. var BABYLON;
  76040. (function (BABYLON) {
  76041. var PhysicsHelper = /** @class */ (function () {
  76042. function PhysicsHelper(scene) {
  76043. this._scene = scene;
  76044. this._physicsEngine = this._scene.getPhysicsEngine();
  76045. if (!this._physicsEngine) {
  76046. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76047. }
  76048. }
  76049. /**
  76050. * @param {Vector3} origin the origin of the explosion
  76051. * @param {number} radius the explosion radius
  76052. * @param {number} strength the explosion strength
  76053. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76054. */
  76055. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76056. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76057. if (!this._physicsEngine) {
  76058. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76059. return null;
  76060. }
  76061. var impostors = this._physicsEngine.getImpostors();
  76062. if (impostors.length === 0) {
  76063. return null;
  76064. }
  76065. var event = new PhysicsRadialExplosionEvent(this._scene);
  76066. impostors.forEach(function (impostor) {
  76067. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76068. if (!impostorForceAndContactPoint) {
  76069. return;
  76070. }
  76071. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76072. });
  76073. event.dispose(false);
  76074. return event;
  76075. };
  76076. /**
  76077. * @param {Vector3} origin the origin of the explosion
  76078. * @param {number} radius the explosion radius
  76079. * @param {number} strength the explosion strength
  76080. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76081. */
  76082. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76083. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76084. if (!this._physicsEngine) {
  76085. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76086. return null;
  76087. }
  76088. var impostors = this._physicsEngine.getImpostors();
  76089. if (impostors.length === 0) {
  76090. return null;
  76091. }
  76092. var event = new PhysicsRadialExplosionEvent(this._scene);
  76093. impostors.forEach(function (impostor) {
  76094. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76095. if (!impostorForceAndContactPoint) {
  76096. return;
  76097. }
  76098. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76099. });
  76100. event.dispose(false);
  76101. return event;
  76102. };
  76103. /**
  76104. * @param {Vector3} origin the origin of the explosion
  76105. * @param {number} radius the explosion radius
  76106. * @param {number} strength the explosion strength
  76107. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76108. */
  76109. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76110. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76111. if (!this._physicsEngine) {
  76112. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76113. return null;
  76114. }
  76115. var impostors = this._physicsEngine.getImpostors();
  76116. if (impostors.length === 0) {
  76117. return null;
  76118. }
  76119. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76120. event.dispose(false);
  76121. return event;
  76122. };
  76123. /**
  76124. * @param {Vector3} origin the origin of the updraft
  76125. * @param {number} radius the radius of the updraft
  76126. * @param {number} strength the strength of the updraft
  76127. * @param {number} height the height of the updraft
  76128. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76129. */
  76130. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76131. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76132. if (!this._physicsEngine) {
  76133. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76134. return null;
  76135. }
  76136. if (this._physicsEngine.getImpostors().length === 0) {
  76137. return null;
  76138. }
  76139. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76140. event.dispose(false);
  76141. return event;
  76142. };
  76143. /**
  76144. * @param {Vector3} origin the of the vortex
  76145. * @param {number} radius the radius of the vortex
  76146. * @param {number} strength the strength of the vortex
  76147. * @param {number} height the height of the vortex
  76148. */
  76149. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76150. if (!this._physicsEngine) {
  76151. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76152. return null;
  76153. }
  76154. if (this._physicsEngine.getImpostors().length === 0) {
  76155. return null;
  76156. }
  76157. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76158. event.dispose(false);
  76159. return event;
  76160. };
  76161. return PhysicsHelper;
  76162. }());
  76163. BABYLON.PhysicsHelper = PhysicsHelper;
  76164. /***** Radial explosion *****/
  76165. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76166. function PhysicsRadialExplosionEvent(scene) {
  76167. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76168. this._rays = [];
  76169. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76170. this._scene = scene;
  76171. }
  76172. /**
  76173. * Returns the data related to the radial explosion event (sphere & rays).
  76174. * @returns {PhysicsRadialExplosionEventData}
  76175. */
  76176. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76177. this._dataFetched = true;
  76178. return {
  76179. sphere: this._sphere,
  76180. rays: this._rays,
  76181. };
  76182. };
  76183. /**
  76184. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76185. * @param impostor
  76186. * @param {Vector3} origin the origin of the explosion
  76187. * @param {number} radius the explosion radius
  76188. * @param {number} strength the explosion strength
  76189. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76190. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76191. */
  76192. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76193. if (impostor.mass === 0) {
  76194. return null;
  76195. }
  76196. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76197. return null;
  76198. }
  76199. if (impostor.object.getClassName() !== 'Mesh') {
  76200. return null;
  76201. }
  76202. var impostorObject = impostor.object;
  76203. var impostorObjectCenter = impostor.getObjectCenter();
  76204. var direction = impostorObjectCenter.subtract(origin);
  76205. var ray = new BABYLON.Ray(origin, direction, radius);
  76206. this._rays.push(ray);
  76207. var hit = ray.intersectsMesh(impostorObject);
  76208. var contactPoint = hit.pickedPoint;
  76209. if (!contactPoint) {
  76210. return null;
  76211. }
  76212. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76213. if (distanceFromOrigin > radius) {
  76214. return null;
  76215. }
  76216. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76217. ? strength
  76218. : strength * (1 - (distanceFromOrigin / radius));
  76219. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76220. return { force: force, contactPoint: contactPoint };
  76221. };
  76222. /**
  76223. * Disposes the sphere.
  76224. * @param {bolean} force
  76225. */
  76226. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76227. var _this = this;
  76228. if (force === void 0) { force = true; }
  76229. if (force) {
  76230. this._sphere.dispose();
  76231. }
  76232. else {
  76233. setTimeout(function () {
  76234. if (!_this._dataFetched) {
  76235. _this._sphere.dispose();
  76236. }
  76237. }, 0);
  76238. }
  76239. };
  76240. /*** Helpers ***/
  76241. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76242. if (!this._sphere) {
  76243. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76244. this._sphere.isVisible = false;
  76245. }
  76246. };
  76247. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76248. var impostorObject = impostor.object;
  76249. this._prepareSphere();
  76250. this._sphere.position = origin;
  76251. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76252. this._sphere._updateBoundingInfo();
  76253. this._sphere.computeWorldMatrix(true);
  76254. return this._sphere.intersectsMesh(impostorObject, true);
  76255. };
  76256. return PhysicsRadialExplosionEvent;
  76257. }());
  76258. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76259. /***** Gravitational Field *****/
  76260. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76261. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76262. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76263. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76264. this._physicsHelper = physicsHelper;
  76265. this._scene = scene;
  76266. this._origin = origin;
  76267. this._radius = radius;
  76268. this._strength = strength;
  76269. this._falloff = falloff;
  76270. this._tickCallback = this._tick.bind(this);
  76271. }
  76272. /**
  76273. * Returns the data related to the gravitational field event (sphere).
  76274. * @returns {PhysicsGravitationalFieldEventData}
  76275. */
  76276. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76277. this._dataFetched = true;
  76278. return {
  76279. sphere: this._sphere,
  76280. };
  76281. };
  76282. /**
  76283. * Enables the gravitational field.
  76284. */
  76285. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76286. this._tickCallback.call(this);
  76287. this._scene.registerBeforeRender(this._tickCallback);
  76288. };
  76289. /**
  76290. * Disables the gravitational field.
  76291. */
  76292. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76293. this._scene.unregisterBeforeRender(this._tickCallback);
  76294. };
  76295. /**
  76296. * Disposes the sphere.
  76297. * @param {bolean} force
  76298. */
  76299. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76300. var _this = this;
  76301. if (force === void 0) { force = true; }
  76302. if (force) {
  76303. this._sphere.dispose();
  76304. }
  76305. else {
  76306. setTimeout(function () {
  76307. if (!_this._dataFetched) {
  76308. _this._sphere.dispose();
  76309. }
  76310. }, 0);
  76311. }
  76312. };
  76313. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76314. // Since the params won't change, we fetch the event only once
  76315. if (this._sphere) {
  76316. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76317. }
  76318. else {
  76319. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76320. if (radialExplosionEvent) {
  76321. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76322. }
  76323. }
  76324. };
  76325. return PhysicsGravitationalFieldEvent;
  76326. }());
  76327. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76328. /***** Updraft *****/
  76329. var PhysicsUpdraftEvent = /** @class */ (function () {
  76330. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76331. this._scene = _scene;
  76332. this._origin = _origin;
  76333. this._radius = _radius;
  76334. this._strength = _strength;
  76335. this._height = _height;
  76336. this._updraftMode = _updraftMode;
  76337. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76338. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76339. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76340. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76341. this._physicsEngine = this._scene.getPhysicsEngine();
  76342. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76343. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76344. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76345. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76346. }
  76347. this._tickCallback = this._tick.bind(this);
  76348. }
  76349. /**
  76350. * Returns the data related to the updraft event (cylinder).
  76351. * @returns {PhysicsUpdraftEventData}
  76352. */
  76353. PhysicsUpdraftEvent.prototype.getData = function () {
  76354. this._dataFetched = true;
  76355. return {
  76356. cylinder: this._cylinder,
  76357. };
  76358. };
  76359. /**
  76360. * Enables the updraft.
  76361. */
  76362. PhysicsUpdraftEvent.prototype.enable = function () {
  76363. this._tickCallback.call(this);
  76364. this._scene.registerBeforeRender(this._tickCallback);
  76365. };
  76366. /**
  76367. * Disables the cortex.
  76368. */
  76369. PhysicsUpdraftEvent.prototype.disable = function () {
  76370. this._scene.unregisterBeforeRender(this._tickCallback);
  76371. };
  76372. /**
  76373. * Disposes the sphere.
  76374. * @param {bolean} force
  76375. */
  76376. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76377. var _this = this;
  76378. if (force === void 0) { force = true; }
  76379. if (force) {
  76380. this._cylinder.dispose();
  76381. }
  76382. else {
  76383. setTimeout(function () {
  76384. if (!_this._dataFetched) {
  76385. _this._cylinder.dispose();
  76386. }
  76387. }, 0);
  76388. }
  76389. };
  76390. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76391. if (impostor.mass === 0) {
  76392. return null;
  76393. }
  76394. if (!this._intersectsWithCylinder(impostor)) {
  76395. return null;
  76396. }
  76397. var impostorObjectCenter = impostor.getObjectCenter();
  76398. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76399. var direction = this._originDirection;
  76400. }
  76401. else {
  76402. var direction = impostorObjectCenter.subtract(this._originTop);
  76403. }
  76404. var multiplier = this._strength * -1;
  76405. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76406. return { force: force, contactPoint: impostorObjectCenter };
  76407. };
  76408. PhysicsUpdraftEvent.prototype._tick = function () {
  76409. var _this = this;
  76410. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76411. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76412. if (!impostorForceAndContactPoint) {
  76413. return;
  76414. }
  76415. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76416. });
  76417. };
  76418. /*** Helpers ***/
  76419. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76420. if (!this._cylinder) {
  76421. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76422. height: this._height,
  76423. diameter: this._radius * 2,
  76424. }, this._scene);
  76425. this._cylinder.isVisible = false;
  76426. }
  76427. };
  76428. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76429. var impostorObject = impostor.object;
  76430. this._prepareCylinder();
  76431. this._cylinder.position = this._cylinderPosition;
  76432. return this._cylinder.intersectsMesh(impostorObject, true);
  76433. };
  76434. return PhysicsUpdraftEvent;
  76435. }());
  76436. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76437. /***** Vortex *****/
  76438. var PhysicsVortexEvent = /** @class */ (function () {
  76439. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76440. this._scene = _scene;
  76441. this._origin = _origin;
  76442. this._radius = _radius;
  76443. this._strength = _strength;
  76444. this._height = _height;
  76445. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76446. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76447. this._updraftMultiplier = 0.02;
  76448. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76449. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76450. this._physicsEngine = this._scene.getPhysicsEngine();
  76451. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76452. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76453. this._tickCallback = this._tick.bind(this);
  76454. }
  76455. /**
  76456. * Returns the data related to the vortex event (cylinder).
  76457. * @returns {PhysicsVortexEventData}
  76458. */
  76459. PhysicsVortexEvent.prototype.getData = function () {
  76460. this._dataFetched = true;
  76461. return {
  76462. cylinder: this._cylinder,
  76463. };
  76464. };
  76465. /**
  76466. * Enables the vortex.
  76467. */
  76468. PhysicsVortexEvent.prototype.enable = function () {
  76469. this._tickCallback.call(this);
  76470. this._scene.registerBeforeRender(this._tickCallback);
  76471. };
  76472. /**
  76473. * Disables the cortex.
  76474. */
  76475. PhysicsVortexEvent.prototype.disable = function () {
  76476. this._scene.unregisterBeforeRender(this._tickCallback);
  76477. };
  76478. /**
  76479. * Disposes the sphere.
  76480. * @param {bolean} force
  76481. */
  76482. PhysicsVortexEvent.prototype.dispose = function (force) {
  76483. var _this = this;
  76484. if (force === void 0) { force = true; }
  76485. if (force) {
  76486. this._cylinder.dispose();
  76487. }
  76488. else {
  76489. setTimeout(function () {
  76490. if (!_this._dataFetched) {
  76491. _this._cylinder.dispose();
  76492. }
  76493. }, 0);
  76494. }
  76495. };
  76496. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76497. if (impostor.mass === 0) {
  76498. return null;
  76499. }
  76500. if (!this._intersectsWithCylinder(impostor)) {
  76501. return null;
  76502. }
  76503. if (impostor.object.getClassName() !== 'Mesh') {
  76504. return null;
  76505. }
  76506. var impostorObject = impostor.object;
  76507. var impostorObjectCenter = impostor.getObjectCenter();
  76508. 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)
  76509. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76510. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76511. var hit = ray.intersectsMesh(impostorObject);
  76512. var contactPoint = hit.pickedPoint;
  76513. if (!contactPoint) {
  76514. return null;
  76515. }
  76516. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76517. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76518. var directionToOrigin = contactPoint.normalize();
  76519. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76520. directionToOrigin = directionToOrigin.negate();
  76521. }
  76522. // TODO: find a more physically based solution
  76523. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76524. var forceX = directionToOrigin.x * this._strength / 8;
  76525. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76526. var forceZ = directionToOrigin.z * this._strength / 8;
  76527. }
  76528. else {
  76529. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76530. var forceY = this._originTop.y * this._updraftMultiplier;
  76531. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76532. }
  76533. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76534. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76535. return { force: force, contactPoint: impostorObjectCenter };
  76536. };
  76537. PhysicsVortexEvent.prototype._tick = function () {
  76538. var _this = this;
  76539. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76540. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76541. if (!impostorForceAndContactPoint) {
  76542. return;
  76543. }
  76544. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76545. });
  76546. };
  76547. /*** Helpers ***/
  76548. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76549. if (!this._cylinder) {
  76550. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76551. height: this._height,
  76552. diameter: this._radius * 2,
  76553. }, this._scene);
  76554. this._cylinder.isVisible = false;
  76555. }
  76556. };
  76557. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76558. var impostorObject = impostor.object;
  76559. this._prepareCylinder();
  76560. this._cylinder.position = this._cylinderPosition;
  76561. return this._cylinder.intersectsMesh(impostorObject, true);
  76562. };
  76563. return PhysicsVortexEvent;
  76564. }());
  76565. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76566. /***** Enums *****/
  76567. /**
  76568. * The strenght of the force in correspondence to the distance of the affected object
  76569. */
  76570. var PhysicsRadialImpulseFalloff;
  76571. (function (PhysicsRadialImpulseFalloff) {
  76572. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76573. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76574. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76575. /**
  76576. * The strenght of the force in correspondence to the distance of the affected object
  76577. */
  76578. var PhysicsUpdraftMode;
  76579. (function (PhysicsUpdraftMode) {
  76580. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76581. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76582. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76583. })(BABYLON || (BABYLON = {}));
  76584. //# sourceMappingURL=babylon.physicsHelper.js.map
  76585. var BABYLON;
  76586. (function (BABYLON) {
  76587. var CannonJSPlugin = /** @class */ (function () {
  76588. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76589. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76590. if (iterations === void 0) { iterations = 10; }
  76591. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76592. this.name = "CannonJSPlugin";
  76593. this._physicsMaterials = new Array();
  76594. this._fixedTimeStep = 1 / 60;
  76595. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76596. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76597. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76598. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76599. this._tmpPosition = BABYLON.Vector3.Zero();
  76600. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76601. this._tmpUnityRotation = new BABYLON.Quaternion();
  76602. if (!this.isSupported()) {
  76603. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76604. return;
  76605. }
  76606. this._extendNamespace();
  76607. this.world = new this.BJSCANNON.World();
  76608. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76609. this.world.solver.iterations = iterations;
  76610. }
  76611. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76612. this.world.gravity.copy(gravity);
  76613. };
  76614. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76615. this._fixedTimeStep = timeStep;
  76616. };
  76617. CannonJSPlugin.prototype.getTimeStep = function () {
  76618. return this._fixedTimeStep;
  76619. };
  76620. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76621. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76622. };
  76623. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76624. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76625. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76626. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76627. };
  76628. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76629. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76630. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76631. impostor.physicsBody.applyForce(impulse, worldPoint);
  76632. };
  76633. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76634. //parent-child relationship. Does this impostor has a parent impostor?
  76635. if (impostor.parent) {
  76636. if (impostor.physicsBody) {
  76637. this.removePhysicsBody(impostor);
  76638. //TODO is that needed?
  76639. impostor.forceUpdate();
  76640. }
  76641. return;
  76642. }
  76643. //should a new body be created for this impostor?
  76644. if (impostor.isBodyInitRequired()) {
  76645. var shape = this._createShape(impostor);
  76646. //unregister events, if body is being changed
  76647. var oldBody = impostor.physicsBody;
  76648. if (oldBody) {
  76649. this.removePhysicsBody(impostor);
  76650. }
  76651. //create the body and material
  76652. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76653. var bodyCreationObject = {
  76654. mass: impostor.getParam("mass"),
  76655. material: material
  76656. };
  76657. // A simple extend, in case native options were used.
  76658. var nativeOptions = impostor.getParam("nativeOptions");
  76659. for (var key in nativeOptions) {
  76660. if (nativeOptions.hasOwnProperty(key)) {
  76661. bodyCreationObject[key] = nativeOptions[key];
  76662. }
  76663. }
  76664. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76665. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76666. this.world.addEventListener("preStep", impostor.beforeStep);
  76667. this.world.addEventListener("postStep", impostor.afterStep);
  76668. impostor.physicsBody.addShape(shape);
  76669. this.world.add(impostor.physicsBody);
  76670. //try to keep the body moving in the right direction by taking old properties.
  76671. //Should be tested!
  76672. if (oldBody) {
  76673. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76674. impostor.physicsBody[param].copy(oldBody[param]);
  76675. });
  76676. }
  76677. this._processChildMeshes(impostor);
  76678. }
  76679. //now update the body's transformation
  76680. this._updatePhysicsBodyTransformation(impostor);
  76681. };
  76682. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76683. var _this = this;
  76684. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76685. var currentRotation = mainImpostor.object.rotationQuaternion;
  76686. if (meshChildren.length) {
  76687. var processMesh = function (localPosition, mesh) {
  76688. if (!currentRotation || !mesh.rotationQuaternion) {
  76689. return;
  76690. }
  76691. var childImpostor = mesh.getPhysicsImpostor();
  76692. if (childImpostor) {
  76693. var parent = childImpostor.parent;
  76694. if (parent !== mainImpostor) {
  76695. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76696. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76697. if (childImpostor.physicsBody) {
  76698. _this.removePhysicsBody(childImpostor);
  76699. childImpostor.physicsBody = null;
  76700. }
  76701. childImpostor.parent = mainImpostor;
  76702. childImpostor.resetUpdateFlags();
  76703. 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));
  76704. //Add the mass of the children.
  76705. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76706. }
  76707. }
  76708. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76709. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76710. };
  76711. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76712. }
  76713. };
  76714. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76715. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76716. this.world.removeEventListener("preStep", impostor.beforeStep);
  76717. this.world.removeEventListener("postStep", impostor.afterStep);
  76718. this.world.remove(impostor.physicsBody);
  76719. };
  76720. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76721. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76722. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76723. if (!mainBody || !connectedBody) {
  76724. return;
  76725. }
  76726. var constraint;
  76727. var jointData = impostorJoint.joint.jointData;
  76728. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76729. var constraintData = {
  76730. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76731. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76732. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76733. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76734. maxForce: jointData.nativeParams.maxForce,
  76735. collideConnected: !!jointData.collision
  76736. };
  76737. switch (impostorJoint.joint.type) {
  76738. case BABYLON.PhysicsJoint.HingeJoint:
  76739. case BABYLON.PhysicsJoint.Hinge2Joint:
  76740. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76741. break;
  76742. case BABYLON.PhysicsJoint.DistanceJoint:
  76743. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76744. break;
  76745. case BABYLON.PhysicsJoint.SpringJoint:
  76746. var springData = jointData;
  76747. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76748. restLength: springData.length,
  76749. stiffness: springData.stiffness,
  76750. damping: springData.damping,
  76751. localAnchorA: constraintData.pivotA,
  76752. localAnchorB: constraintData.pivotB
  76753. });
  76754. break;
  76755. case BABYLON.PhysicsJoint.LockJoint:
  76756. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76757. break;
  76758. case BABYLON.PhysicsJoint.PointToPointJoint:
  76759. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76760. default:
  76761. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76762. break;
  76763. }
  76764. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76765. constraint.collideConnected = !!jointData.collision;
  76766. impostorJoint.joint.physicsJoint = constraint;
  76767. //don't add spring as constraint, as it is not one.
  76768. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76769. this.world.addConstraint(constraint);
  76770. }
  76771. else {
  76772. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76773. constraint.applyForce();
  76774. });
  76775. }
  76776. };
  76777. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76778. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76779. };
  76780. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76781. var index;
  76782. var mat;
  76783. for (index = 0; index < this._physicsMaterials.length; index++) {
  76784. mat = this._physicsMaterials[index];
  76785. if (mat.friction === friction && mat.restitution === restitution) {
  76786. return mat;
  76787. }
  76788. }
  76789. var currentMat = new this.BJSCANNON.Material(name);
  76790. currentMat.friction = friction;
  76791. currentMat.restitution = restitution;
  76792. this._physicsMaterials.push(currentMat);
  76793. return currentMat;
  76794. };
  76795. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76796. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76797. };
  76798. CannonJSPlugin.prototype._createShape = function (impostor) {
  76799. var object = impostor.object;
  76800. var returnValue;
  76801. var extendSize = impostor.getObjectExtendSize();
  76802. switch (impostor.type) {
  76803. case BABYLON.PhysicsImpostor.SphereImpostor:
  76804. var radiusX = extendSize.x;
  76805. var radiusY = extendSize.y;
  76806. var radiusZ = extendSize.z;
  76807. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76808. break;
  76809. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76810. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76811. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76812. break;
  76813. case BABYLON.PhysicsImpostor.BoxImpostor:
  76814. var box = extendSize.scale(0.5);
  76815. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76816. break;
  76817. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76818. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76819. returnValue = new this.BJSCANNON.Plane();
  76820. break;
  76821. case BABYLON.PhysicsImpostor.MeshImpostor:
  76822. // should transform the vertex data to world coordinates!!
  76823. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76824. var rawFaces = object.getIndices ? object.getIndices() : [];
  76825. if (!rawVerts)
  76826. return;
  76827. // get only scale! so the object could transform correctly.
  76828. var oldPosition = object.position.clone();
  76829. var oldRotation = object.rotation && object.rotation.clone();
  76830. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76831. object.position.copyFromFloats(0, 0, 0);
  76832. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76833. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76834. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76835. var transform = object.computeWorldMatrix(true);
  76836. // convert rawVerts to object space
  76837. var temp = new Array();
  76838. var index;
  76839. for (index = 0; index < rawVerts.length; index += 3) {
  76840. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76841. }
  76842. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76843. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76844. //now set back the transformation!
  76845. object.position.copyFrom(oldPosition);
  76846. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76847. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76848. break;
  76849. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76850. var oldPosition2 = object.position.clone();
  76851. var oldRotation2 = object.rotation && object.rotation.clone();
  76852. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76853. object.position.copyFromFloats(0, 0, 0);
  76854. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76855. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76856. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76857. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76858. returnValue = this._createHeightmap(object);
  76859. object.position.copyFrom(oldPosition2);
  76860. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76861. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76862. object.computeWorldMatrix(true);
  76863. break;
  76864. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76865. returnValue = new this.BJSCANNON.Particle();
  76866. break;
  76867. }
  76868. return returnValue;
  76869. };
  76870. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76871. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76872. var transform = object.computeWorldMatrix(true);
  76873. // convert rawVerts to object space
  76874. var temp = new Array();
  76875. var index;
  76876. for (index = 0; index < pos.length; index += 3) {
  76877. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76878. }
  76879. pos = temp;
  76880. var matrix = new Array();
  76881. //For now pointDepth will not be used and will be automatically calculated.
  76882. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76883. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76884. var boundingInfo = object.getBoundingInfo();
  76885. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76886. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76887. var elementSize = dim * 2 / arraySize;
  76888. for (var i = 0; i < pos.length; i = i + 3) {
  76889. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76890. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76891. var y = -pos[i + 2] + minY;
  76892. if (!matrix[x]) {
  76893. matrix[x] = [];
  76894. }
  76895. if (!matrix[x][z]) {
  76896. matrix[x][z] = y;
  76897. }
  76898. matrix[x][z] = Math.max(y, matrix[x][z]);
  76899. }
  76900. for (var x = 0; x <= arraySize; ++x) {
  76901. if (!matrix[x]) {
  76902. var loc = 1;
  76903. while (!matrix[(x + loc) % arraySize]) {
  76904. loc++;
  76905. }
  76906. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76907. //console.log("missing x", x);
  76908. }
  76909. for (var z = 0; z <= arraySize; ++z) {
  76910. if (!matrix[x][z]) {
  76911. var loc = 1;
  76912. var newValue;
  76913. while (newValue === undefined) {
  76914. newValue = matrix[x][(z + loc++) % arraySize];
  76915. }
  76916. matrix[x][z] = newValue;
  76917. }
  76918. }
  76919. }
  76920. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76921. elementSize: elementSize
  76922. });
  76923. //For future reference, needed for body transformation
  76924. shape.minY = minY;
  76925. return shape;
  76926. };
  76927. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76928. var object = impostor.object;
  76929. //make sure it is updated...
  76930. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76931. // The delta between the mesh position and the mesh bounding box center
  76932. var bInfo = object.getBoundingInfo();
  76933. if (!bInfo)
  76934. return;
  76935. var center = impostor.getObjectCenter();
  76936. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76937. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76938. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76939. this._tmpPosition.copyFrom(center);
  76940. var quaternion = object.rotationQuaternion;
  76941. if (!quaternion) {
  76942. return;
  76943. }
  76944. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76945. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76946. //-90 DEG in X, precalculated
  76947. quaternion = quaternion.multiply(this._minus90X);
  76948. //Invert! (Precalculated, 90 deg in X)
  76949. //No need to clone. this will never change.
  76950. impostor.setDeltaRotation(this._plus90X);
  76951. }
  76952. //If it is a heightfield, if should be centered.
  76953. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76954. var mesh = object;
  76955. var boundingInfo = mesh.getBoundingInfo();
  76956. //calculate the correct body position:
  76957. var rotationQuaternion = mesh.rotationQuaternion;
  76958. mesh.rotationQuaternion = this._tmpUnityRotation;
  76959. mesh.computeWorldMatrix(true);
  76960. //get original center with no rotation
  76961. var c = center.clone();
  76962. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76963. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76964. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76965. mesh.setPreTransformMatrix(p);
  76966. mesh.computeWorldMatrix(true);
  76967. //calculate the translation
  76968. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76969. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76970. //add it inverted to the delta
  76971. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76972. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76973. //rotation is back
  76974. mesh.rotationQuaternion = rotationQuaternion;
  76975. mesh.setPreTransformMatrix(oldPivot);
  76976. mesh.computeWorldMatrix(true);
  76977. }
  76978. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76979. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76980. //this._tmpPosition.copyFrom(object.position);
  76981. }
  76982. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76983. //Now update the impostor object
  76984. impostor.physicsBody.position.copy(this._tmpPosition);
  76985. impostor.physicsBody.quaternion.copy(quaternion);
  76986. };
  76987. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76988. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76989. if (impostor.object.rotationQuaternion) {
  76990. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76991. }
  76992. };
  76993. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76994. impostor.physicsBody.position.copy(newPosition);
  76995. impostor.physicsBody.quaternion.copy(newRotation);
  76996. };
  76997. CannonJSPlugin.prototype.isSupported = function () {
  76998. return this.BJSCANNON !== undefined;
  76999. };
  77000. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77001. impostor.physicsBody.velocity.copy(velocity);
  77002. };
  77003. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77004. impostor.physicsBody.angularVelocity.copy(velocity);
  77005. };
  77006. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77007. var v = impostor.physicsBody.velocity;
  77008. if (!v) {
  77009. return null;
  77010. }
  77011. return new BABYLON.Vector3(v.x, v.y, v.z);
  77012. };
  77013. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77014. var v = impostor.physicsBody.angularVelocity;
  77015. if (!v) {
  77016. return null;
  77017. }
  77018. return new BABYLON.Vector3(v.x, v.y, v.z);
  77019. };
  77020. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77021. impostor.physicsBody.mass = mass;
  77022. impostor.physicsBody.updateMassProperties();
  77023. };
  77024. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77025. return impostor.physicsBody.mass;
  77026. };
  77027. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77028. return impostor.physicsBody.material.friction;
  77029. };
  77030. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77031. impostor.physicsBody.material.friction = friction;
  77032. };
  77033. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77034. return impostor.physicsBody.material.restitution;
  77035. };
  77036. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77037. impostor.physicsBody.material.restitution = restitution;
  77038. };
  77039. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77040. impostor.physicsBody.sleep();
  77041. };
  77042. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77043. impostor.physicsBody.wakeUp();
  77044. };
  77045. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77046. joint.physicsJoint.distance = maxDistance;
  77047. };
  77048. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77049. // if (!motorIndex) {
  77050. // joint.physicsJoint.enableMotor();
  77051. // }
  77052. // }
  77053. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77054. // if (!motorIndex) {
  77055. // joint.physicsJoint.disableMotor();
  77056. // }
  77057. // }
  77058. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77059. if (!motorIndex) {
  77060. joint.physicsJoint.enableMotor();
  77061. joint.physicsJoint.setMotorSpeed(speed);
  77062. if (maxForce) {
  77063. this.setLimit(joint, maxForce);
  77064. }
  77065. }
  77066. };
  77067. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77068. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77069. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77070. };
  77071. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77072. var body = impostor.physicsBody;
  77073. mesh.position.x = body.position.x;
  77074. mesh.position.y = body.position.y;
  77075. mesh.position.z = body.position.z;
  77076. if (mesh.rotationQuaternion) {
  77077. mesh.rotationQuaternion.x = body.quaternion.x;
  77078. mesh.rotationQuaternion.y = body.quaternion.y;
  77079. mesh.rotationQuaternion.z = body.quaternion.z;
  77080. mesh.rotationQuaternion.w = body.quaternion.w;
  77081. }
  77082. };
  77083. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77084. var shape = impostor.physicsBody.shapes[0];
  77085. return shape.boundingSphereRadius;
  77086. };
  77087. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77088. var shape = impostor.physicsBody.shapes[0];
  77089. result.x = shape.halfExtents.x * 2;
  77090. result.y = shape.halfExtents.y * 2;
  77091. result.z = shape.halfExtents.z * 2;
  77092. };
  77093. CannonJSPlugin.prototype.dispose = function () {
  77094. };
  77095. CannonJSPlugin.prototype._extendNamespace = function () {
  77096. //this will force cannon to execute at least one step when using interpolation
  77097. var step_tmp1 = new this.BJSCANNON.Vec3();
  77098. var Engine = this.BJSCANNON;
  77099. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77100. maxSubSteps = maxSubSteps || 10;
  77101. timeSinceLastCalled = timeSinceLastCalled || 0;
  77102. if (timeSinceLastCalled === 0) {
  77103. this.internalStep(dt);
  77104. this.time += dt;
  77105. }
  77106. else {
  77107. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77108. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77109. var t0 = performance.now();
  77110. for (var i = 0; i !== internalSteps; i++) {
  77111. this.internalStep(dt);
  77112. if (performance.now() - t0 > dt * 1000) {
  77113. break;
  77114. }
  77115. }
  77116. this.time += timeSinceLastCalled;
  77117. var h = this.time % dt;
  77118. var h_div_dt = h / dt;
  77119. var interpvelo = step_tmp1;
  77120. var bodies = this.bodies;
  77121. for (var j = 0; j !== bodies.length; j++) {
  77122. var b = bodies[j];
  77123. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77124. b.position.vsub(b.previousPosition, interpvelo);
  77125. interpvelo.scale(h_div_dt, interpvelo);
  77126. b.position.vadd(interpvelo, b.interpolatedPosition);
  77127. }
  77128. else {
  77129. b.interpolatedPosition.copy(b.position);
  77130. b.interpolatedQuaternion.copy(b.quaternion);
  77131. }
  77132. }
  77133. }
  77134. };
  77135. };
  77136. return CannonJSPlugin;
  77137. }());
  77138. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77139. })(BABYLON || (BABYLON = {}));
  77140. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77141. var BABYLON;
  77142. (function (BABYLON) {
  77143. var OimoJSPlugin = /** @class */ (function () {
  77144. function OimoJSPlugin(iterations) {
  77145. this.name = "OimoJSPlugin";
  77146. this._tmpImpostorsArray = [];
  77147. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77148. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77149. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77150. this.world.worldscale(1);
  77151. this.world.clear();
  77152. //making sure no stats are calculated
  77153. this.world.isNoStat = true;
  77154. }
  77155. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77156. this.world.gravity.copy(gravity);
  77157. };
  77158. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77159. this.world.timeStep = timeStep;
  77160. };
  77161. OimoJSPlugin.prototype.getTimeStep = function () {
  77162. return this.world.timeStep;
  77163. };
  77164. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77165. var _this = this;
  77166. impostors.forEach(function (impostor) {
  77167. impostor.beforeStep();
  77168. });
  77169. this.world.step();
  77170. impostors.forEach(function (impostor) {
  77171. impostor.afterStep();
  77172. //update the ordered impostors array
  77173. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77174. });
  77175. //check for collisions
  77176. var contact = this.world.contacts;
  77177. while (contact !== null) {
  77178. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77179. contact = contact.next;
  77180. continue;
  77181. }
  77182. //is this body colliding with any other? get the impostor
  77183. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77184. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77185. if (!mainImpostor || !collidingImpostor) {
  77186. contact = contact.next;
  77187. continue;
  77188. }
  77189. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77190. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77191. contact = contact.next;
  77192. }
  77193. };
  77194. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77195. var mass = impostor.physicsBody.massInfo.mass;
  77196. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77197. };
  77198. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77199. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77200. this.applyImpulse(impostor, force, contactPoint);
  77201. };
  77202. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77203. var _this = this;
  77204. //parent-child relationship. Does this impostor has a parent impostor?
  77205. if (impostor.parent) {
  77206. if (impostor.physicsBody) {
  77207. this.removePhysicsBody(impostor);
  77208. //TODO is that needed?
  77209. impostor.forceUpdate();
  77210. }
  77211. return;
  77212. }
  77213. if (impostor.isBodyInitRequired()) {
  77214. var bodyConfig = {
  77215. name: impostor.uniqueId,
  77216. //Oimo must have mass, also for static objects.
  77217. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77218. size: [],
  77219. type: [],
  77220. pos: [],
  77221. rot: [],
  77222. move: impostor.getParam("mass") !== 0,
  77223. //Supporting older versions of Oimo
  77224. world: this.world
  77225. };
  77226. var impostors = [impostor];
  77227. var addToArray = function (parent) {
  77228. if (!parent.getChildMeshes)
  77229. return;
  77230. parent.getChildMeshes().forEach(function (m) {
  77231. if (m.physicsImpostor) {
  77232. impostors.push(m.physicsImpostor);
  77233. //m.physicsImpostor._init();
  77234. }
  77235. });
  77236. };
  77237. addToArray(impostor.object);
  77238. var checkWithEpsilon_1 = function (value) {
  77239. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77240. };
  77241. impostors.forEach(function (i) {
  77242. if (!impostor.object.rotationQuaternion) {
  77243. return;
  77244. }
  77245. //get the correct bounding box
  77246. var oldQuaternion = i.object.rotationQuaternion;
  77247. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77248. x: impostor.object.rotationQuaternion.x,
  77249. y: impostor.object.rotationQuaternion.y,
  77250. z: impostor.object.rotationQuaternion.z,
  77251. s: impostor.object.rotationQuaternion.w
  77252. });
  77253. var extendSize = i.getObjectExtendSize();
  77254. if (i === impostor) {
  77255. var center = impostor.getObjectCenter();
  77256. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77257. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77258. //Can also use Array.prototype.push.apply
  77259. bodyConfig.pos.push(center.x);
  77260. bodyConfig.pos.push(center.y);
  77261. bodyConfig.pos.push(center.z);
  77262. //tmp solution
  77263. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77264. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77265. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77266. }
  77267. else {
  77268. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77269. bodyConfig.pos.push(localPosition.x);
  77270. bodyConfig.pos.push(localPosition.y);
  77271. bodyConfig.pos.push(localPosition.z);
  77272. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77273. bodyConfig.rot.push(0);
  77274. bodyConfig.rot.push(0);
  77275. bodyConfig.rot.push(0);
  77276. }
  77277. // register mesh
  77278. switch (i.type) {
  77279. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77280. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77281. case BABYLON.PhysicsImpostor.SphereImpostor:
  77282. var radiusX = extendSize.x;
  77283. var radiusY = extendSize.y;
  77284. var radiusZ = extendSize.z;
  77285. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77286. bodyConfig.type.push('sphere');
  77287. //due to the way oimo works with compounds, add 3 times
  77288. bodyConfig.size.push(size);
  77289. bodyConfig.size.push(size);
  77290. bodyConfig.size.push(size);
  77291. break;
  77292. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77293. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77294. var sizeY = checkWithEpsilon_1(extendSize.y);
  77295. bodyConfig.type.push('cylinder');
  77296. bodyConfig.size.push(sizeX);
  77297. bodyConfig.size.push(sizeY);
  77298. //due to the way oimo works with compounds, add one more value.
  77299. bodyConfig.size.push(sizeY);
  77300. break;
  77301. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77302. case BABYLON.PhysicsImpostor.BoxImpostor:
  77303. default:
  77304. var sizeX = checkWithEpsilon_1(extendSize.x);
  77305. var sizeY = checkWithEpsilon_1(extendSize.y);
  77306. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77307. bodyConfig.type.push('box');
  77308. bodyConfig.size.push(sizeX);
  77309. bodyConfig.size.push(sizeY);
  77310. bodyConfig.size.push(sizeZ);
  77311. break;
  77312. }
  77313. //actually not needed, but hey...
  77314. i.object.rotationQuaternion = oldQuaternion;
  77315. });
  77316. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77317. }
  77318. else {
  77319. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77320. }
  77321. impostor.setDeltaPosition(this._tmpPositionVector);
  77322. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77323. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77324. };
  77325. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77326. //impostor.physicsBody.dispose();
  77327. //Same as : (older oimo versions)
  77328. this.world.removeRigidBody(impostor.physicsBody);
  77329. };
  77330. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77331. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77332. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77333. if (!mainBody || !connectedBody) {
  77334. return;
  77335. }
  77336. var jointData = impostorJoint.joint.jointData;
  77337. var options = jointData.nativeParams || {};
  77338. var type;
  77339. var nativeJointData = {
  77340. body1: mainBody,
  77341. body2: connectedBody,
  77342. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77343. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77344. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77345. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77346. min: options.min,
  77347. max: options.max,
  77348. collision: options.collision || jointData.collision,
  77349. spring: options.spring,
  77350. //supporting older version of Oimo
  77351. world: this.world
  77352. };
  77353. switch (impostorJoint.joint.type) {
  77354. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77355. type = "jointBall";
  77356. break;
  77357. case BABYLON.PhysicsJoint.SpringJoint:
  77358. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77359. var springData = jointData;
  77360. nativeJointData.min = springData.length || nativeJointData.min;
  77361. //Max should also be set, just make sure it is at least min
  77362. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77363. case BABYLON.PhysicsJoint.DistanceJoint:
  77364. type = "jointDistance";
  77365. nativeJointData.max = jointData.maxDistance;
  77366. break;
  77367. case BABYLON.PhysicsJoint.PrismaticJoint:
  77368. type = "jointPrisme";
  77369. break;
  77370. case BABYLON.PhysicsJoint.SliderJoint:
  77371. type = "jointSlide";
  77372. break;
  77373. case BABYLON.PhysicsJoint.WheelJoint:
  77374. type = "jointWheel";
  77375. break;
  77376. case BABYLON.PhysicsJoint.HingeJoint:
  77377. default:
  77378. type = "jointHinge";
  77379. break;
  77380. }
  77381. nativeJointData.type = type;
  77382. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77383. };
  77384. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77385. //Bug in Oimo prevents us from disposing a joint in the playground
  77386. //joint.joint.physicsJoint.dispose();
  77387. //So we will bruteforce it!
  77388. try {
  77389. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77390. }
  77391. catch (e) {
  77392. BABYLON.Tools.Warn(e);
  77393. }
  77394. };
  77395. OimoJSPlugin.prototype.isSupported = function () {
  77396. return this.BJSOIMO !== undefined;
  77397. };
  77398. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77399. if (!impostor.physicsBody.sleeping) {
  77400. //TODO check that
  77401. if (impostor.physicsBody.shapes.next) {
  77402. var parentShape = this._getLastShape(impostor.physicsBody);
  77403. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77404. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77405. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77406. }
  77407. else {
  77408. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77409. }
  77410. if (impostor.object.rotationQuaternion) {
  77411. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77412. impostor.object.rotationQuaternion.normalize();
  77413. }
  77414. }
  77415. };
  77416. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77417. var body = impostor.physicsBody;
  77418. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77419. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77420. body.syncShapes();
  77421. body.awake();
  77422. };
  77423. OimoJSPlugin.prototype._getLastShape = function (body) {
  77424. var lastShape = body.shapes;
  77425. while (lastShape.next) {
  77426. lastShape = lastShape.next;
  77427. }
  77428. return lastShape;
  77429. };
  77430. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77431. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77432. };
  77433. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77434. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77435. };
  77436. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77437. var v = impostor.physicsBody.linearVelocity;
  77438. if (!v) {
  77439. return null;
  77440. }
  77441. return new BABYLON.Vector3(v.x, v.y, v.z);
  77442. };
  77443. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77444. var v = impostor.physicsBody.angularVelocity;
  77445. if (!v) {
  77446. return null;
  77447. }
  77448. return new BABYLON.Vector3(v.x, v.y, v.z);
  77449. };
  77450. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77451. var staticBody = mass === 0;
  77452. //this will actually set the body's density and not its mass.
  77453. //But this is how oimo treats the mass variable.
  77454. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77455. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77456. };
  77457. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77458. return impostor.physicsBody.shapes.density;
  77459. };
  77460. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77461. return impostor.physicsBody.shapes.friction;
  77462. };
  77463. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77464. impostor.physicsBody.shapes.friction = friction;
  77465. };
  77466. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77467. return impostor.physicsBody.shapes.restitution;
  77468. };
  77469. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77470. impostor.physicsBody.shapes.restitution = restitution;
  77471. };
  77472. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77473. impostor.physicsBody.sleep();
  77474. };
  77475. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77476. impostor.physicsBody.awake();
  77477. };
  77478. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77479. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77480. if (minDistance !== void 0) {
  77481. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77482. }
  77483. };
  77484. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77485. //TODO separate rotational and transational motors.
  77486. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77487. if (motor) {
  77488. motor.setMotor(speed, maxForce);
  77489. }
  77490. };
  77491. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77492. //TODO separate rotational and transational motors.
  77493. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77494. if (motor) {
  77495. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77496. }
  77497. };
  77498. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77499. var body = impostor.physicsBody;
  77500. mesh.position.x = body.position.x;
  77501. mesh.position.y = body.position.y;
  77502. mesh.position.z = body.position.z;
  77503. if (mesh.rotationQuaternion) {
  77504. mesh.rotationQuaternion.x = body.orientation.x;
  77505. mesh.rotationQuaternion.y = body.orientation.y;
  77506. mesh.rotationQuaternion.z = body.orientation.z;
  77507. mesh.rotationQuaternion.w = body.orientation.s;
  77508. }
  77509. };
  77510. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77511. return impostor.physicsBody.shapes.radius;
  77512. };
  77513. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77514. var shape = impostor.physicsBody.shapes;
  77515. result.x = shape.halfWidth * 2;
  77516. result.y = shape.halfHeight * 2;
  77517. result.z = shape.halfDepth * 2;
  77518. };
  77519. OimoJSPlugin.prototype.dispose = function () {
  77520. this.world.clear();
  77521. };
  77522. return OimoJSPlugin;
  77523. }());
  77524. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77525. })(BABYLON || (BABYLON = {}));
  77526. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77527. var BABYLON;
  77528. (function (BABYLON) {
  77529. /*
  77530. * Based on jsTGALoader - Javascript loader for TGA file
  77531. * By Vincent Thibault
  77532. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77533. */
  77534. var TGATools = /** @class */ (function () {
  77535. function TGATools() {
  77536. }
  77537. TGATools.GetTGAHeader = function (data) {
  77538. var offset = 0;
  77539. var header = {
  77540. id_length: data[offset++],
  77541. colormap_type: data[offset++],
  77542. image_type: data[offset++],
  77543. colormap_index: data[offset++] | data[offset++] << 8,
  77544. colormap_length: data[offset++] | data[offset++] << 8,
  77545. colormap_size: data[offset++],
  77546. origin: [
  77547. data[offset++] | data[offset++] << 8,
  77548. data[offset++] | data[offset++] << 8
  77549. ],
  77550. width: data[offset++] | data[offset++] << 8,
  77551. height: data[offset++] | data[offset++] << 8,
  77552. pixel_size: data[offset++],
  77553. flags: data[offset++]
  77554. };
  77555. return header;
  77556. };
  77557. TGATools.UploadContent = function (gl, data) {
  77558. // Not enough data to contain header ?
  77559. if (data.length < 19) {
  77560. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77561. return;
  77562. }
  77563. // Read Header
  77564. var offset = 18;
  77565. var header = TGATools.GetTGAHeader(data);
  77566. // Assume it's a valid Targa file.
  77567. if (header.id_length + offset > data.length) {
  77568. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77569. return;
  77570. }
  77571. // Skip not needed data
  77572. offset += header.id_length;
  77573. var use_rle = false;
  77574. var use_pal = false;
  77575. var use_grey = false;
  77576. // Get some informations.
  77577. switch (header.image_type) {
  77578. case TGATools._TYPE_RLE_INDEXED:
  77579. use_rle = true;
  77580. case TGATools._TYPE_INDEXED:
  77581. use_pal = true;
  77582. break;
  77583. case TGATools._TYPE_RLE_RGB:
  77584. use_rle = true;
  77585. case TGATools._TYPE_RGB:
  77586. // use_rgb = true;
  77587. break;
  77588. case TGATools._TYPE_RLE_GREY:
  77589. use_rle = true;
  77590. case TGATools._TYPE_GREY:
  77591. use_grey = true;
  77592. break;
  77593. }
  77594. var pixel_data;
  77595. // var numAlphaBits = header.flags & 0xf;
  77596. var pixel_size = header.pixel_size >> 3;
  77597. var pixel_total = header.width * header.height * pixel_size;
  77598. // Read palettes
  77599. var palettes;
  77600. if (use_pal) {
  77601. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77602. }
  77603. // Read LRE
  77604. if (use_rle) {
  77605. pixel_data = new Uint8Array(pixel_total);
  77606. var c, count, i;
  77607. var localOffset = 0;
  77608. var pixels = new Uint8Array(pixel_size);
  77609. while (offset < pixel_total && localOffset < pixel_total) {
  77610. c = data[offset++];
  77611. count = (c & 0x7f) + 1;
  77612. // RLE pixels
  77613. if (c & 0x80) {
  77614. // Bind pixel tmp array
  77615. for (i = 0; i < pixel_size; ++i) {
  77616. pixels[i] = data[offset++];
  77617. }
  77618. // Copy pixel array
  77619. for (i = 0; i < count; ++i) {
  77620. pixel_data.set(pixels, localOffset + i * pixel_size);
  77621. }
  77622. localOffset += pixel_size * count;
  77623. }
  77624. else {
  77625. count *= pixel_size;
  77626. for (i = 0; i < count; ++i) {
  77627. pixel_data[localOffset + i] = data[offset++];
  77628. }
  77629. localOffset += count;
  77630. }
  77631. }
  77632. }
  77633. else {
  77634. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77635. }
  77636. // Load to texture
  77637. var x_start, y_start, x_step, y_step, y_end, x_end;
  77638. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77639. default:
  77640. case TGATools._ORIGIN_UL:
  77641. x_start = 0;
  77642. x_step = 1;
  77643. x_end = header.width;
  77644. y_start = 0;
  77645. y_step = 1;
  77646. y_end = header.height;
  77647. break;
  77648. case TGATools._ORIGIN_BL:
  77649. x_start = 0;
  77650. x_step = 1;
  77651. x_end = header.width;
  77652. y_start = header.height - 1;
  77653. y_step = -1;
  77654. y_end = -1;
  77655. break;
  77656. case TGATools._ORIGIN_UR:
  77657. x_start = header.width - 1;
  77658. x_step = -1;
  77659. x_end = -1;
  77660. y_start = 0;
  77661. y_step = 1;
  77662. y_end = header.height;
  77663. break;
  77664. case TGATools._ORIGIN_BR:
  77665. x_start = header.width - 1;
  77666. x_step = -1;
  77667. x_end = -1;
  77668. y_start = header.height - 1;
  77669. y_step = -1;
  77670. y_end = -1;
  77671. break;
  77672. }
  77673. // Load the specify method
  77674. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77675. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77676. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77677. };
  77678. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77679. var image = pixel_data, colormap = palettes;
  77680. var width = header.width, height = header.height;
  77681. var color, i = 0, x, y;
  77682. var imageData = new Uint8Array(width * height * 4);
  77683. for (y = y_start; y !== y_end; y += y_step) {
  77684. for (x = x_start; x !== x_end; x += x_step, i++) {
  77685. color = image[i];
  77686. imageData[(x + width * y) * 4 + 3] = 255;
  77687. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77688. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77689. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77690. }
  77691. }
  77692. return imageData;
  77693. };
  77694. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77695. var image = pixel_data;
  77696. var width = header.width, height = header.height;
  77697. var color, i = 0, x, y;
  77698. var imageData = new Uint8Array(width * height * 4);
  77699. for (y = y_start; y !== y_end; y += y_step) {
  77700. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77701. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77702. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77703. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77704. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77705. imageData[(x + width * y) * 4 + 0] = r;
  77706. imageData[(x + width * y) * 4 + 1] = g;
  77707. imageData[(x + width * y) * 4 + 2] = b;
  77708. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77709. }
  77710. }
  77711. return imageData;
  77712. };
  77713. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77714. var image = pixel_data;
  77715. var width = header.width, height = header.height;
  77716. var i = 0, x, y;
  77717. var imageData = new Uint8Array(width * height * 4);
  77718. for (y = y_start; y !== y_end; y += y_step) {
  77719. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77720. imageData[(x + width * y) * 4 + 3] = 255;
  77721. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77722. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77723. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77724. }
  77725. }
  77726. return imageData;
  77727. };
  77728. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77729. var image = pixel_data;
  77730. var width = header.width, height = header.height;
  77731. var i = 0, x, y;
  77732. var imageData = new Uint8Array(width * height * 4);
  77733. for (y = y_start; y !== y_end; y += y_step) {
  77734. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77735. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77736. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77737. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77738. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77739. }
  77740. }
  77741. return imageData;
  77742. };
  77743. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77744. var image = pixel_data;
  77745. var width = header.width, height = header.height;
  77746. var color, i = 0, x, y;
  77747. var imageData = new Uint8Array(width * height * 4);
  77748. for (y = y_start; y !== y_end; y += y_step) {
  77749. for (x = x_start; x !== x_end; x += x_step, i++) {
  77750. color = image[i];
  77751. imageData[(x + width * y) * 4 + 0] = color;
  77752. imageData[(x + width * y) * 4 + 1] = color;
  77753. imageData[(x + width * y) * 4 + 2] = color;
  77754. imageData[(x + width * y) * 4 + 3] = 255;
  77755. }
  77756. }
  77757. return imageData;
  77758. };
  77759. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77760. var image = pixel_data;
  77761. var width = header.width, height = header.height;
  77762. var i = 0, x, y;
  77763. var imageData = new Uint8Array(width * height * 4);
  77764. for (y = y_start; y !== y_end; y += y_step) {
  77765. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77766. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77767. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77768. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77769. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77770. }
  77771. }
  77772. return imageData;
  77773. };
  77774. //private static _TYPE_NO_DATA = 0;
  77775. TGATools._TYPE_INDEXED = 1;
  77776. TGATools._TYPE_RGB = 2;
  77777. TGATools._TYPE_GREY = 3;
  77778. TGATools._TYPE_RLE_INDEXED = 9;
  77779. TGATools._TYPE_RLE_RGB = 10;
  77780. TGATools._TYPE_RLE_GREY = 11;
  77781. TGATools._ORIGIN_MASK = 0x30;
  77782. TGATools._ORIGIN_SHIFT = 0x04;
  77783. TGATools._ORIGIN_BL = 0x00;
  77784. TGATools._ORIGIN_BR = 0x01;
  77785. TGATools._ORIGIN_UL = 0x02;
  77786. TGATools._ORIGIN_UR = 0x03;
  77787. return TGATools;
  77788. }());
  77789. BABYLON.TGATools = TGATools;
  77790. })(BABYLON || (BABYLON = {}));
  77791. //# sourceMappingURL=babylon.tga.js.map
  77792. var BABYLON;
  77793. (function (BABYLON) {
  77794. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77795. // All values and structures referenced from:
  77796. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77797. var DDS_MAGIC = 0x20534444;
  77798. var
  77799. //DDSD_CAPS = 0x1,
  77800. //DDSD_HEIGHT = 0x2,
  77801. //DDSD_WIDTH = 0x4,
  77802. //DDSD_PITCH = 0x8,
  77803. //DDSD_PIXELFORMAT = 0x1000,
  77804. DDSD_MIPMAPCOUNT = 0x20000;
  77805. //DDSD_LINEARSIZE = 0x80000,
  77806. //DDSD_DEPTH = 0x800000;
  77807. // var DDSCAPS_COMPLEX = 0x8,
  77808. // DDSCAPS_MIPMAP = 0x400000,
  77809. // DDSCAPS_TEXTURE = 0x1000;
  77810. var DDSCAPS2_CUBEMAP = 0x200;
  77811. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77812. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77813. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77814. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77815. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77816. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77817. // DDSCAPS2_VOLUME = 0x200000;
  77818. var
  77819. //DDPF_ALPHAPIXELS = 0x1,
  77820. //DDPF_ALPHA = 0x2,
  77821. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77822. //DDPF_YUV = 0x200,
  77823. DDPF_LUMINANCE = 0x20000;
  77824. function FourCCToInt32(value) {
  77825. return value.charCodeAt(0) +
  77826. (value.charCodeAt(1) << 8) +
  77827. (value.charCodeAt(2) << 16) +
  77828. (value.charCodeAt(3) << 24);
  77829. }
  77830. function Int32ToFourCC(value) {
  77831. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77832. }
  77833. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77834. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77835. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77836. var FOURCC_DX10 = FourCCToInt32("DX10");
  77837. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77838. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77839. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77840. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77841. var headerLengthInt = 31; // The header length in 32 bit ints
  77842. // Offsets into the header array
  77843. var off_magic = 0;
  77844. var off_size = 1;
  77845. var off_flags = 2;
  77846. var off_height = 3;
  77847. var off_width = 4;
  77848. var off_mipmapCount = 7;
  77849. var off_pfFlags = 20;
  77850. var off_pfFourCC = 21;
  77851. var off_RGBbpp = 22;
  77852. var off_RMask = 23;
  77853. var off_GMask = 24;
  77854. var off_BMask = 25;
  77855. var off_AMask = 26;
  77856. // var off_caps1 = 27;
  77857. var off_caps2 = 28;
  77858. // var off_caps3 = 29;
  77859. // var off_caps4 = 30;
  77860. var off_dxgiFormat = 32;
  77861. ;
  77862. var DDSTools = /** @class */ (function () {
  77863. function DDSTools() {
  77864. }
  77865. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77866. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77867. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77868. var mipmapCount = 1;
  77869. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77870. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77871. }
  77872. var fourCC = header[off_pfFourCC];
  77873. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77874. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77875. switch (fourCC) {
  77876. case FOURCC_D3DFMT_R16G16B16A16F:
  77877. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77878. break;
  77879. case FOURCC_D3DFMT_R32G32B32A32F:
  77880. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77881. break;
  77882. case FOURCC_DX10:
  77883. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77884. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77885. break;
  77886. }
  77887. }
  77888. return {
  77889. width: header[off_width],
  77890. height: header[off_height],
  77891. mipmapCount: mipmapCount,
  77892. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77893. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77894. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77895. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77896. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77897. dxgiFormat: dxgiFormat,
  77898. textureType: textureType
  77899. };
  77900. };
  77901. DDSTools._ToHalfFloat = function (value) {
  77902. if (!DDSTools._FloatView) {
  77903. DDSTools._FloatView = new Float32Array(1);
  77904. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77905. }
  77906. DDSTools._FloatView[0] = value;
  77907. var x = DDSTools._Int32View[0];
  77908. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77909. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77910. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77911. /* If zero, or denormal, or exponent underflows too much for a denormal
  77912. * half, return signed zero. */
  77913. if (e < 103) {
  77914. return bits;
  77915. }
  77916. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77917. if (e > 142) {
  77918. bits |= 0x7c00;
  77919. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77920. * not Inf, so make sure we set one mantissa bit too. */
  77921. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77922. return bits;
  77923. }
  77924. /* If exponent underflows but not too much, return a denormal */
  77925. if (e < 113) {
  77926. m |= 0x0800;
  77927. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77928. * to 1, which is OK. */
  77929. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77930. return bits;
  77931. }
  77932. bits |= ((e - 112) << 10) | (m >> 1);
  77933. bits += m & 1;
  77934. return bits;
  77935. };
  77936. DDSTools._FromHalfFloat = function (value) {
  77937. var s = (value & 0x8000) >> 15;
  77938. var e = (value & 0x7C00) >> 10;
  77939. var f = value & 0x03FF;
  77940. if (e === 0) {
  77941. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77942. }
  77943. else if (e == 0x1F) {
  77944. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77945. }
  77946. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77947. };
  77948. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77949. var destArray = new Float32Array(dataLength);
  77950. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77951. var index = 0;
  77952. for (var y = 0; y < height; y++) {
  77953. for (var x = 0; x < width; x++) {
  77954. var srcPos = (x + y * width) * 4;
  77955. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77956. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77957. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77958. if (DDSTools.StoreLODInAlphaChannel) {
  77959. destArray[index + 3] = lod;
  77960. }
  77961. else {
  77962. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77963. }
  77964. index += 4;
  77965. }
  77966. }
  77967. return destArray;
  77968. };
  77969. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77970. if (DDSTools.StoreLODInAlphaChannel) {
  77971. var destArray = new Uint16Array(dataLength);
  77972. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77973. var index = 0;
  77974. for (var y = 0; y < height; y++) {
  77975. for (var x = 0; x < width; x++) {
  77976. var srcPos = (x + y * width) * 4;
  77977. destArray[index] = srcData[srcPos];
  77978. destArray[index + 1] = srcData[srcPos + 1];
  77979. destArray[index + 2] = srcData[srcPos + 2];
  77980. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77981. index += 4;
  77982. }
  77983. }
  77984. return destArray;
  77985. }
  77986. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77987. };
  77988. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77989. if (DDSTools.StoreLODInAlphaChannel) {
  77990. var destArray = new Float32Array(dataLength);
  77991. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77992. var index = 0;
  77993. for (var y = 0; y < height; y++) {
  77994. for (var x = 0; x < width; x++) {
  77995. var srcPos = (x + y * width) * 4;
  77996. destArray[index] = srcData[srcPos];
  77997. destArray[index + 1] = srcData[srcPos + 1];
  77998. destArray[index + 2] = srcData[srcPos + 2];
  77999. destArray[index + 3] = lod;
  78000. index += 4;
  78001. }
  78002. }
  78003. return destArray;
  78004. }
  78005. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78006. };
  78007. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78008. var destArray = new Uint8Array(dataLength);
  78009. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78010. var index = 0;
  78011. for (var y = 0; y < height; y++) {
  78012. for (var x = 0; x < width; x++) {
  78013. var srcPos = (x + y * width) * 4;
  78014. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78015. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78016. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78017. if (DDSTools.StoreLODInAlphaChannel) {
  78018. destArray[index + 3] = lod;
  78019. }
  78020. else {
  78021. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78022. }
  78023. index += 4;
  78024. }
  78025. }
  78026. return destArray;
  78027. };
  78028. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78029. var destArray = new Uint8Array(dataLength);
  78030. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78031. var index = 0;
  78032. for (var y = 0; y < height; y++) {
  78033. for (var x = 0; x < width; x++) {
  78034. var srcPos = (x + y * width) * 4;
  78035. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78036. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78037. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78038. if (DDSTools.StoreLODInAlphaChannel) {
  78039. destArray[index + 3] = lod;
  78040. }
  78041. else {
  78042. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78043. }
  78044. index += 4;
  78045. }
  78046. }
  78047. return destArray;
  78048. };
  78049. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78050. var byteArray = new Uint8Array(dataLength);
  78051. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78052. var index = 0;
  78053. for (var y = 0; y < height; y++) {
  78054. for (var x = 0; x < width; x++) {
  78055. var srcPos = (x + y * width) * 4;
  78056. byteArray[index] = srcData[srcPos + rOffset];
  78057. byteArray[index + 1] = srcData[srcPos + gOffset];
  78058. byteArray[index + 2] = srcData[srcPos + bOffset];
  78059. byteArray[index + 3] = srcData[srcPos + aOffset];
  78060. index += 4;
  78061. }
  78062. }
  78063. return byteArray;
  78064. };
  78065. DDSTools._ExtractLongWordOrder = function (value) {
  78066. if (value === 0 || value === 255 || value === -16777216) {
  78067. return 0;
  78068. }
  78069. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78070. };
  78071. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78072. var byteArray = new Uint8Array(dataLength);
  78073. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78074. var index = 0;
  78075. for (var y = 0; y < height; y++) {
  78076. for (var x = 0; x < width; x++) {
  78077. var srcPos = (x + y * width) * 3;
  78078. byteArray[index] = srcData[srcPos + rOffset];
  78079. byteArray[index + 1] = srcData[srcPos + gOffset];
  78080. byteArray[index + 2] = srcData[srcPos + bOffset];
  78081. index += 3;
  78082. }
  78083. }
  78084. return byteArray;
  78085. };
  78086. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78087. var byteArray = new Uint8Array(dataLength);
  78088. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78089. var index = 0;
  78090. for (var y = 0; y < height; y++) {
  78091. for (var x = 0; x < width; x++) {
  78092. var srcPos = (x + y * width);
  78093. byteArray[index] = srcData[srcPos];
  78094. index++;
  78095. }
  78096. }
  78097. return byteArray;
  78098. };
  78099. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78100. if (lodIndex === void 0) { lodIndex = -1; }
  78101. var ext = engine.getCaps().s3tc;
  78102. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78103. var fourCC, width, height, dataLength = 0, dataOffset;
  78104. var byteArray, mipmapCount, mip;
  78105. var internalFormat = 0;
  78106. var format = 0;
  78107. var blockBytes = 1;
  78108. if (header[off_magic] !== DDS_MAGIC) {
  78109. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78110. return;
  78111. }
  78112. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78113. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78114. return;
  78115. }
  78116. if (info.isCompressed && !ext) {
  78117. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78118. return;
  78119. }
  78120. var bpp = header[off_RGBbpp];
  78121. dataOffset = header[off_size] + 4;
  78122. var computeFormats = false;
  78123. if (info.isFourCC) {
  78124. fourCC = header[off_pfFourCC];
  78125. switch (fourCC) {
  78126. case FOURCC_DXT1:
  78127. blockBytes = 8;
  78128. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78129. break;
  78130. case FOURCC_DXT3:
  78131. blockBytes = 16;
  78132. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78133. break;
  78134. case FOURCC_DXT5:
  78135. blockBytes = 16;
  78136. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78137. break;
  78138. case FOURCC_D3DFMT_R16G16B16A16F:
  78139. computeFormats = true;
  78140. break;
  78141. case FOURCC_D3DFMT_R32G32B32A32F:
  78142. computeFormats = true;
  78143. break;
  78144. case FOURCC_DX10:
  78145. // There is an additionnal header so dataOffset need to be changed
  78146. dataOffset += 5 * 4; // 5 uints
  78147. var supported = false;
  78148. switch (info.dxgiFormat) {
  78149. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78150. computeFormats = true;
  78151. supported = true;
  78152. break;
  78153. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78154. info.isRGB = true;
  78155. info.isFourCC = false;
  78156. bpp = 32;
  78157. supported = true;
  78158. break;
  78159. }
  78160. if (supported) {
  78161. break;
  78162. }
  78163. default:
  78164. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78165. return;
  78166. }
  78167. }
  78168. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78169. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78170. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78171. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78172. if (computeFormats) {
  78173. format = engine._getWebGLTextureType(info.textureType);
  78174. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78175. }
  78176. mipmapCount = 1;
  78177. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78178. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78179. }
  78180. for (var face = 0; face < faces; face++) {
  78181. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78182. width = header[off_width];
  78183. height = header[off_height];
  78184. for (mip = 0; mip < mipmapCount; ++mip) {
  78185. if (lodIndex === -1 || lodIndex === mip) {
  78186. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78187. var i = (lodIndex === -1) ? mip : 0;
  78188. if (!info.isCompressed && info.isFourCC) {
  78189. dataLength = width * height * 4;
  78190. var floatArray = null;
  78191. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78192. if (bpp === 128) {
  78193. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78194. }
  78195. else if (bpp === 64) {
  78196. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78197. }
  78198. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78199. format = engine._getWebGLTextureType(info.textureType);
  78200. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78201. }
  78202. else {
  78203. if (bpp === 128) {
  78204. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78205. }
  78206. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78207. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78208. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78209. format = engine._getWebGLTextureType(info.textureType);
  78210. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78211. }
  78212. else {
  78213. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78214. }
  78215. }
  78216. if (floatArray) {
  78217. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78218. }
  78219. }
  78220. else if (info.isRGB) {
  78221. if (bpp === 24) {
  78222. dataLength = width * height * 3;
  78223. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78224. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78225. }
  78226. else {
  78227. dataLength = width * height * 4;
  78228. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78229. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78230. }
  78231. }
  78232. else if (info.isLuminance) {
  78233. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78234. var unpaddedRowSize = width;
  78235. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78236. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78237. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78238. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78239. }
  78240. else {
  78241. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78242. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78243. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78244. }
  78245. }
  78246. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78247. width *= 0.5;
  78248. height *= 0.5;
  78249. width = Math.max(1.0, width);
  78250. height = Math.max(1.0, height);
  78251. }
  78252. if (currentFace !== undefined) {
  78253. // Loading a single face
  78254. break;
  78255. }
  78256. }
  78257. };
  78258. DDSTools.StoreLODInAlphaChannel = false;
  78259. return DDSTools;
  78260. }());
  78261. BABYLON.DDSTools = DDSTools;
  78262. })(BABYLON || (BABYLON = {}));
  78263. //# sourceMappingURL=babylon.dds.js.map
  78264. var BABYLON;
  78265. (function (BABYLON) {
  78266. /**
  78267. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78268. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78269. */
  78270. var KhronosTextureContainer = /** @class */ (function () {
  78271. /**
  78272. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78273. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78274. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78275. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78276. */
  78277. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78278. this.arrayBuffer = arrayBuffer;
  78279. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78280. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78281. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78282. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78283. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78284. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78285. BABYLON.Tools.Error("texture missing KTX identifier");
  78286. return;
  78287. }
  78288. // load the reset of the header in native 32 bit int
  78289. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78290. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78291. var oppositeEndianess = header[0] === 0x01020304;
  78292. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78293. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78294. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78295. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78296. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78297. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78298. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78299. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78300. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78301. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78302. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78303. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78304. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78305. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78306. if (this.glType !== 0) {
  78307. BABYLON.Tools.Error("only compressed formats currently supported");
  78308. return;
  78309. }
  78310. else {
  78311. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78312. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78313. }
  78314. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78315. BABYLON.Tools.Error("only 2D textures currently supported");
  78316. return;
  78317. }
  78318. if (this.numberOfArrayElements !== 0) {
  78319. BABYLON.Tools.Error("texture arrays not currently supported");
  78320. return;
  78321. }
  78322. if (this.numberOfFaces !== facesExpected) {
  78323. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78324. return;
  78325. }
  78326. // we now have a completely validated file, so could use existence of loadType as success
  78327. // would need to make this more elaborate & adjust checks above to support more than one load type
  78328. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78329. }
  78330. // not as fast hardware based, but will probably never need to use
  78331. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78332. return ((val & 0xFF) << 24)
  78333. | ((val & 0xFF00) << 8)
  78334. | ((val >> 8) & 0xFF00)
  78335. | ((val >> 24) & 0xFF);
  78336. };
  78337. /**
  78338. * It is assumed that the texture has already been created & is currently bound
  78339. */
  78340. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78341. switch (this.loadType) {
  78342. case KhronosTextureContainer.COMPRESSED_2D:
  78343. this._upload2DCompressedLevels(gl, loadMipmaps);
  78344. break;
  78345. case KhronosTextureContainer.TEX_2D:
  78346. case KhronosTextureContainer.COMPRESSED_3D:
  78347. case KhronosTextureContainer.TEX_3D:
  78348. }
  78349. };
  78350. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78351. // initialize width & height for level 1
  78352. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78353. var width = this.pixelWidth;
  78354. var height = this.pixelHeight;
  78355. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78356. for (var level = 0; level < mipmapCount; level++) {
  78357. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78358. for (var face = 0; face < this.numberOfFaces; face++) {
  78359. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78360. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78361. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78362. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78363. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78364. }
  78365. width = Math.max(1.0, width * 0.5);
  78366. height = Math.max(1.0, height * 0.5);
  78367. }
  78368. };
  78369. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78370. // load types
  78371. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78372. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78373. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78374. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78375. return KhronosTextureContainer;
  78376. }());
  78377. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78378. })(BABYLON || (BABYLON = {}));
  78379. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78380. var BABYLON;
  78381. (function (BABYLON) {
  78382. var Debug = /** @class */ (function () {
  78383. function Debug() {
  78384. }
  78385. Debug.AxesViewer = /** @class */ (function () {
  78386. function AxesViewer(scene, scaleLines) {
  78387. if (scaleLines === void 0) { scaleLines = 1; }
  78388. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78389. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78390. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78391. this.scaleLines = 1;
  78392. this.scaleLines = scaleLines;
  78393. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78394. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78395. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78396. this._xmesh.renderingGroupId = 2;
  78397. this._ymesh.renderingGroupId = 2;
  78398. this._zmesh.renderingGroupId = 2;
  78399. this._xmesh.material.checkReadyOnlyOnce = true;
  78400. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78401. this._ymesh.material.checkReadyOnlyOnce = true;
  78402. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78403. this._zmesh.material.checkReadyOnlyOnce = true;
  78404. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78405. this.scene = scene;
  78406. }
  78407. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78408. var scaleLines = this.scaleLines;
  78409. if (this._xmesh) {
  78410. this._xmesh.position.copyFrom(position);
  78411. }
  78412. if (this._ymesh) {
  78413. this._ymesh.position.copyFrom(position);
  78414. }
  78415. if (this._zmesh) {
  78416. this._zmesh.position.copyFrom(position);
  78417. }
  78418. var point2 = this._xline[1];
  78419. point2.x = xaxis.x * scaleLines;
  78420. point2.y = xaxis.y * scaleLines;
  78421. point2.z = xaxis.z * scaleLines;
  78422. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78423. point2 = this._yline[1];
  78424. point2.x = yaxis.x * scaleLines;
  78425. point2.y = yaxis.y * scaleLines;
  78426. point2.z = yaxis.z * scaleLines;
  78427. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78428. point2 = this._zline[1];
  78429. point2.x = zaxis.x * scaleLines;
  78430. point2.y = zaxis.y * scaleLines;
  78431. point2.z = zaxis.z * scaleLines;
  78432. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78433. };
  78434. AxesViewer.prototype.dispose = function () {
  78435. if (this._xmesh) {
  78436. this._xmesh.dispose();
  78437. }
  78438. if (this._ymesh) {
  78439. this._ymesh.dispose();
  78440. }
  78441. if (this._zmesh) {
  78442. this._zmesh.dispose();
  78443. }
  78444. this._xmesh = null;
  78445. this._ymesh = null;
  78446. this._zmesh = null;
  78447. this.scene = null;
  78448. };
  78449. return AxesViewer;
  78450. }());
  78451. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78452. __extends(BoneAxesViewer, _super);
  78453. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78454. if (scaleLines === void 0) { scaleLines = 1; }
  78455. var _this = _super.call(this, scene, scaleLines) || this;
  78456. _this.pos = BABYLON.Vector3.Zero();
  78457. _this.xaxis = BABYLON.Vector3.Zero();
  78458. _this.yaxis = BABYLON.Vector3.Zero();
  78459. _this.zaxis = BABYLON.Vector3.Zero();
  78460. _this.mesh = mesh;
  78461. _this.bone = bone;
  78462. return _this;
  78463. }
  78464. BoneAxesViewer.prototype.update = function () {
  78465. if (!this.mesh || !this.bone) {
  78466. return;
  78467. }
  78468. var bone = this.bone;
  78469. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78470. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78471. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78472. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78473. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78474. };
  78475. BoneAxesViewer.prototype.dispose = function () {
  78476. if (this.mesh) {
  78477. this.mesh = null;
  78478. this.bone = null;
  78479. _super.prototype.dispose.call(this);
  78480. }
  78481. };
  78482. return BoneAxesViewer;
  78483. }(Debug.AxesViewer));
  78484. Debug.PhysicsViewer = /** @class */ (function () {
  78485. function PhysicsViewer(scene) {
  78486. this._impostors = [];
  78487. this._meshes = [];
  78488. this._numMeshes = 0;
  78489. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78490. var physicEngine = this._scene.getPhysicsEngine();
  78491. if (physicEngine) {
  78492. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78493. }
  78494. }
  78495. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78496. var plugin = this._physicsEnginePlugin;
  78497. for (var i = 0; i < this._numMeshes; i++) {
  78498. var impostor = this._impostors[i];
  78499. if (!impostor) {
  78500. continue;
  78501. }
  78502. if (impostor.isDisposed) {
  78503. this.hideImpostor(this._impostors[i--]);
  78504. }
  78505. else {
  78506. var mesh = this._meshes[i];
  78507. if (mesh && plugin) {
  78508. plugin.syncMeshWithImpostor(mesh, impostor);
  78509. }
  78510. }
  78511. }
  78512. };
  78513. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78514. if (!this._scene) {
  78515. return;
  78516. }
  78517. for (var i = 0; i < this._numMeshes; i++) {
  78518. if (this._impostors[i] == impostor) {
  78519. return;
  78520. }
  78521. }
  78522. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78523. if (debugMesh) {
  78524. this._impostors[this._numMeshes] = impostor;
  78525. this._meshes[this._numMeshes] = debugMesh;
  78526. if (this._numMeshes === 0) {
  78527. this._renderFunction = this._updateDebugMeshes.bind(this);
  78528. this._scene.registerBeforeRender(this._renderFunction);
  78529. }
  78530. this._numMeshes++;
  78531. }
  78532. };
  78533. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78534. if (!impostor || !this._scene) {
  78535. return;
  78536. }
  78537. var removed = false;
  78538. for (var i = 0; i < this._numMeshes; i++) {
  78539. if (this._impostors[i] == impostor) {
  78540. var mesh = this._meshes[i];
  78541. if (!mesh) {
  78542. continue;
  78543. }
  78544. this._scene.removeMesh(mesh);
  78545. mesh.dispose();
  78546. this._numMeshes--;
  78547. if (this._numMeshes > 0) {
  78548. this._meshes[i] = this._meshes[this._numMeshes];
  78549. this._impostors[i] = this._impostors[this._numMeshes];
  78550. this._meshes[this._numMeshes] = null;
  78551. this._impostors[this._numMeshes] = null;
  78552. }
  78553. else {
  78554. this._meshes[0] = null;
  78555. this._impostors[0] = null;
  78556. }
  78557. removed = true;
  78558. break;
  78559. }
  78560. }
  78561. if (removed && this._numMeshes === 0) {
  78562. this._scene.unregisterBeforeRender(this._renderFunction);
  78563. }
  78564. };
  78565. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78566. if (!this._debugMaterial) {
  78567. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78568. this._debugMaterial.wireframe = true;
  78569. }
  78570. return this._debugMaterial;
  78571. };
  78572. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78573. if (!this._debugBoxMesh) {
  78574. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78575. this._debugBoxMesh.renderingGroupId = 1;
  78576. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78577. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78578. scene.removeMesh(this._debugBoxMesh);
  78579. }
  78580. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78581. };
  78582. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78583. if (!this._debugSphereMesh) {
  78584. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78585. this._debugSphereMesh.renderingGroupId = 1;
  78586. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78587. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78588. scene.removeMesh(this._debugSphereMesh);
  78589. }
  78590. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78591. };
  78592. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78593. var mesh = null;
  78594. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78595. mesh = this._getDebugBoxMesh(scene);
  78596. impostor.getBoxSizeToRef(mesh.scaling);
  78597. }
  78598. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78599. mesh = this._getDebugSphereMesh(scene);
  78600. var radius = impostor.getRadius();
  78601. mesh.scaling.x = radius * 2;
  78602. mesh.scaling.y = radius * 2;
  78603. mesh.scaling.z = radius * 2;
  78604. }
  78605. return mesh;
  78606. };
  78607. PhysicsViewer.prototype.dispose = function () {
  78608. for (var i = 0; i < this._numMeshes; i++) {
  78609. this.hideImpostor(this._impostors[i]);
  78610. }
  78611. if (this._debugBoxMesh) {
  78612. this._debugBoxMesh.dispose();
  78613. }
  78614. if (this._debugSphereMesh) {
  78615. this._debugSphereMesh.dispose();
  78616. }
  78617. if (this._debugMaterial) {
  78618. this._debugMaterial.dispose();
  78619. }
  78620. this._impostors.length = 0;
  78621. this._scene = null;
  78622. this._physicsEnginePlugin = null;
  78623. };
  78624. return PhysicsViewer;
  78625. }());
  78626. Debug.SkeletonViewer = /** @class */ (function () {
  78627. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78628. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78629. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78630. this.skeleton = skeleton;
  78631. this.mesh = mesh;
  78632. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78633. this.renderingGroupId = renderingGroupId;
  78634. this.color = BABYLON.Color3.White();
  78635. this._debugLines = new Array();
  78636. this._isEnabled = false;
  78637. this._scene = scene;
  78638. this.update();
  78639. this._renderFunction = this.update.bind(this);
  78640. }
  78641. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78642. get: function () {
  78643. return this._isEnabled;
  78644. },
  78645. set: function (value) {
  78646. if (this._isEnabled === value) {
  78647. return;
  78648. }
  78649. this._isEnabled = value;
  78650. if (value) {
  78651. this._scene.registerBeforeRender(this._renderFunction);
  78652. }
  78653. else {
  78654. this._scene.unregisterBeforeRender(this._renderFunction);
  78655. }
  78656. },
  78657. enumerable: true,
  78658. configurable: true
  78659. });
  78660. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78661. if (x === void 0) { x = 0; }
  78662. if (y === void 0) { y = 0; }
  78663. if (z === void 0) { z = 0; }
  78664. var tmat = BABYLON.Tmp.Matrix[0];
  78665. var parentBone = bone.getParent();
  78666. tmat.copyFrom(bone.getLocalMatrix());
  78667. if (x !== 0 || y !== 0 || z !== 0) {
  78668. var tmat2 = BABYLON.Tmp.Matrix[1];
  78669. BABYLON.Matrix.IdentityToRef(tmat2);
  78670. tmat2.m[12] = x;
  78671. tmat2.m[13] = y;
  78672. tmat2.m[14] = z;
  78673. tmat2.multiplyToRef(tmat, tmat);
  78674. }
  78675. if (parentBone) {
  78676. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78677. }
  78678. tmat.multiplyToRef(meshMat, tmat);
  78679. position.x = tmat.m[12];
  78680. position.y = tmat.m[13];
  78681. position.z = tmat.m[14];
  78682. };
  78683. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78684. var len = bones.length;
  78685. var meshPos = this.mesh.position;
  78686. for (var i = 0; i < len; i++) {
  78687. var bone = bones[i];
  78688. var points = this._debugLines[i];
  78689. if (!points) {
  78690. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78691. this._debugLines[i] = points;
  78692. }
  78693. this._getBonePosition(points[0], bone, meshMat);
  78694. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78695. points[0].subtractInPlace(meshPos);
  78696. points[1].subtractInPlace(meshPos);
  78697. }
  78698. };
  78699. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78700. var len = bones.length;
  78701. var boneNum = 0;
  78702. var meshPos = this.mesh.position;
  78703. for (var i = len - 1; i >= 0; i--) {
  78704. var childBone = bones[i];
  78705. var parentBone = childBone.getParent();
  78706. if (!parentBone) {
  78707. continue;
  78708. }
  78709. var points = this._debugLines[boneNum];
  78710. if (!points) {
  78711. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78712. this._debugLines[boneNum] = points;
  78713. }
  78714. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78715. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78716. points[0].subtractInPlace(meshPos);
  78717. points[1].subtractInPlace(meshPos);
  78718. boneNum++;
  78719. }
  78720. };
  78721. SkeletonViewer.prototype.update = function () {
  78722. if (this.autoUpdateBonesMatrices) {
  78723. this.skeleton.computeAbsoluteTransforms();
  78724. }
  78725. if (this.skeleton.bones[0].length === undefined) {
  78726. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78727. }
  78728. else {
  78729. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78730. }
  78731. if (!this._debugMesh) {
  78732. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78733. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78734. }
  78735. else {
  78736. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78737. }
  78738. this._debugMesh.position.copyFrom(this.mesh.position);
  78739. this._debugMesh.color = this.color;
  78740. };
  78741. SkeletonViewer.prototype.dispose = function () {
  78742. if (this._debugMesh) {
  78743. this.isEnabled = false;
  78744. this._debugMesh.dispose();
  78745. this._debugMesh = null;
  78746. }
  78747. };
  78748. return SkeletonViewer;
  78749. }());
  78750. return Debug;
  78751. }());
  78752. BABYLON.Debug = Debug;
  78753. })(BABYLON || (BABYLON = {}));
  78754. //# sourceMappingURL=babylon.debugModules.js.map
  78755. var BABYLON;
  78756. (function (BABYLON) {
  78757. var RayHelper = /** @class */ (function () {
  78758. function RayHelper(ray) {
  78759. this.ray = ray;
  78760. }
  78761. RayHelper.CreateAndShow = function (ray, scene, color) {
  78762. var helper = new RayHelper(ray);
  78763. helper.show(scene, color);
  78764. return helper;
  78765. };
  78766. RayHelper.prototype.show = function (scene, color) {
  78767. if (!this._renderFunction && this.ray) {
  78768. var ray = this.ray;
  78769. this._renderFunction = this._render.bind(this);
  78770. this._scene = scene;
  78771. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78772. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78773. if (this._renderFunction) {
  78774. this._scene.registerBeforeRender(this._renderFunction);
  78775. }
  78776. }
  78777. if (color && this._renderLine) {
  78778. this._renderLine.color.copyFrom(color);
  78779. }
  78780. };
  78781. RayHelper.prototype.hide = function () {
  78782. if (this._renderFunction && this._scene) {
  78783. this._scene.unregisterBeforeRender(this._renderFunction);
  78784. this._scene = null;
  78785. this._renderFunction = null;
  78786. if (this._renderLine) {
  78787. this._renderLine.dispose();
  78788. this._renderLine = null;
  78789. }
  78790. this._renderPoints = [];
  78791. }
  78792. };
  78793. RayHelper.prototype._render = function () {
  78794. var ray = this.ray;
  78795. if (!ray) {
  78796. return;
  78797. }
  78798. var point = this._renderPoints[1];
  78799. var len = Math.min(ray.length, 1000000);
  78800. point.copyFrom(ray.direction);
  78801. point.scaleInPlace(len);
  78802. point.addInPlace(ray.origin);
  78803. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78804. };
  78805. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78806. this._attachedToMesh = mesh;
  78807. var ray = this.ray;
  78808. if (!ray) {
  78809. return;
  78810. }
  78811. if (!ray.direction) {
  78812. ray.direction = BABYLON.Vector3.Zero();
  78813. }
  78814. if (!ray.origin) {
  78815. ray.origin = BABYLON.Vector3.Zero();
  78816. }
  78817. if (length) {
  78818. ray.length = length;
  78819. }
  78820. if (!meshSpaceOrigin) {
  78821. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78822. }
  78823. if (!meshSpaceDirection) {
  78824. // -1 so that this will work with Mesh.lookAt
  78825. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78826. }
  78827. if (!this._meshSpaceDirection) {
  78828. this._meshSpaceDirection = meshSpaceDirection.clone();
  78829. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78830. }
  78831. else {
  78832. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78833. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78834. }
  78835. if (!this._updateToMeshFunction) {
  78836. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78837. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78838. }
  78839. this._updateToMesh();
  78840. };
  78841. RayHelper.prototype.detachFromMesh = function () {
  78842. if (this._attachedToMesh) {
  78843. if (this._updateToMeshFunction) {
  78844. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78845. }
  78846. this._attachedToMesh = null;
  78847. this._updateToMeshFunction = null;
  78848. }
  78849. };
  78850. RayHelper.prototype._updateToMesh = function () {
  78851. var ray = this.ray;
  78852. if (!this._attachedToMesh || !ray) {
  78853. return;
  78854. }
  78855. if (this._attachedToMesh._isDisposed) {
  78856. this.detachFromMesh();
  78857. return;
  78858. }
  78859. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78860. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78861. };
  78862. RayHelper.prototype.dispose = function () {
  78863. this.hide();
  78864. this.detachFromMesh();
  78865. this.ray = null;
  78866. };
  78867. return RayHelper;
  78868. }());
  78869. BABYLON.RayHelper = RayHelper;
  78870. })(BABYLON || (BABYLON = {}));
  78871. //# sourceMappingURL=babylon.rayHelper.js.map
  78872. var BABYLON;
  78873. (function (BABYLON) {
  78874. // load the inspector using require, if not present in the global namespace.
  78875. var DebugLayer = /** @class */ (function () {
  78876. function DebugLayer(scene) {
  78877. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78878. this._scene = scene;
  78879. // load inspector using require, if it doesn't exist on the global namespace.
  78880. }
  78881. /** Creates the inspector window. */
  78882. DebugLayer.prototype._createInspector = function (config) {
  78883. if (config === void 0) { config = {}; }
  78884. var popup = config.popup || false;
  78885. var initialTab = config.initialTab || 0;
  78886. var parentElement = config.parentElement || null;
  78887. if (!this._inspector) {
  78888. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78889. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78890. } // else nothing to do,; instance is already existing
  78891. };
  78892. DebugLayer.prototype.isVisible = function () {
  78893. if (!this._inspector) {
  78894. return false;
  78895. }
  78896. return true;
  78897. };
  78898. DebugLayer.prototype.hide = function () {
  78899. if (this._inspector) {
  78900. try {
  78901. this._inspector.dispose();
  78902. }
  78903. catch (e) {
  78904. // If the inspector has been removed directly from the inspector tool
  78905. }
  78906. this._inspector = null;
  78907. }
  78908. };
  78909. DebugLayer.prototype.show = function (config) {
  78910. if (config === void 0) { config = {}; }
  78911. if (typeof this.BJSINSPECTOR == 'undefined') {
  78912. // Load inspector and add it to the DOM
  78913. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78914. }
  78915. else {
  78916. // Otherwise creates the inspector
  78917. this._createInspector(config);
  78918. }
  78919. };
  78920. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78921. return DebugLayer;
  78922. }());
  78923. BABYLON.DebugLayer = DebugLayer;
  78924. })(BABYLON || (BABYLON = {}));
  78925. //# sourceMappingURL=babylon.debugLayer.js.map
  78926. var BABYLON;
  78927. (function (BABYLON) {
  78928. var BoundingBoxRenderer = /** @class */ (function () {
  78929. function BoundingBoxRenderer(scene) {
  78930. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78931. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78932. this.showBackLines = true;
  78933. this.renderList = new BABYLON.SmartArray(32);
  78934. this._vertexBuffers = {};
  78935. this._scene = scene;
  78936. }
  78937. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78938. if (this._colorShader) {
  78939. return;
  78940. }
  78941. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78942. attributes: [BABYLON.VertexBuffer.PositionKind],
  78943. uniforms: ["world", "viewProjection", "color"]
  78944. });
  78945. var engine = this._scene.getEngine();
  78946. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78947. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78948. this._createIndexBuffer();
  78949. };
  78950. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78951. var engine = this._scene.getEngine();
  78952. 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]);
  78953. };
  78954. BoundingBoxRenderer.prototype._rebuild = function () {
  78955. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78956. if (vb) {
  78957. vb._rebuild();
  78958. }
  78959. this._createIndexBuffer();
  78960. };
  78961. BoundingBoxRenderer.prototype.reset = function () {
  78962. this.renderList.reset();
  78963. };
  78964. BoundingBoxRenderer.prototype.render = function () {
  78965. if (this.renderList.length === 0) {
  78966. return;
  78967. }
  78968. this._prepareRessources();
  78969. if (!this._colorShader.isReady()) {
  78970. return;
  78971. }
  78972. var engine = this._scene.getEngine();
  78973. engine.setDepthWrite(false);
  78974. this._colorShader._preBind();
  78975. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78976. var boundingBox = this.renderList.data[boundingBoxIndex];
  78977. var min = boundingBox.minimum;
  78978. var max = boundingBox.maximum;
  78979. var diff = max.subtract(min);
  78980. var median = min.add(diff.scale(0.5));
  78981. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78982. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78983. .multiply(boundingBox.getWorldMatrix());
  78984. // VBOs
  78985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78986. if (this.showBackLines) {
  78987. // Back
  78988. engine.setDepthFunctionToGreaterOrEqual();
  78989. this._scene.resetCachedMaterial();
  78990. this._colorShader.setColor4("color", this.backColor.toColor4());
  78991. this._colorShader.bind(worldMatrix);
  78992. // Draw order
  78993. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78994. }
  78995. // Front
  78996. engine.setDepthFunctionToLess();
  78997. this._scene.resetCachedMaterial();
  78998. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78999. this._colorShader.bind(worldMatrix);
  79000. // Draw order
  79001. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79002. }
  79003. this._colorShader.unbind();
  79004. engine.setDepthFunctionToLessOrEqual();
  79005. engine.setDepthWrite(true);
  79006. };
  79007. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79008. this._prepareRessources();
  79009. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79010. return;
  79011. }
  79012. var engine = this._scene.getEngine();
  79013. engine.setDepthWrite(false);
  79014. engine.setColorWrite(false);
  79015. this._colorShader._preBind();
  79016. var boundingBox = mesh._boundingInfo.boundingBox;
  79017. var min = boundingBox.minimum;
  79018. var max = boundingBox.maximum;
  79019. var diff = max.subtract(min);
  79020. var median = min.add(diff.scale(0.5));
  79021. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79022. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79023. .multiply(boundingBox.getWorldMatrix());
  79024. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79025. engine.setDepthFunctionToLess();
  79026. this._scene.resetCachedMaterial();
  79027. this._colorShader.bind(worldMatrix);
  79028. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79029. this._colorShader.unbind();
  79030. engine.setDepthFunctionToLessOrEqual();
  79031. engine.setDepthWrite(true);
  79032. engine.setColorWrite(true);
  79033. };
  79034. BoundingBoxRenderer.prototype.dispose = function () {
  79035. if (!this._colorShader) {
  79036. return;
  79037. }
  79038. this.renderList.dispose();
  79039. this._colorShader.dispose();
  79040. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79041. if (buffer) {
  79042. buffer.dispose();
  79043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79044. }
  79045. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79046. };
  79047. return BoundingBoxRenderer;
  79048. }());
  79049. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79050. })(BABYLON || (BABYLON = {}));
  79051. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79052. var BABYLON;
  79053. (function (BABYLON) {
  79054. var MorphTarget = /** @class */ (function () {
  79055. function MorphTarget(name, influence) {
  79056. if (influence === void 0) { influence = 0; }
  79057. this.name = name;
  79058. this.animations = new Array();
  79059. this._positions = null;
  79060. this._normals = null;
  79061. this._tangents = null;
  79062. this.onInfluenceChanged = new BABYLON.Observable();
  79063. this.influence = influence;
  79064. }
  79065. Object.defineProperty(MorphTarget.prototype, "influence", {
  79066. get: function () {
  79067. return this._influence;
  79068. },
  79069. set: function (influence) {
  79070. if (this._influence === influence) {
  79071. return;
  79072. }
  79073. var previous = this._influence;
  79074. this._influence = influence;
  79075. if (this.onInfluenceChanged.hasObservers) {
  79076. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79077. }
  79078. },
  79079. enumerable: true,
  79080. configurable: true
  79081. });
  79082. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79083. get: function () {
  79084. return !!this._positions;
  79085. },
  79086. enumerable: true,
  79087. configurable: true
  79088. });
  79089. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79090. get: function () {
  79091. return !!this._normals;
  79092. },
  79093. enumerable: true,
  79094. configurable: true
  79095. });
  79096. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79097. get: function () {
  79098. return !!this._tangents;
  79099. },
  79100. enumerable: true,
  79101. configurable: true
  79102. });
  79103. MorphTarget.prototype.setPositions = function (data) {
  79104. this._positions = data;
  79105. };
  79106. MorphTarget.prototype.getPositions = function () {
  79107. return this._positions;
  79108. };
  79109. MorphTarget.prototype.setNormals = function (data) {
  79110. this._normals = data;
  79111. };
  79112. MorphTarget.prototype.getNormals = function () {
  79113. return this._normals;
  79114. };
  79115. MorphTarget.prototype.setTangents = function (data) {
  79116. this._tangents = data;
  79117. };
  79118. MorphTarget.prototype.getTangents = function () {
  79119. return this._tangents;
  79120. };
  79121. /**
  79122. * Serializes the current target into a Serialization object.
  79123. * Returns the serialized object.
  79124. */
  79125. MorphTarget.prototype.serialize = function () {
  79126. var serializationObject = {};
  79127. serializationObject.name = this.name;
  79128. serializationObject.influence = this.influence;
  79129. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79130. if (this.hasNormals) {
  79131. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79132. }
  79133. if (this.hasTangents) {
  79134. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79135. }
  79136. // Animations
  79137. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79138. return serializationObject;
  79139. };
  79140. // Statics
  79141. MorphTarget.Parse = function (serializationObject) {
  79142. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79143. result.setPositions(serializationObject.positions);
  79144. if (serializationObject.normals) {
  79145. result.setNormals(serializationObject.normals);
  79146. }
  79147. if (serializationObject.tangents) {
  79148. result.setTangents(serializationObject.tangents);
  79149. }
  79150. // Animations
  79151. if (serializationObject.animations) {
  79152. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79153. var parsedAnimation = serializationObject.animations[animationIndex];
  79154. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79155. }
  79156. }
  79157. return result;
  79158. };
  79159. MorphTarget.FromMesh = function (mesh, name, influence) {
  79160. if (!name) {
  79161. name = mesh.name;
  79162. }
  79163. var result = new MorphTarget(name, influence);
  79164. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79165. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79166. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79167. }
  79168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79169. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79170. }
  79171. return result;
  79172. };
  79173. return MorphTarget;
  79174. }());
  79175. BABYLON.MorphTarget = MorphTarget;
  79176. })(BABYLON || (BABYLON = {}));
  79177. //# sourceMappingURL=babylon.morphTarget.js.map
  79178. var BABYLON;
  79179. (function (BABYLON) {
  79180. var MorphTargetManager = /** @class */ (function () {
  79181. function MorphTargetManager(scene) {
  79182. if (scene === void 0) { scene = null; }
  79183. this._targets = new Array();
  79184. this._targetObservable = new Array();
  79185. this._activeTargets = new BABYLON.SmartArray(16);
  79186. this._supportsNormals = false;
  79187. this._supportsTangents = false;
  79188. this._vertexCount = 0;
  79189. this._uniqueId = 0;
  79190. this._tempInfluences = new Array();
  79191. if (!scene) {
  79192. scene = BABYLON.Engine.LastCreatedScene;
  79193. }
  79194. this._scene = scene;
  79195. if (this._scene) {
  79196. this._scene.morphTargetManagers.push(this);
  79197. this._uniqueId = this._scene.getUniqueId();
  79198. }
  79199. }
  79200. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79201. get: function () {
  79202. return this._uniqueId;
  79203. },
  79204. enumerable: true,
  79205. configurable: true
  79206. });
  79207. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79208. get: function () {
  79209. return this._vertexCount;
  79210. },
  79211. enumerable: true,
  79212. configurable: true
  79213. });
  79214. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79215. get: function () {
  79216. return this._supportsNormals;
  79217. },
  79218. enumerable: true,
  79219. configurable: true
  79220. });
  79221. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79222. get: function () {
  79223. return this._supportsTangents;
  79224. },
  79225. enumerable: true,
  79226. configurable: true
  79227. });
  79228. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79229. get: function () {
  79230. return this._targets.length;
  79231. },
  79232. enumerable: true,
  79233. configurable: true
  79234. });
  79235. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79236. get: function () {
  79237. return this._activeTargets.length;
  79238. },
  79239. enumerable: true,
  79240. configurable: true
  79241. });
  79242. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79243. get: function () {
  79244. return this._influences;
  79245. },
  79246. enumerable: true,
  79247. configurable: true
  79248. });
  79249. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79250. return this._activeTargets.data[index];
  79251. };
  79252. MorphTargetManager.prototype.getTarget = function (index) {
  79253. return this._targets[index];
  79254. };
  79255. MorphTargetManager.prototype.addTarget = function (target) {
  79256. var _this = this;
  79257. this._targets.push(target);
  79258. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79259. _this._syncActiveTargets(needUpdate);
  79260. }));
  79261. this._syncActiveTargets(true);
  79262. };
  79263. MorphTargetManager.prototype.removeTarget = function (target) {
  79264. var index = this._targets.indexOf(target);
  79265. if (index >= 0) {
  79266. this._targets.splice(index, 1);
  79267. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79268. this._syncActiveTargets(true);
  79269. }
  79270. };
  79271. /**
  79272. * Serializes the current manager into a Serialization object.
  79273. * Returns the serialized object.
  79274. */
  79275. MorphTargetManager.prototype.serialize = function () {
  79276. var serializationObject = {};
  79277. serializationObject.id = this.uniqueId;
  79278. serializationObject.targets = [];
  79279. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79280. var target = _a[_i];
  79281. serializationObject.targets.push(target.serialize());
  79282. }
  79283. return serializationObject;
  79284. };
  79285. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79286. var influenceCount = 0;
  79287. this._activeTargets.reset();
  79288. this._supportsNormals = true;
  79289. this._supportsTangents = true;
  79290. this._vertexCount = 0;
  79291. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79292. var target = _a[_i];
  79293. this._activeTargets.push(target);
  79294. this._tempInfluences[influenceCount++] = target.influence;
  79295. var positions = target.getPositions();
  79296. if (positions) {
  79297. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79298. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79299. var vertexCount = positions.length / 3;
  79300. if (this._vertexCount === 0) {
  79301. this._vertexCount = vertexCount;
  79302. }
  79303. else if (this._vertexCount !== vertexCount) {
  79304. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79305. return;
  79306. }
  79307. }
  79308. }
  79309. if (!this._influences || this._influences.length !== influenceCount) {
  79310. this._influences = new Float32Array(influenceCount);
  79311. }
  79312. for (var index = 0; index < influenceCount; index++) {
  79313. this._influences[index] = this._tempInfluences[index];
  79314. }
  79315. if (needUpdate && this._scene) {
  79316. // Flag meshes as dirty to resync with the active targets
  79317. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79318. var mesh = _c[_b];
  79319. if (mesh.morphTargetManager === this) {
  79320. mesh._syncGeometryWithMorphTargetManager();
  79321. }
  79322. }
  79323. }
  79324. };
  79325. // Statics
  79326. MorphTargetManager.Parse = function (serializationObject, scene) {
  79327. var result = new MorphTargetManager(scene);
  79328. result._uniqueId = serializationObject.id;
  79329. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79330. var targetData = _a[_i];
  79331. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79332. }
  79333. return result;
  79334. };
  79335. return MorphTargetManager;
  79336. }());
  79337. BABYLON.MorphTargetManager = MorphTargetManager;
  79338. })(BABYLON || (BABYLON = {}));
  79339. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79340. var BABYLON;
  79341. (function (BABYLON) {
  79342. var Octree = /** @class */ (function () {
  79343. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79344. if (maxDepth === void 0) { maxDepth = 2; }
  79345. this.maxDepth = maxDepth;
  79346. this.dynamicContent = new Array();
  79347. this._maxBlockCapacity = maxBlockCapacity || 64;
  79348. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79349. this._creationFunc = creationFunc;
  79350. }
  79351. // Methods
  79352. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79353. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79354. };
  79355. Octree.prototype.addMesh = function (entry) {
  79356. for (var index = 0; index < this.blocks.length; index++) {
  79357. var block = this.blocks[index];
  79358. block.addEntry(entry);
  79359. }
  79360. };
  79361. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79362. this._selectionContent.reset();
  79363. for (var index = 0; index < this.blocks.length; index++) {
  79364. var block = this.blocks[index];
  79365. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79366. }
  79367. if (allowDuplicate) {
  79368. this._selectionContent.concat(this.dynamicContent);
  79369. }
  79370. else {
  79371. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79372. }
  79373. return this._selectionContent;
  79374. };
  79375. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79376. this._selectionContent.reset();
  79377. for (var index = 0; index < this.blocks.length; index++) {
  79378. var block = this.blocks[index];
  79379. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79380. }
  79381. if (allowDuplicate) {
  79382. this._selectionContent.concat(this.dynamicContent);
  79383. }
  79384. else {
  79385. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79386. }
  79387. return this._selectionContent;
  79388. };
  79389. Octree.prototype.intersectsRay = function (ray) {
  79390. this._selectionContent.reset();
  79391. for (var index = 0; index < this.blocks.length; index++) {
  79392. var block = this.blocks[index];
  79393. block.intersectsRay(ray, this._selectionContent);
  79394. }
  79395. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79396. return this._selectionContent;
  79397. };
  79398. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79399. target.blocks = new Array();
  79400. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79401. // Segmenting space
  79402. for (var x = 0; x < 2; x++) {
  79403. for (var y = 0; y < 2; y++) {
  79404. for (var z = 0; z < 2; z++) {
  79405. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79406. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79407. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79408. block.addEntries(entries);
  79409. target.blocks.push(block);
  79410. }
  79411. }
  79412. }
  79413. };
  79414. Octree.CreationFuncForMeshes = function (entry, block) {
  79415. var boundingInfo = entry.getBoundingInfo();
  79416. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79417. block.entries.push(entry);
  79418. }
  79419. };
  79420. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79421. var boundingInfo = entry.getBoundingInfo();
  79422. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79423. block.entries.push(entry);
  79424. }
  79425. };
  79426. return Octree;
  79427. }());
  79428. BABYLON.Octree = Octree;
  79429. })(BABYLON || (BABYLON = {}));
  79430. //# sourceMappingURL=babylon.octree.js.map
  79431. var BABYLON;
  79432. (function (BABYLON) {
  79433. var OctreeBlock = /** @class */ (function () {
  79434. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79435. this.entries = new Array();
  79436. this._boundingVectors = new Array();
  79437. this._capacity = capacity;
  79438. this._depth = depth;
  79439. this._maxDepth = maxDepth;
  79440. this._creationFunc = creationFunc;
  79441. this._minPoint = minPoint;
  79442. this._maxPoint = maxPoint;
  79443. this._boundingVectors.push(minPoint.clone());
  79444. this._boundingVectors.push(maxPoint.clone());
  79445. this._boundingVectors.push(minPoint.clone());
  79446. this._boundingVectors[2].x = maxPoint.x;
  79447. this._boundingVectors.push(minPoint.clone());
  79448. this._boundingVectors[3].y = maxPoint.y;
  79449. this._boundingVectors.push(minPoint.clone());
  79450. this._boundingVectors[4].z = maxPoint.z;
  79451. this._boundingVectors.push(maxPoint.clone());
  79452. this._boundingVectors[5].z = minPoint.z;
  79453. this._boundingVectors.push(maxPoint.clone());
  79454. this._boundingVectors[6].x = minPoint.x;
  79455. this._boundingVectors.push(maxPoint.clone());
  79456. this._boundingVectors[7].y = minPoint.y;
  79457. }
  79458. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79459. // Property
  79460. get: function () {
  79461. return this._capacity;
  79462. },
  79463. enumerable: true,
  79464. configurable: true
  79465. });
  79466. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79467. get: function () {
  79468. return this._minPoint;
  79469. },
  79470. enumerable: true,
  79471. configurable: true
  79472. });
  79473. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79474. get: function () {
  79475. return this._maxPoint;
  79476. },
  79477. enumerable: true,
  79478. configurable: true
  79479. });
  79480. // Methods
  79481. OctreeBlock.prototype.addEntry = function (entry) {
  79482. if (this.blocks) {
  79483. for (var index = 0; index < this.blocks.length; index++) {
  79484. var block = this.blocks[index];
  79485. block.addEntry(entry);
  79486. }
  79487. return;
  79488. }
  79489. this._creationFunc(entry, this);
  79490. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79491. this.createInnerBlocks();
  79492. }
  79493. };
  79494. OctreeBlock.prototype.addEntries = function (entries) {
  79495. for (var index = 0; index < entries.length; index++) {
  79496. var mesh = entries[index];
  79497. this.addEntry(mesh);
  79498. }
  79499. };
  79500. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79501. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79502. if (this.blocks) {
  79503. for (var index = 0; index < this.blocks.length; index++) {
  79504. var block = this.blocks[index];
  79505. block.select(frustumPlanes, selection, allowDuplicate);
  79506. }
  79507. return;
  79508. }
  79509. if (allowDuplicate) {
  79510. selection.concat(this.entries);
  79511. }
  79512. else {
  79513. selection.concatWithNoDuplicate(this.entries);
  79514. }
  79515. }
  79516. };
  79517. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79518. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79519. if (this.blocks) {
  79520. for (var index = 0; index < this.blocks.length; index++) {
  79521. var block = this.blocks[index];
  79522. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79523. }
  79524. return;
  79525. }
  79526. if (allowDuplicate) {
  79527. selection.concat(this.entries);
  79528. }
  79529. else {
  79530. selection.concatWithNoDuplicate(this.entries);
  79531. }
  79532. }
  79533. };
  79534. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79535. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79536. if (this.blocks) {
  79537. for (var index = 0; index < this.blocks.length; index++) {
  79538. var block = this.blocks[index];
  79539. block.intersectsRay(ray, selection);
  79540. }
  79541. return;
  79542. }
  79543. selection.concatWithNoDuplicate(this.entries);
  79544. }
  79545. };
  79546. OctreeBlock.prototype.createInnerBlocks = function () {
  79547. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79548. };
  79549. return OctreeBlock;
  79550. }());
  79551. BABYLON.OctreeBlock = OctreeBlock;
  79552. })(BABYLON || (BABYLON = {}));
  79553. //# sourceMappingURL=babylon.octreeBlock.js.map
  79554. var BABYLON;
  79555. (function (BABYLON) {
  79556. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79557. __extends(VRDistortionCorrectionPostProcess, _super);
  79558. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79559. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79560. 'LensCenter',
  79561. 'Scale',
  79562. 'ScaleIn',
  79563. 'HmdWarpParam'
  79564. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79565. _this._isRightEye = isRightEye;
  79566. _this._distortionFactors = vrMetrics.distortionK;
  79567. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79568. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79569. _this.adaptScaleToCurrentViewport = true;
  79570. _this.onSizeChangedObservable.add(function () {
  79571. _this.aspectRatio = _this.width * .5 / _this.height;
  79572. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79573. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79574. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79575. });
  79576. _this.onApplyObservable.add(function (effect) {
  79577. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79578. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79579. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79580. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79581. });
  79582. return _this;
  79583. }
  79584. return VRDistortionCorrectionPostProcess;
  79585. }(BABYLON.PostProcess));
  79586. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79587. })(BABYLON || (BABYLON = {}));
  79588. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79589. var BABYLON;
  79590. (function (BABYLON) {
  79591. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79592. __extends(AnaglyphPostProcess, _super);
  79593. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79594. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79595. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79596. _this.onApplyObservable.add(function (effect) {
  79597. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79598. });
  79599. return _this;
  79600. }
  79601. return AnaglyphPostProcess;
  79602. }(BABYLON.PostProcess));
  79603. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79604. })(BABYLON || (BABYLON = {}));
  79605. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79606. var BABYLON;
  79607. (function (BABYLON) {
  79608. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79609. __extends(StereoscopicInterlacePostProcess, _super);
  79610. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79611. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79612. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79613. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79614. _this.onSizeChangedObservable.add(function () {
  79615. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79616. });
  79617. _this.onApplyObservable.add(function (effect) {
  79618. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79619. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79620. });
  79621. return _this;
  79622. }
  79623. return StereoscopicInterlacePostProcess;
  79624. }(BABYLON.PostProcess));
  79625. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79626. })(BABYLON || (BABYLON = {}));
  79627. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79628. var BABYLON;
  79629. (function (BABYLON) {
  79630. /**
  79631. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79632. * Screen rotation is taken into account.
  79633. */
  79634. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79635. function FreeCameraDeviceOrientationInput() {
  79636. var _this = this;
  79637. this._screenOrientationAngle = 0;
  79638. this._screenQuaternion = new BABYLON.Quaternion();
  79639. this._alpha = 0;
  79640. this._beta = 0;
  79641. this._gamma = 0;
  79642. this._orientationChanged = function () {
  79643. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79644. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79645. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79646. };
  79647. this._deviceOrientation = function (evt) {
  79648. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79649. _this._beta = evt.beta !== null ? evt.beta : 0;
  79650. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79651. };
  79652. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79653. this._orientationChanged();
  79654. }
  79655. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79656. get: function () {
  79657. return this._camera;
  79658. },
  79659. set: function (camera) {
  79660. this._camera = camera;
  79661. if (this._camera != null && !this._camera.rotationQuaternion) {
  79662. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79663. }
  79664. },
  79665. enumerable: true,
  79666. configurable: true
  79667. });
  79668. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79669. window.addEventListener("orientationchange", this._orientationChanged);
  79670. window.addEventListener("deviceorientation", this._deviceOrientation);
  79671. //In certain cases, the attach control is called AFTER orientation was changed,
  79672. //So this is needed.
  79673. this._orientationChanged();
  79674. };
  79675. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79676. window.removeEventListener("orientationchange", this._orientationChanged);
  79677. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79678. };
  79679. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79680. //if no device orientation provided, don't update the rotation.
  79681. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79682. if (!this._alpha)
  79683. return;
  79684. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79685. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79686. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79687. //Mirror on XY Plane
  79688. this._camera.rotationQuaternion.z *= -1;
  79689. this._camera.rotationQuaternion.w *= -1;
  79690. };
  79691. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79692. return "FreeCameraDeviceOrientationInput";
  79693. };
  79694. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79695. return "deviceOrientation";
  79696. };
  79697. return FreeCameraDeviceOrientationInput;
  79698. }());
  79699. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79700. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79701. })(BABYLON || (BABYLON = {}));
  79702. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79703. var BABYLON;
  79704. (function (BABYLON) {
  79705. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79706. function ArcRotateCameraVRDeviceOrientationInput() {
  79707. this.alphaCorrection = 1;
  79708. this.betaCorrection = 1;
  79709. this.gammaCorrection = 1;
  79710. this._alpha = 0;
  79711. this._gamma = 0;
  79712. this._dirty = false;
  79713. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79714. }
  79715. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79716. this.camera.attachControl(element, noPreventDefault);
  79717. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79718. };
  79719. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79720. if (evt.alpha !== null) {
  79721. this._alpha = +evt.alpha | 0;
  79722. }
  79723. if (evt.gamma !== null) {
  79724. this._gamma = +evt.gamma | 0;
  79725. }
  79726. this._dirty = true;
  79727. };
  79728. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79729. if (this._dirty) {
  79730. this._dirty = false;
  79731. if (this._gamma < 0) {
  79732. this._gamma = 180 + this._gamma;
  79733. }
  79734. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79735. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79736. }
  79737. };
  79738. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79739. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79740. };
  79741. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79742. return "ArcRotateCameraVRDeviceOrientationInput";
  79743. };
  79744. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79745. return "VRDeviceOrientation";
  79746. };
  79747. return ArcRotateCameraVRDeviceOrientationInput;
  79748. }());
  79749. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79750. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79751. })(BABYLON || (BABYLON = {}));
  79752. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79753. var BABYLON;
  79754. (function (BABYLON) {
  79755. var VRCameraMetrics = /** @class */ (function () {
  79756. function VRCameraMetrics() {
  79757. this.compensateDistortion = true;
  79758. }
  79759. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79760. get: function () {
  79761. return this.hResolution / (2 * this.vResolution);
  79762. },
  79763. enumerable: true,
  79764. configurable: true
  79765. });
  79766. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79767. get: function () {
  79768. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79769. },
  79770. enumerable: true,
  79771. configurable: true
  79772. });
  79773. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79774. get: function () {
  79775. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79776. var h = (4 * meters) / this.hScreenSize;
  79777. return BABYLON.Matrix.Translation(h, 0, 0);
  79778. },
  79779. enumerable: true,
  79780. configurable: true
  79781. });
  79782. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79783. get: function () {
  79784. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79785. var h = (4 * meters) / this.hScreenSize;
  79786. return BABYLON.Matrix.Translation(-h, 0, 0);
  79787. },
  79788. enumerable: true,
  79789. configurable: true
  79790. });
  79791. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79792. get: function () {
  79793. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79794. },
  79795. enumerable: true,
  79796. configurable: true
  79797. });
  79798. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79799. get: function () {
  79800. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79801. },
  79802. enumerable: true,
  79803. configurable: true
  79804. });
  79805. VRCameraMetrics.GetDefault = function () {
  79806. var result = new VRCameraMetrics();
  79807. result.hResolution = 1280;
  79808. result.vResolution = 800;
  79809. result.hScreenSize = 0.149759993;
  79810. result.vScreenSize = 0.0935999975;
  79811. result.vScreenCenter = 0.0467999987;
  79812. result.eyeToScreenDistance = 0.0410000011;
  79813. result.lensSeparationDistance = 0.0635000020;
  79814. result.interpupillaryDistance = 0.0640000030;
  79815. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79816. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79817. result.postProcessScaleFactor = 1.714605507808412;
  79818. result.lensCenterOffset = 0.151976421;
  79819. return result;
  79820. };
  79821. return VRCameraMetrics;
  79822. }());
  79823. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79824. })(BABYLON || (BABYLON = {}));
  79825. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79826. var BABYLON;
  79827. (function (BABYLON) {
  79828. /**
  79829. * This represents a WebVR camera.
  79830. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79831. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79832. */
  79833. var WebVRFreeCamera = /** @class */ (function (_super) {
  79834. __extends(WebVRFreeCamera, _super);
  79835. /**
  79836. * Instantiates a WebVRFreeCamera.
  79837. * @param name The name of the WebVRFreeCamera
  79838. * @param position The starting anchor position for the camera
  79839. * @param scene The scene the camera belongs to
  79840. * @param webVROptions a set of customizable options for the webVRCamera
  79841. */
  79842. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79843. if (webVROptions === void 0) { webVROptions = {}; }
  79844. var _this = _super.call(this, name, position, scene) || this;
  79845. _this.webVROptions = webVROptions;
  79846. /**
  79847. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79848. */
  79849. _this._vrDevice = null;
  79850. /**
  79851. * The rawPose of the vrDevice.
  79852. */
  79853. _this.rawPose = null;
  79854. _this._specsVersion = "1.1";
  79855. _this._attached = false;
  79856. _this._descendants = [];
  79857. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79858. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79859. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79860. _this._standingMatrix = null;
  79861. /**
  79862. * Represents device position in babylon space.
  79863. */
  79864. _this.devicePosition = BABYLON.Vector3.Zero();
  79865. /**
  79866. * Represents device rotation in babylon space.
  79867. */
  79868. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79869. /**
  79870. * The scale of the device to be used when translating from device space to babylon space.
  79871. */
  79872. _this.deviceScaleFactor = 1;
  79873. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79874. _this._worldToDevice = BABYLON.Matrix.Identity();
  79875. /**
  79876. * References to the webVR controllers for the vrDevice.
  79877. */
  79878. _this.controllers = [];
  79879. /**
  79880. * Emits an event when a controller is attached.
  79881. */
  79882. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79883. /**
  79884. * Emits an event when a controller's mesh has been loaded;
  79885. */
  79886. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79887. /**
  79888. * If the rig cameras be used as parent instead of this camera.
  79889. */
  79890. _this.rigParenting = true;
  79891. _this._defaultHeight = undefined;
  79892. _this._workingVector = BABYLON.Vector3.Zero();
  79893. _this._oneVector = BABYLON.Vector3.One();
  79894. _this._workingMatrix = BABYLON.Matrix.Identity();
  79895. _this._cache.position = BABYLON.Vector3.Zero();
  79896. if (webVROptions.defaultHeight) {
  79897. _this._defaultHeight = webVROptions.defaultHeight;
  79898. _this.position.y = _this._defaultHeight;
  79899. }
  79900. _this.minZ = 0.1;
  79901. //legacy support - the compensation boolean was removed.
  79902. if (arguments.length === 5) {
  79903. _this.webVROptions = arguments[4];
  79904. }
  79905. // default webVR options
  79906. if (_this.webVROptions.trackPosition == undefined) {
  79907. _this.webVROptions.trackPosition = true;
  79908. }
  79909. if (_this.webVROptions.controllerMeshes == undefined) {
  79910. _this.webVROptions.controllerMeshes = true;
  79911. }
  79912. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79913. _this.webVROptions.defaultLightingOnControllers = true;
  79914. }
  79915. _this.rotationQuaternion = new BABYLON.Quaternion();
  79916. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79917. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79918. }
  79919. //enable VR
  79920. var engine = _this.getEngine();
  79921. _this._onVREnabled = function (success) { if (success) {
  79922. _this.initControllers();
  79923. } };
  79924. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79925. engine.initWebVR().add(function (event) {
  79926. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79927. return;
  79928. }
  79929. _this._vrDevice = event.vrDisplay;
  79930. //reset the rig parameters.
  79931. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79932. if (_this._attached) {
  79933. _this.getEngine().enableVR();
  79934. }
  79935. });
  79936. if (typeof (VRFrameData) !== "undefined")
  79937. _this._frameData = new VRFrameData();
  79938. /**
  79939. * The idea behind the following lines:
  79940. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79941. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79942. * the second will not show it correctly.
  79943. *
  79944. * To solve this - each object that has the camera as parent will be added to a protected array.
  79945. * When the rig camera renders, it will take this array and set all of those to be its children.
  79946. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79947. * Amazing!
  79948. */
  79949. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79950. if (camera.parent === _this && _this.rigParenting) {
  79951. _this._descendants = _this.getDescendants(true, function (n) {
  79952. // don't take the cameras or the controllers!
  79953. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79954. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79955. return !isController && !isRigCamera;
  79956. });
  79957. _this._descendants.forEach(function (node) {
  79958. node.parent = camera;
  79959. });
  79960. }
  79961. });
  79962. scene.onAfterCameraRenderObservable.add(function (camera) {
  79963. if (camera.parent === _this && _this.rigParenting) {
  79964. _this._descendants.forEach(function (node) {
  79965. node.parent = _this;
  79966. });
  79967. }
  79968. });
  79969. return _this;
  79970. }
  79971. /**
  79972. * Gets the device distance from the ground in meters.
  79973. * @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.
  79974. */
  79975. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79976. if (this._standingMatrix) {
  79977. // Add standing matrix offset to get real offset from ground in room
  79978. this._standingMatrix.getTranslationToRef(this._workingVector);
  79979. return this._deviceRoomPosition.y + this._workingVector.y;
  79980. }
  79981. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79982. return this._defaultHeight || 0;
  79983. };
  79984. /**
  79985. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79986. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79987. */
  79988. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79989. var _this = this;
  79990. if (callback === void 0) { callback = function (bool) { }; }
  79991. // Use standing matrix if available
  79992. this.getEngine().initWebVRAsync().then(function (result) {
  79993. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79994. callback(false);
  79995. }
  79996. else {
  79997. _this._standingMatrix = new BABYLON.Matrix();
  79998. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79999. if (!_this.getScene().useRightHandedSystem) {
  80000. [2, 6, 8, 9, 14].forEach(function (num) {
  80001. if (_this._standingMatrix) {
  80002. _this._standingMatrix.m[num] *= -1;
  80003. }
  80004. });
  80005. }
  80006. callback(true);
  80007. }
  80008. });
  80009. };
  80010. /**
  80011. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80012. * @returns A promise with a boolean set to if the standing matrix is supported.
  80013. */
  80014. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80015. var _this = this;
  80016. return new Promise(function (res, rej) {
  80017. _this.useStandingMatrix(function (supported) {
  80018. res(supported);
  80019. });
  80020. });
  80021. };
  80022. /**
  80023. * Disposes the camera
  80024. */
  80025. WebVRFreeCamera.prototype.dispose = function () {
  80026. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80027. _super.prototype.dispose.call(this);
  80028. };
  80029. /**
  80030. * Gets a vrController by name.
  80031. * @param name The name of the controller to retreive
  80032. * @returns the controller matching the name specified or null if not found
  80033. */
  80034. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80035. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80036. var gp = _a[_i];
  80037. if (gp.hand === name) {
  80038. return gp;
  80039. }
  80040. }
  80041. return null;
  80042. };
  80043. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80044. /**
  80045. * The controller corrisponding to the users left hand.
  80046. */
  80047. get: function () {
  80048. if (!this._leftController) {
  80049. this._leftController = this.getControllerByName("left");
  80050. }
  80051. return this._leftController;
  80052. },
  80053. enumerable: true,
  80054. configurable: true
  80055. });
  80056. ;
  80057. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80058. /**
  80059. * The controller corrisponding to the users right hand.
  80060. */
  80061. get: function () {
  80062. if (!this._rightController) {
  80063. this._rightController = this.getControllerByName("right");
  80064. }
  80065. return this._rightController;
  80066. },
  80067. enumerable: true,
  80068. configurable: true
  80069. });
  80070. ;
  80071. /**
  80072. * Casts a ray forward from the vrCamera's gaze.
  80073. * @param length Length of the ray (default: 100)
  80074. * @returns the ray corrisponding to the gaze
  80075. */
  80076. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80077. if (length === void 0) { length = 100; }
  80078. if (this.leftCamera) {
  80079. // Use left eye to avoid computation to compute center on every call
  80080. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80081. }
  80082. else {
  80083. return _super.prototype.getForwardRay.call(this, length);
  80084. }
  80085. };
  80086. /**
  80087. * Updates the camera based on device's frame data
  80088. */
  80089. WebVRFreeCamera.prototype._checkInputs = function () {
  80090. if (this._vrDevice && this._vrDevice.isPresenting) {
  80091. this._vrDevice.getFrameData(this._frameData);
  80092. this.updateFromDevice(this._frameData.pose);
  80093. }
  80094. _super.prototype._checkInputs.call(this);
  80095. };
  80096. /**
  80097. * Updates the poseControlled values based on the input device pose.
  80098. * @param poseData Pose coming from the device
  80099. */
  80100. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80101. if (poseData && poseData.orientation) {
  80102. this.rawPose = poseData;
  80103. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80104. if (this.getScene().useRightHandedSystem) {
  80105. this._deviceRoomRotationQuaternion.z *= -1;
  80106. this._deviceRoomRotationQuaternion.w *= -1;
  80107. }
  80108. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80109. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80110. if (this.getScene().useRightHandedSystem) {
  80111. this._deviceRoomPosition.z *= -1;
  80112. }
  80113. }
  80114. }
  80115. };
  80116. /**
  80117. * WebVR's attach control will start broadcasting frames to the device.
  80118. * Note that in certain browsers (chrome for example) this function must be called
  80119. * within a user-interaction callback. Example:
  80120. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80121. *
  80122. * @param element html element to attach the vrDevice to
  80123. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80124. */
  80125. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80126. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80127. this._attached = true;
  80128. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80129. if (this._vrDevice) {
  80130. this.getEngine().enableVR();
  80131. }
  80132. };
  80133. /**
  80134. * Detaches the camera from the html element and disables VR
  80135. *
  80136. * @param element html element to detach from
  80137. */
  80138. WebVRFreeCamera.prototype.detachControl = function (element) {
  80139. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80140. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80141. _super.prototype.detachControl.call(this, element);
  80142. this._attached = false;
  80143. this.getEngine().disableVR();
  80144. };
  80145. /**
  80146. * @returns the name of this class
  80147. */
  80148. WebVRFreeCamera.prototype.getClassName = function () {
  80149. return "WebVRFreeCamera";
  80150. };
  80151. /**
  80152. * Calls resetPose on the vrDisplay
  80153. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80154. */
  80155. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80156. //uses the vrDisplay's "resetPose()".
  80157. //pitch and roll won't be affected.
  80158. this._vrDevice.resetPose();
  80159. };
  80160. /**
  80161. * Updates the rig cameras (left and right eye)
  80162. */
  80163. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80164. var camLeft = this._rigCameras[0];
  80165. var camRight = this._rigCameras[1];
  80166. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80167. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80168. camLeft.position.copyFrom(this._deviceRoomPosition);
  80169. camRight.position.copyFrom(this._deviceRoomPosition);
  80170. };
  80171. /**
  80172. * Updates the cached values of the camera
  80173. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80174. */
  80175. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80176. var _this = this;
  80177. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80178. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80179. if (!this.updateCacheCalled) {
  80180. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80181. this.updateCacheCalled = true;
  80182. this.update();
  80183. }
  80184. // Set working vector to the device position in room space rotated by the new rotation
  80185. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80186. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80187. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80188. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80189. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80190. // Add translation from anchor position
  80191. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80192. this._workingVector.addInPlace(this.position);
  80193. this._workingVector.subtractInPlace(this._cache.position);
  80194. this._deviceToWorld.setTranslation(this._workingVector);
  80195. // Set an inverted matrix to be used when updating the camera
  80196. this._deviceToWorld.invertToRef(this._worldToDevice);
  80197. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80198. this.controllers.forEach(function (controller) {
  80199. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80200. controller.update();
  80201. });
  80202. }
  80203. if (!ignoreParentClass) {
  80204. _super.prototype._updateCache.call(this);
  80205. }
  80206. this.updateCacheCalled = false;
  80207. };
  80208. /**
  80209. * Updates the current device position and rotation in the babylon world
  80210. */
  80211. WebVRFreeCamera.prototype.update = function () {
  80212. // Get current device position in babylon world
  80213. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80214. // Get current device rotation in babylon world
  80215. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80216. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80217. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80218. _super.prototype.update.call(this);
  80219. };
  80220. /**
  80221. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80222. * @returns an identity matrix
  80223. */
  80224. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80225. return BABYLON.Matrix.Identity();
  80226. };
  80227. /**
  80228. * This function is called by the two RIG cameras.
  80229. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80230. */
  80231. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80232. var _this = this;
  80233. // Update the parent camera prior to using a child camera to avoid desynchronization
  80234. var parentCamera = this._cameraRigParams["parentCamera"];
  80235. parentCamera._updateCache();
  80236. //WebVR 1.1
  80237. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80238. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80239. if (!this.getScene().useRightHandedSystem) {
  80240. [2, 6, 8, 9, 14].forEach(function (num) {
  80241. _this._webvrViewMatrix.m[num] *= -1;
  80242. });
  80243. }
  80244. // update the camera rotation matrix
  80245. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80246. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80247. // Computing target and final matrix
  80248. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80249. // should the view matrix be updated with scale and position offset?
  80250. if (parentCamera.deviceScaleFactor !== 1) {
  80251. this._webvrViewMatrix.invert();
  80252. // scale the position, if set
  80253. if (parentCamera.deviceScaleFactor) {
  80254. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80255. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80256. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80257. }
  80258. this._webvrViewMatrix.invert();
  80259. }
  80260. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80261. return this._webvrViewMatrix;
  80262. };
  80263. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80264. var _this = this;
  80265. var parentCamera = this.parent;
  80266. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80267. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80268. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80269. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80270. //babylon compatible matrix
  80271. if (!this.getScene().useRightHandedSystem) {
  80272. [8, 9, 10, 11].forEach(function (num) {
  80273. _this._projectionMatrix.m[num] *= -1;
  80274. });
  80275. }
  80276. return this._projectionMatrix;
  80277. };
  80278. /**
  80279. * Initializes the controllers and their meshes
  80280. */
  80281. WebVRFreeCamera.prototype.initControllers = function () {
  80282. var _this = this;
  80283. this.controllers = [];
  80284. var manager = this.getScene().gamepadManager;
  80285. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80286. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80287. var webVrController = gamepad;
  80288. if (webVrController.defaultModel) {
  80289. webVrController.defaultModel.setEnabled(false);
  80290. }
  80291. if (webVrController.hand === "right") {
  80292. _this._rightController = null;
  80293. }
  80294. if (webVrController.hand === "left") {
  80295. _this._leftController = null;
  80296. }
  80297. var controllerIndex = _this.controllers.indexOf(webVrController);
  80298. if (controllerIndex !== -1) {
  80299. _this.controllers.splice(controllerIndex, 1);
  80300. }
  80301. }
  80302. });
  80303. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80304. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80305. var webVrController_1 = gamepad;
  80306. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80307. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80308. if (_this.webVROptions.controllerMeshes) {
  80309. if (webVrController_1.defaultModel) {
  80310. webVrController_1.defaultModel.setEnabled(true);
  80311. }
  80312. else {
  80313. // Load the meshes
  80314. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80315. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80316. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80317. if (_this.webVROptions.defaultLightingOnControllers) {
  80318. if (!_this._lightOnControllers) {
  80319. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80320. }
  80321. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80322. var children = mesh.getChildren();
  80323. if (children.length !== 0) {
  80324. children.forEach(function (mesh) {
  80325. light.includedOnlyMeshes.push(mesh);
  80326. activateLightOnSubMeshes_1(mesh, light);
  80327. });
  80328. }
  80329. };
  80330. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80331. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80332. }
  80333. });
  80334. }
  80335. }
  80336. webVrController_1.attachToPoseControlledCamera(_this);
  80337. // since this is async - sanity check. Is the controller already stored?
  80338. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80339. //add to the controllers array
  80340. _this.controllers.push(webVrController_1);
  80341. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80342. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80343. // So we're overriding setting left & right manually to be sure
  80344. var firstViveWandDetected = false;
  80345. for (var i = 0; i < _this.controllers.length; i++) {
  80346. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80347. if (!firstViveWandDetected) {
  80348. firstViveWandDetected = true;
  80349. _this.controllers[i].hand = "left";
  80350. }
  80351. else {
  80352. _this.controllers[i].hand = "right";
  80353. }
  80354. }
  80355. }
  80356. //did we find enough controllers? Great! let the developer know.
  80357. if (_this.controllers.length >= 2) {
  80358. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80359. }
  80360. }
  80361. }
  80362. });
  80363. };
  80364. return WebVRFreeCamera;
  80365. }(BABYLON.FreeCamera));
  80366. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80367. })(BABYLON || (BABYLON = {}));
  80368. //# sourceMappingURL=babylon.webVRCamera.js.map
  80369. var BABYLON;
  80370. (function (BABYLON) {
  80371. // We're mainly based on the logic defined into the FreeCamera code
  80372. /**
  80373. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80374. * being tilted forward or back and left or right.
  80375. */
  80376. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80377. __extends(DeviceOrientationCamera, _super);
  80378. /**
  80379. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80380. * @param name The name of the camera
  80381. * @param position The start position camera
  80382. * @param scene The scene the camera belongs to
  80383. */
  80384. function DeviceOrientationCamera(name, position, scene) {
  80385. var _this = _super.call(this, name, position, scene) || this;
  80386. _this._quaternionCache = new BABYLON.Quaternion();
  80387. _this.inputs.addDeviceOrientation();
  80388. return _this;
  80389. }
  80390. /**
  80391. * Gets the current instance class name ("DeviceOrientationCamera").
  80392. * This helps avoiding instanceof at run time.
  80393. * @returns the class name
  80394. */
  80395. DeviceOrientationCamera.prototype.getClassName = function () {
  80396. return "DeviceOrientationCamera";
  80397. };
  80398. /**
  80399. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80400. */
  80401. DeviceOrientationCamera.prototype._checkInputs = function () {
  80402. _super.prototype._checkInputs.call(this);
  80403. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80404. if (this._initialQuaternion) {
  80405. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80406. }
  80407. };
  80408. /**
  80409. * Reset the camera to its default orientation on the specified axis only.
  80410. * @param axis The axis to reset
  80411. */
  80412. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80413. var _this = this;
  80414. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80415. //can only work if this camera has a rotation quaternion already.
  80416. if (!this.rotationQuaternion)
  80417. return;
  80418. if (!this._initialQuaternion) {
  80419. this._initialQuaternion = new BABYLON.Quaternion();
  80420. }
  80421. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80422. ['x', 'y', 'z'].forEach(function (axisName) {
  80423. if (!axis[axisName]) {
  80424. _this._initialQuaternion[axisName] = 0;
  80425. }
  80426. else {
  80427. _this._initialQuaternion[axisName] *= -1;
  80428. }
  80429. });
  80430. this._initialQuaternion.normalize();
  80431. //force rotation update
  80432. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80433. };
  80434. return DeviceOrientationCamera;
  80435. }(BABYLON.FreeCamera));
  80436. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80437. })(BABYLON || (BABYLON = {}));
  80438. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80439. var BABYLON;
  80440. (function (BABYLON) {
  80441. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80442. __extends(VRDeviceOrientationFreeCamera, _super);
  80443. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80444. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80445. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80446. var _this = _super.call(this, name, position, scene) || this;
  80447. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80448. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80449. return _this;
  80450. }
  80451. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80452. return "VRDeviceOrientationFreeCamera";
  80453. };
  80454. return VRDeviceOrientationFreeCamera;
  80455. }(BABYLON.DeviceOrientationCamera));
  80456. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80457. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80458. __extends(VRDeviceOrientationGamepadCamera, _super);
  80459. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80460. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80461. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80462. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80463. _this.inputs.addGamepad();
  80464. return _this;
  80465. }
  80466. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80467. return "VRDeviceOrientationGamepadCamera";
  80468. };
  80469. return VRDeviceOrientationGamepadCamera;
  80470. }(VRDeviceOrientationFreeCamera));
  80471. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80472. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80473. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80474. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80475. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80476. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80477. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80478. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80479. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80480. _this.inputs.addVRDeviceOrientation();
  80481. return _this;
  80482. }
  80483. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80484. return "VRDeviceOrientationArcRotateCamera";
  80485. };
  80486. return VRDeviceOrientationArcRotateCamera;
  80487. }(BABYLON.ArcRotateCamera));
  80488. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80489. })(BABYLON || (BABYLON = {}));
  80490. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80491. var BABYLON;
  80492. (function (BABYLON) {
  80493. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80494. __extends(AnaglyphFreeCamera, _super);
  80495. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80496. var _this = _super.call(this, name, position, scene) || this;
  80497. _this.interaxialDistance = interaxialDistance;
  80498. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80499. return _this;
  80500. }
  80501. AnaglyphFreeCamera.prototype.getClassName = function () {
  80502. return "AnaglyphFreeCamera";
  80503. };
  80504. return AnaglyphFreeCamera;
  80505. }(BABYLON.FreeCamera));
  80506. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80507. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80508. __extends(AnaglyphArcRotateCamera, _super);
  80509. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80510. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80511. _this.interaxialDistance = interaxialDistance;
  80512. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80513. return _this;
  80514. }
  80515. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80516. return "AnaglyphArcRotateCamera";
  80517. };
  80518. return AnaglyphArcRotateCamera;
  80519. }(BABYLON.ArcRotateCamera));
  80520. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80521. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80522. __extends(AnaglyphGamepadCamera, _super);
  80523. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80524. var _this = _super.call(this, name, position, scene) || this;
  80525. _this.interaxialDistance = interaxialDistance;
  80526. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80527. return _this;
  80528. }
  80529. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80530. return "AnaglyphGamepadCamera";
  80531. };
  80532. return AnaglyphGamepadCamera;
  80533. }(BABYLON.GamepadCamera));
  80534. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80535. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80536. __extends(AnaglyphUniversalCamera, _super);
  80537. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80538. var _this = _super.call(this, name, position, scene) || this;
  80539. _this.interaxialDistance = interaxialDistance;
  80540. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80541. return _this;
  80542. }
  80543. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80544. return "AnaglyphUniversalCamera";
  80545. };
  80546. return AnaglyphUniversalCamera;
  80547. }(BABYLON.UniversalCamera));
  80548. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80549. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80550. __extends(StereoscopicFreeCamera, _super);
  80551. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80552. var _this = _super.call(this, name, position, scene) || this;
  80553. _this.interaxialDistance = interaxialDistance;
  80554. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80555. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80556. return _this;
  80557. }
  80558. StereoscopicFreeCamera.prototype.getClassName = function () {
  80559. return "StereoscopicFreeCamera";
  80560. };
  80561. return StereoscopicFreeCamera;
  80562. }(BABYLON.FreeCamera));
  80563. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80564. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80565. __extends(StereoscopicArcRotateCamera, _super);
  80566. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80567. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80568. _this.interaxialDistance = interaxialDistance;
  80569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80571. return _this;
  80572. }
  80573. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80574. return "StereoscopicArcRotateCamera";
  80575. };
  80576. return StereoscopicArcRotateCamera;
  80577. }(BABYLON.ArcRotateCamera));
  80578. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80579. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80580. __extends(StereoscopicGamepadCamera, _super);
  80581. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80582. var _this = _super.call(this, name, position, scene) || this;
  80583. _this.interaxialDistance = interaxialDistance;
  80584. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80585. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80586. return _this;
  80587. }
  80588. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80589. return "StereoscopicGamepadCamera";
  80590. };
  80591. return StereoscopicGamepadCamera;
  80592. }(BABYLON.GamepadCamera));
  80593. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80594. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80595. __extends(StereoscopicUniversalCamera, _super);
  80596. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80597. var _this = _super.call(this, name, position, scene) || this;
  80598. _this.interaxialDistance = interaxialDistance;
  80599. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80600. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80601. return _this;
  80602. }
  80603. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80604. return "StereoscopicUniversalCamera";
  80605. };
  80606. return StereoscopicUniversalCamera;
  80607. }(BABYLON.UniversalCamera));
  80608. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80609. })(BABYLON || (BABYLON = {}));
  80610. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80611. var BABYLON;
  80612. (function (BABYLON) {
  80613. var VRExperienceHelperGazer = /** @class */ (function () {
  80614. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80615. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80616. this.scene = scene;
  80617. this._pointerDownOnMeshAsked = false;
  80618. this._isActionableMesh = false;
  80619. this._teleportationRequestInitiated = false;
  80620. this._teleportationBackRequestInitiated = false;
  80621. this._dpadPressed = true;
  80622. this._activePointer = false;
  80623. this._id = VRExperienceHelperGazer._idCounter++;
  80624. // Gaze tracker
  80625. if (!gazeTrackerToClone) {
  80626. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80627. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80628. this._gazeTracker.isPickable = false;
  80629. this._gazeTracker.isVisible = false;
  80630. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80631. targetMat.specularColor = BABYLON.Color3.Black();
  80632. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80633. targetMat.backFaceCulling = false;
  80634. this._gazeTracker.material = targetMat;
  80635. }
  80636. else {
  80637. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80638. }
  80639. }
  80640. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80641. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80642. };
  80643. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80644. this._pointerDownOnMeshAsked = true;
  80645. if (this._currentMeshSelected && this._currentHit) {
  80646. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80647. }
  80648. };
  80649. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80650. if (this._currentMeshSelected && this._currentHit) {
  80651. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80652. }
  80653. this._pointerDownOnMeshAsked = false;
  80654. };
  80655. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80656. this._activePointer = true;
  80657. };
  80658. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80659. this._activePointer = false;
  80660. };
  80661. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80662. };
  80663. VRExperienceHelperGazer.prototype.dispose = function () {
  80664. this._interactionsEnabled = false;
  80665. this._teleportationEnabled = false;
  80666. };
  80667. VRExperienceHelperGazer._idCounter = 0;
  80668. return VRExperienceHelperGazer;
  80669. }());
  80670. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80671. __extends(VRExperienceHelperControllerGazer, _super);
  80672. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80673. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80674. _this.webVRController = webVRController;
  80675. // Laser pointer
  80676. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80677. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80678. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80679. laserPointerMaterial.alpha = 0.6;
  80680. _this._laserPointer.material = laserPointerMaterial;
  80681. _this._laserPointer.rotation.x = Math.PI / 2;
  80682. _this._laserPointer.position.z = -0.5;
  80683. _this._laserPointer.isVisible = false;
  80684. if (!webVRController.mesh) {
  80685. // Create an empty mesh that is used prior to loading the high quality model
  80686. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80687. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80688. preloadPointerPose.rotation.x = -0.7;
  80689. preloadMesh.addChild(preloadPointerPose);
  80690. webVRController.attachToMesh(preloadMesh);
  80691. }
  80692. _this._setLaserPointerParent(webVRController.mesh);
  80693. return _this;
  80694. }
  80695. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80696. return this.webVRController.getForwardRay(length);
  80697. };
  80698. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80699. _super.prototype._activatePointer.call(this);
  80700. this._laserPointer.isVisible = true;
  80701. };
  80702. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80703. _super.prototype._deactivatePointer.call(this);
  80704. this._laserPointer.isVisible = false;
  80705. };
  80706. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80707. this._laserPointer.material.emissiveColor = color;
  80708. };
  80709. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80710. var makeNotPick = function (root) {
  80711. root.name += " laserPointer";
  80712. root.getChildMeshes().forEach(function (c) {
  80713. makeNotPick(c);
  80714. });
  80715. };
  80716. makeNotPick(mesh);
  80717. var childMeshes = mesh.getChildMeshes();
  80718. this.webVRController._pointingPoseNode = null;
  80719. for (var i = 0; i < childMeshes.length; i++) {
  80720. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80721. mesh = childMeshes[i];
  80722. this.webVRController._pointingPoseNode = mesh;
  80723. break;
  80724. }
  80725. }
  80726. this._laserPointer.parent = mesh;
  80727. };
  80728. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80729. this._laserPointer.scaling.y = distance;
  80730. this._laserPointer.position.z = -distance / 2;
  80731. };
  80732. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80733. _super.prototype.dispose.call(this);
  80734. this._laserPointer.dispose();
  80735. };
  80736. return VRExperienceHelperControllerGazer;
  80737. }(VRExperienceHelperGazer));
  80738. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80739. __extends(VRExperienceHelperCameraGazer, _super);
  80740. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80741. var _this = _super.call(this, scene) || this;
  80742. _this.getCamera = getCamera;
  80743. return _this;
  80744. }
  80745. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80746. var camera = this.getCamera();
  80747. if (camera) {
  80748. return camera.getForwardRay(length);
  80749. }
  80750. else {
  80751. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80752. }
  80753. };
  80754. return VRExperienceHelperCameraGazer;
  80755. }(VRExperienceHelperGazer));
  80756. /**
  80757. * Helps to quickly add VR support to an existing scene.
  80758. * See http://doc.babylonjs.com/how_to/webvr_helper
  80759. */
  80760. var VRExperienceHelper = /** @class */ (function () {
  80761. /**
  80762. * Instantiates a VRExperienceHelper.
  80763. * Helps to quickly add VR support to an existing scene.
  80764. * @param scene The scene the VRExperienceHelper belongs to.
  80765. * @param webVROptions Options to modify the vr experience helper's behavior.
  80766. */
  80767. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80768. if (webVROptions === void 0) { webVROptions = {}; }
  80769. var _this = this;
  80770. this.webVROptions = webVROptions;
  80771. // Can the system support WebVR, even if a headset isn't plugged in?
  80772. this._webVRsupported = false;
  80773. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80774. this._webVRready = false;
  80775. // Are we waiting for the requestPresent callback to complete?
  80776. this._webVRrequesting = false;
  80777. // Are we presenting to the headset right now?
  80778. this._webVRpresenting = false;
  80779. // Are we presenting in the fullscreen fallback?
  80780. this._fullscreenVRpresenting = false;
  80781. /**
  80782. * Observable raised when entering VR.
  80783. */
  80784. this.onEnteringVRObservable = new BABYLON.Observable();
  80785. /**
  80786. * Observable raised when exiting VR.
  80787. */
  80788. this.onExitingVRObservable = new BABYLON.Observable();
  80789. /**
  80790. * Observable raised when controller mesh is loaded.
  80791. */
  80792. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80793. this._useCustomVRButton = false;
  80794. this._teleportationRequested = false;
  80795. this._teleportActive = false;
  80796. this._floorMeshesCollection = [];
  80797. this._rotationAllowed = true;
  80798. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80799. this._rotationRightAsked = false;
  80800. this._rotationLeftAsked = false;
  80801. this._isDefaultTeleportationTarget = true;
  80802. this._teleportationFillColor = "#444444";
  80803. this._teleportationBorderColor = "#FFFFFF";
  80804. this._rotationAngle = 0;
  80805. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80806. this._padSensibilityUp = 0.65;
  80807. this._padSensibilityDown = 0.35;
  80808. this.leftController = null;
  80809. this.rightController = null;
  80810. /**
  80811. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80812. */
  80813. this.onNewMeshSelected = new BABYLON.Observable();
  80814. /**
  80815. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80816. */
  80817. this.onNewMeshPicked = new BABYLON.Observable();
  80818. /**
  80819. * Observable raised before camera teleportation
  80820. */
  80821. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80822. /**
  80823. * Observable raised after camera teleportation
  80824. */
  80825. this.onAfterCameraTeleport = new BABYLON.Observable();
  80826. /**
  80827. * Observable raised when current selected mesh gets unselected
  80828. */
  80829. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80830. /**
  80831. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80832. */
  80833. this.teleportationEnabled = true;
  80834. this._teleportationInitialized = false;
  80835. this._interactionsEnabled = false;
  80836. this._interactionsRequested = false;
  80837. this._displayGaze = true;
  80838. this._displayLaserPointer = true;
  80839. this._onResize = function () {
  80840. _this.moveButtonToBottomRight();
  80841. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80842. _this.exitVR();
  80843. }
  80844. };
  80845. this._onFullscreenChange = function () {
  80846. if (document.fullscreen !== undefined) {
  80847. _this._fullscreenVRpresenting = document.fullscreen;
  80848. }
  80849. else if (document.mozFullScreen !== undefined) {
  80850. _this._fullscreenVRpresenting = document.mozFullScreen;
  80851. }
  80852. else if (document.webkitIsFullScreen !== undefined) {
  80853. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80854. }
  80855. else if (document.msIsFullScreen !== undefined) {
  80856. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80857. }
  80858. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80859. _this.exitVR();
  80860. if (!_this._useCustomVRButton) {
  80861. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80862. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80863. }
  80864. }
  80865. };
  80866. this.beforeRender = function () {
  80867. if (_this.leftController && _this.leftController._activePointer) {
  80868. _this._castRayAndSelectObject(_this.leftController);
  80869. }
  80870. if (_this.rightController && _this.rightController._activePointer) {
  80871. _this._castRayAndSelectObject(_this.rightController);
  80872. }
  80873. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80874. _this._castRayAndSelectObject(_this._cameraGazer);
  80875. }
  80876. else {
  80877. _this._cameraGazer._gazeTracker.isVisible = false;
  80878. }
  80879. };
  80880. this._onNewGamepadConnected = function (gamepad) {
  80881. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80882. if (gamepad.leftStick) {
  80883. gamepad.onleftstickchanged(function (stickValues) {
  80884. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80885. // Listening to classic/xbox gamepad only if no VR controller is active
  80886. if ((!_this.leftController && !_this.rightController) ||
  80887. ((_this.leftController && !_this.leftController._activePointer) &&
  80888. (_this.rightController && !_this.rightController._activePointer))) {
  80889. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80890. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80891. }
  80892. }
  80893. });
  80894. }
  80895. if (gamepad.rightStick) {
  80896. gamepad.onrightstickchanged(function (stickValues) {
  80897. if (_this._teleportationInitialized) {
  80898. _this._checkRotate(stickValues, _this._cameraGazer);
  80899. }
  80900. });
  80901. }
  80902. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80903. gamepad.onbuttondown(function (buttonPressed) {
  80904. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80905. _this._cameraGazer._selectionPointerDown();
  80906. }
  80907. });
  80908. gamepad.onbuttonup(function (buttonPressed) {
  80909. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80910. _this._cameraGazer._selectionPointerUp();
  80911. }
  80912. });
  80913. }
  80914. }
  80915. else {
  80916. var webVRController = gamepad;
  80917. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80918. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80919. _this.rightController = controller;
  80920. }
  80921. else {
  80922. _this.leftController = controller;
  80923. }
  80924. _this._tryEnableInteractionOnController(controller);
  80925. }
  80926. };
  80927. // 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
  80928. this._tryEnableInteractionOnController = function (controller) {
  80929. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80930. _this._enableInteractionOnController(controller);
  80931. }
  80932. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80933. _this._enableTeleportationOnController(controller);
  80934. }
  80935. };
  80936. this._onNewGamepadDisconnected = function (gamepad) {
  80937. if (gamepad instanceof BABYLON.WebVRController) {
  80938. if (gamepad.hand === "left" && _this.leftController != null) {
  80939. _this.leftController.dispose();
  80940. _this.leftController = null;
  80941. }
  80942. if (gamepad.hand === "right" && _this.rightController != null) {
  80943. _this.rightController.dispose();
  80944. _this.rightController = null;
  80945. }
  80946. }
  80947. };
  80948. this._workingVector = BABYLON.Vector3.Zero();
  80949. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80950. this._workingMatrix = BABYLON.Matrix.Identity();
  80951. this._scene = scene;
  80952. this._canvas = scene.getEngine().getRenderingCanvas();
  80953. // Parse options
  80954. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80955. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80956. }
  80957. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80958. webVROptions.createDeviceOrientationCamera = true;
  80959. }
  80960. if (webVROptions.defaultHeight === undefined) {
  80961. webVROptions.defaultHeight = 1.7;
  80962. }
  80963. if (webVROptions.useCustomVRButton) {
  80964. this._useCustomVRButton = true;
  80965. if (webVROptions.customVRButton) {
  80966. this._btnVR = webVROptions.customVRButton;
  80967. }
  80968. }
  80969. if (webVROptions.rayLength) {
  80970. this._rayLength = webVROptions.rayLength;
  80971. }
  80972. this._defaultHeight = webVROptions.defaultHeight;
  80973. if (webVROptions.positionScale) {
  80974. this._rayLength *= webVROptions.positionScale;
  80975. this._defaultHeight *= webVROptions.positionScale;
  80976. }
  80977. // Set position
  80978. if (this._scene.activeCamera) {
  80979. this._position = this._scene.activeCamera.position.clone();
  80980. }
  80981. else {
  80982. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80983. }
  80984. // Set non-vr camera
  80985. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80986. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80987. // Copy data from existing camera
  80988. if (this._scene.activeCamera) {
  80989. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80990. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80991. // Set rotation from previous camera
  80992. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80993. var targetCamera = this._scene.activeCamera;
  80994. if (targetCamera.rotationQuaternion) {
  80995. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80996. }
  80997. else {
  80998. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80999. }
  81000. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81001. }
  81002. }
  81003. this._scene.activeCamera = this._deviceOrientationCamera;
  81004. if (this._canvas) {
  81005. this._scene.activeCamera.attachControl(this._canvas);
  81006. }
  81007. }
  81008. else {
  81009. this._existingCamera = this._scene.activeCamera;
  81010. }
  81011. // Create VR cameras
  81012. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81013. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81014. }
  81015. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81016. this._webVRCamera.useStandingMatrix();
  81017. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81018. // Create default button
  81019. if (!this._useCustomVRButton) {
  81020. this._btnVR = document.createElement("BUTTON");
  81021. this._btnVR.className = "babylonVRicon";
  81022. this._btnVR.id = "babylonVRiconbtn";
  81023. this._btnVR.title = "Click to switch to VR";
  81024. 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) }";
  81025. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81026. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81027. // css += ".babylonVRicon.vrdisplaysupported { }";
  81028. // css += ".babylonVRicon.vrdisplayready { }";
  81029. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81030. var style = document.createElement('style');
  81031. style.appendChild(document.createTextNode(css));
  81032. document.getElementsByTagName('head')[0].appendChild(style);
  81033. this.moveButtonToBottomRight();
  81034. }
  81035. // VR button click event
  81036. if (this._btnVR) {
  81037. this._btnVR.addEventListener("click", function () {
  81038. if (!_this.isInVRMode) {
  81039. _this.enterVR();
  81040. }
  81041. else {
  81042. _this.exitVR();
  81043. }
  81044. });
  81045. }
  81046. // Window events
  81047. window.addEventListener("resize", this._onResize);
  81048. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81049. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81050. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81051. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81052. // Display vr button when headset is connected
  81053. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81054. this.displayVRButton();
  81055. }
  81056. else {
  81057. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81058. if (e.vrDisplay) {
  81059. _this.displayVRButton();
  81060. }
  81061. });
  81062. }
  81063. // Exiting VR mode using 'ESC' key on desktop
  81064. this._onKeyDown = function (event) {
  81065. if (event.keyCode === 27 && _this.isInVRMode) {
  81066. _this.exitVR();
  81067. }
  81068. };
  81069. document.addEventListener("keydown", this._onKeyDown);
  81070. // Exiting VR mode double tapping the touch screen
  81071. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81072. if (_this.isInVRMode) {
  81073. _this.exitVR();
  81074. if (_this._fullscreenVRpresenting) {
  81075. _this._scene.getEngine().switchFullscreen(true);
  81076. }
  81077. }
  81078. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81079. // Listen for WebVR display changes
  81080. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81081. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81082. this._onVRRequestPresentStart = function () {
  81083. _this._webVRrequesting = true;
  81084. _this.updateButtonVisibility();
  81085. };
  81086. this._onVRRequestPresentComplete = function (success) {
  81087. _this._webVRrequesting = false;
  81088. _this.updateButtonVisibility();
  81089. };
  81090. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81091. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81092. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81093. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81094. scene.onDisposeObservable.add(function () {
  81095. _this.dispose();
  81096. });
  81097. // Gamepad connection events
  81098. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81099. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81100. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81101. this.updateButtonVisibility();
  81102. //create easing functions
  81103. this._circleEase = new BABYLON.CircleEase();
  81104. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81105. }
  81106. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81107. /** Return this.onEnteringVRObservable
  81108. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81109. */
  81110. get: function () {
  81111. return this.onEnteringVRObservable;
  81112. },
  81113. enumerable: true,
  81114. configurable: true
  81115. });
  81116. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81117. /** Return this.onExitingVRObservable
  81118. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81119. */
  81120. get: function () {
  81121. return this.onExitingVRObservable;
  81122. },
  81123. enumerable: true,
  81124. configurable: true
  81125. });
  81126. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81127. /** Return this.onControllerMeshLoadedObservable
  81128. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81129. */
  81130. get: function () {
  81131. return this.onControllerMeshLoadedObservable;
  81132. },
  81133. enumerable: true,
  81134. configurable: true
  81135. });
  81136. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81137. /**
  81138. * The mesh used to display where the user is going to teleport.
  81139. */
  81140. get: function () {
  81141. return this._teleportationTarget;
  81142. },
  81143. /**
  81144. * Sets the mesh to be used to display where the user is going to teleport.
  81145. */
  81146. set: function (value) {
  81147. if (value) {
  81148. value.name = "teleportationTarget";
  81149. this._isDefaultTeleportationTarget = false;
  81150. this._teleportationTarget = value;
  81151. }
  81152. },
  81153. enumerable: true,
  81154. configurable: true
  81155. });
  81156. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81157. /**
  81158. * The mesh used to display where the user is selecting,
  81159. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81160. * See http://doc.babylonjs.com/resources/baking_transformations
  81161. */
  81162. get: function () {
  81163. return this._cameraGazer._gazeTracker;
  81164. },
  81165. set: function (value) {
  81166. if (value) {
  81167. this._cameraGazer._gazeTracker = value;
  81168. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81169. this._cameraGazer._gazeTracker.isPickable = false;
  81170. this._cameraGazer._gazeTracker.isVisible = false;
  81171. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81172. if (this.leftController) {
  81173. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81174. }
  81175. if (this.rightController) {
  81176. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81177. }
  81178. }
  81179. },
  81180. enumerable: true,
  81181. configurable: true
  81182. });
  81183. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81184. /**
  81185. * If the ray of the gaze should be displayed.
  81186. */
  81187. get: function () {
  81188. return this._displayGaze;
  81189. },
  81190. /**
  81191. * Sets if the ray of the gaze should be displayed.
  81192. */
  81193. set: function (value) {
  81194. this._displayGaze = value;
  81195. if (!value) {
  81196. this._cameraGazer._gazeTracker.isVisible = false;
  81197. if (this.leftController) {
  81198. this.leftController._gazeTracker.isVisible = false;
  81199. }
  81200. if (this.rightController) {
  81201. this.rightController._gazeTracker.isVisible = false;
  81202. }
  81203. }
  81204. },
  81205. enumerable: true,
  81206. configurable: true
  81207. });
  81208. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81209. /**
  81210. * If the ray of the LaserPointer should be displayed.
  81211. */
  81212. get: function () {
  81213. return this._displayLaserPointer;
  81214. },
  81215. /**
  81216. * Sets if the ray of the LaserPointer should be displayed.
  81217. */
  81218. set: function (value) {
  81219. this._displayLaserPointer = value;
  81220. if (!value) {
  81221. if (this.rightController) {
  81222. this.rightController._deactivatePointer();
  81223. this.rightController._gazeTracker.isVisible = false;
  81224. }
  81225. if (this.leftController) {
  81226. this.leftController._deactivatePointer();
  81227. this.leftController._gazeTracker.isVisible = false;
  81228. }
  81229. }
  81230. else {
  81231. if (this.rightController) {
  81232. this.rightController._activatePointer();
  81233. }
  81234. else if (this.leftController) {
  81235. this.leftController._activatePointer();
  81236. }
  81237. }
  81238. },
  81239. enumerable: true,
  81240. configurable: true
  81241. });
  81242. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81243. /**
  81244. * The deviceOrientationCamera used as the camera when not in VR.
  81245. */
  81246. get: function () {
  81247. return this._deviceOrientationCamera;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81253. /**
  81254. * Based on the current WebVR support, returns the current VR camera used.
  81255. */
  81256. get: function () {
  81257. if (this._webVRready) {
  81258. return this._webVRCamera;
  81259. }
  81260. else {
  81261. return this._scene.activeCamera;
  81262. }
  81263. },
  81264. enumerable: true,
  81265. configurable: true
  81266. });
  81267. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81268. /**
  81269. * The webVRCamera which is used when in VR.
  81270. */
  81271. get: function () {
  81272. return this._webVRCamera;
  81273. },
  81274. enumerable: true,
  81275. configurable: true
  81276. });
  81277. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81278. /**
  81279. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81280. */
  81281. get: function () {
  81282. return this._vrDeviceOrientationCamera;
  81283. },
  81284. enumerable: true,
  81285. configurable: true
  81286. });
  81287. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81288. get: function () {
  81289. var result = this._cameraGazer._teleportationRequestInitiated
  81290. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81291. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81292. return result;
  81293. },
  81294. enumerable: true,
  81295. configurable: true
  81296. });
  81297. // Raised when one of the controller has loaded successfully its associated default mesh
  81298. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81299. if (this.leftController && this.leftController.webVRController == webVRController) {
  81300. if (webVRController.mesh) {
  81301. this.leftController._setLaserPointerParent(webVRController.mesh);
  81302. }
  81303. }
  81304. if (this.rightController && this.rightController.webVRController == webVRController) {
  81305. if (webVRController.mesh) {
  81306. this.rightController._setLaserPointerParent(webVRController.mesh);
  81307. }
  81308. }
  81309. try {
  81310. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81311. }
  81312. catch (err) {
  81313. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81314. }
  81315. };
  81316. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81317. /**
  81318. * Gets a value indicating if we are currently in VR mode.
  81319. */
  81320. get: function () {
  81321. return this._webVRpresenting || this._fullscreenVRpresenting;
  81322. },
  81323. enumerable: true,
  81324. configurable: true
  81325. });
  81326. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81327. var vrDisplay = this._scene.getEngine().getVRDevice();
  81328. if (vrDisplay) {
  81329. var wasPresenting = this._webVRpresenting;
  81330. // A VR display is connected
  81331. this._webVRpresenting = vrDisplay.isPresenting;
  81332. if (wasPresenting && !this._webVRpresenting)
  81333. this.exitVR();
  81334. }
  81335. else {
  81336. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81337. }
  81338. this.updateButtonVisibility();
  81339. };
  81340. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81341. this._webVRsupported = eventArgs.vrSupported;
  81342. this._webVRready = !!eventArgs.vrDisplay;
  81343. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81344. this.updateButtonVisibility();
  81345. };
  81346. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81347. if (this._canvas && !this._useCustomVRButton) {
  81348. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81349. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81350. }
  81351. };
  81352. VRExperienceHelper.prototype.displayVRButton = function () {
  81353. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81354. document.body.appendChild(this._btnVR);
  81355. this._btnVRDisplayed = true;
  81356. }
  81357. };
  81358. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81359. if (!this._btnVR || this._useCustomVRButton) {
  81360. return;
  81361. }
  81362. this._btnVR.className = "babylonVRicon";
  81363. if (this.isInVRMode) {
  81364. this._btnVR.className += " vrdisplaypresenting";
  81365. }
  81366. else {
  81367. if (this._webVRready)
  81368. this._btnVR.className += " vrdisplayready";
  81369. if (this._webVRsupported)
  81370. this._btnVR.className += " vrdisplaysupported";
  81371. if (this._webVRrequesting)
  81372. this._btnVR.className += " vrdisplayrequesting";
  81373. }
  81374. };
  81375. /**
  81376. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81377. * Otherwise, will use the fullscreen API.
  81378. */
  81379. VRExperienceHelper.prototype.enterVR = function () {
  81380. if (this.onEnteringVRObservable) {
  81381. try {
  81382. this.onEnteringVRObservable.notifyObservers(this);
  81383. }
  81384. catch (err) {
  81385. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81386. }
  81387. }
  81388. if (this._scene.activeCamera) {
  81389. this._position = this._scene.activeCamera.position.clone();
  81390. // make sure that we return to the last active camera
  81391. this._existingCamera = this._scene.activeCamera;
  81392. }
  81393. if (this._webVRrequesting)
  81394. return;
  81395. // If WebVR is supported and a headset is connected
  81396. if (this._webVRready) {
  81397. if (!this._webVRpresenting) {
  81398. this._webVRCamera.position = this._position;
  81399. this._scene.activeCamera = this._webVRCamera;
  81400. }
  81401. }
  81402. else if (this._vrDeviceOrientationCamera) {
  81403. this._vrDeviceOrientationCamera.position = this._position;
  81404. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81405. this._scene.getEngine().switchFullscreen(true);
  81406. this.updateButtonVisibility();
  81407. }
  81408. if (this._scene.activeCamera && this._canvas) {
  81409. this._scene.activeCamera.attachControl(this._canvas);
  81410. }
  81411. if (this._interactionsEnabled) {
  81412. this._scene.registerBeforeRender(this.beforeRender);
  81413. }
  81414. };
  81415. /**
  81416. * Attempt to exit VR, or fullscreen.
  81417. */
  81418. VRExperienceHelper.prototype.exitVR = function () {
  81419. if (this.onExitingVRObservable) {
  81420. try {
  81421. this.onExitingVRObservable.notifyObservers(this);
  81422. }
  81423. catch (err) {
  81424. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81425. }
  81426. }
  81427. if (this._webVRpresenting) {
  81428. this._scene.getEngine().disableVR();
  81429. }
  81430. if (this._scene.activeCamera) {
  81431. this._position = this._scene.activeCamera.position.clone();
  81432. }
  81433. if (this._deviceOrientationCamera) {
  81434. this._deviceOrientationCamera.position = this._position;
  81435. this._scene.activeCamera = this._deviceOrientationCamera;
  81436. if (this._canvas) {
  81437. this._scene.activeCamera.attachControl(this._canvas);
  81438. }
  81439. }
  81440. else if (this._existingCamera) {
  81441. this._existingCamera.position = this._position;
  81442. this._scene.activeCamera = this._existingCamera;
  81443. }
  81444. this.updateButtonVisibility();
  81445. if (this._interactionsEnabled) {
  81446. this._scene.unregisterBeforeRender(this.beforeRender);
  81447. }
  81448. };
  81449. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81450. /**
  81451. * The position of the vr experience helper.
  81452. */
  81453. get: function () {
  81454. return this._position;
  81455. },
  81456. /**
  81457. * Sets the position of the vr experience helper.
  81458. */
  81459. set: function (value) {
  81460. this._position = value;
  81461. if (this._scene.activeCamera) {
  81462. this._scene.activeCamera.position = value;
  81463. }
  81464. },
  81465. enumerable: true,
  81466. configurable: true
  81467. });
  81468. /**
  81469. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81470. */
  81471. VRExperienceHelper.prototype.enableInteractions = function () {
  81472. var _this = this;
  81473. if (!this._interactionsEnabled) {
  81474. this._interactionsRequested = true;
  81475. if (this.leftController) {
  81476. this._enableInteractionOnController(this.leftController);
  81477. }
  81478. if (this.rightController) {
  81479. this._enableInteractionOnController(this.rightController);
  81480. }
  81481. this.raySelectionPredicate = function (mesh) {
  81482. return mesh.isVisible;
  81483. };
  81484. this.meshSelectionPredicate = function (mesh) {
  81485. return true;
  81486. };
  81487. this._raySelectionPredicate = function (mesh) {
  81488. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81489. && mesh.name.indexOf("teleportationTarget") === -1
  81490. && mesh.name.indexOf("torusTeleportation") === -1
  81491. && mesh.name.indexOf("laserPointer") === -1)) {
  81492. return _this.raySelectionPredicate(mesh);
  81493. }
  81494. return false;
  81495. };
  81496. this._interactionsEnabled = true;
  81497. }
  81498. };
  81499. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81500. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81501. if (this._floorMeshesCollection[i].id === mesh.id) {
  81502. return true;
  81503. }
  81504. }
  81505. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81506. return true;
  81507. }
  81508. return false;
  81509. };
  81510. /**
  81511. * Adds a floor mesh to be used for teleportation.
  81512. * @param floorMesh the mesh to be used for teleportation.
  81513. */
  81514. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81515. if (!this._floorMeshesCollection) {
  81516. return;
  81517. }
  81518. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81519. return;
  81520. }
  81521. this._floorMeshesCollection.push(floorMesh);
  81522. };
  81523. /**
  81524. * Removes a floor mesh from being used for teleportation.
  81525. * @param floorMesh the mesh to be removed.
  81526. */
  81527. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81528. if (!this._floorMeshesCollection) {
  81529. return;
  81530. }
  81531. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81532. if (meshIndex !== -1) {
  81533. this._floorMeshesCollection.splice(meshIndex, 1);
  81534. }
  81535. };
  81536. /**
  81537. * Enables interactions and teleportation using the VR controllers and gaze.
  81538. * @param vrTeleportationOptions options to modify teleportation behavior.
  81539. */
  81540. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81541. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81542. if (!this._teleportationInitialized) {
  81543. this._teleportationRequested = true;
  81544. this.enableInteractions();
  81545. if (vrTeleportationOptions.floorMeshName) {
  81546. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81547. }
  81548. if (vrTeleportationOptions.floorMeshes) {
  81549. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81550. }
  81551. if (this.leftController != null) {
  81552. this._enableTeleportationOnController(this.leftController);
  81553. }
  81554. if (this.rightController != null) {
  81555. this._enableTeleportationOnController(this.rightController);
  81556. }
  81557. // Creates an image processing post process for the vignette not relying
  81558. // on the main scene configuration for image processing to reduce setup and spaces
  81559. // (gamma/linear) conflicts.
  81560. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81561. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81562. imageProcessingConfiguration.vignetteEnabled = true;
  81563. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81564. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81565. this._teleportationInitialized = true;
  81566. if (this._isDefaultTeleportationTarget) {
  81567. this._createTeleportationCircles();
  81568. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81569. }
  81570. }
  81571. };
  81572. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81573. var _this = this;
  81574. var controllerMesh = controller.webVRController.mesh;
  81575. if (controllerMesh) {
  81576. controller._interactionsEnabled = true;
  81577. controller._activatePointer();
  81578. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81579. // Enabling / disabling laserPointer
  81580. if (_this._displayLaserPointer && stateObject.value === 1) {
  81581. if (controller._activePointer) {
  81582. controller._deactivatePointer();
  81583. }
  81584. else {
  81585. controller._activatePointer();
  81586. }
  81587. if (_this.displayGaze) {
  81588. controller._gazeTracker.isVisible = controller._activePointer;
  81589. }
  81590. }
  81591. });
  81592. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81593. if (!controller._pointerDownOnMeshAsked) {
  81594. if (stateObject.value > _this._padSensibilityUp) {
  81595. controller._selectionPointerDown();
  81596. }
  81597. }
  81598. else if (stateObject.value < _this._padSensibilityDown) {
  81599. controller._selectionPointerUp();
  81600. }
  81601. });
  81602. }
  81603. };
  81604. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81605. // Dont teleport if another gaze already requested teleportation
  81606. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81607. return;
  81608. }
  81609. if (!gazer._teleportationRequestInitiated) {
  81610. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81611. gazer._activatePointer();
  81612. gazer._teleportationRequestInitiated = true;
  81613. }
  81614. }
  81615. else {
  81616. // Listening to the proper controller values changes to confirm teleportation
  81617. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81618. if (this._teleportActive) {
  81619. this._teleportCamera(this._haloCenter);
  81620. }
  81621. gazer._teleportationRequestInitiated = false;
  81622. }
  81623. }
  81624. };
  81625. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81626. // Only rotate when user is not currently selecting a teleportation location
  81627. if (gazer._teleportationRequestInitiated) {
  81628. return;
  81629. }
  81630. if (!this._rotationLeftAsked) {
  81631. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81632. this._rotationLeftAsked = true;
  81633. if (this._rotationAllowed) {
  81634. this._rotateCamera(false);
  81635. }
  81636. }
  81637. }
  81638. else {
  81639. if (stateObject.x > -this._padSensibilityDown) {
  81640. this._rotationLeftAsked = false;
  81641. }
  81642. }
  81643. if (!this._rotationRightAsked) {
  81644. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81645. this._rotationRightAsked = true;
  81646. if (this._rotationAllowed) {
  81647. this._rotateCamera(true);
  81648. }
  81649. }
  81650. }
  81651. else {
  81652. if (stateObject.x < this._padSensibilityDown) {
  81653. this._rotationRightAsked = false;
  81654. }
  81655. }
  81656. };
  81657. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81658. // Only teleport backwards when user is not currently selecting a teleportation location
  81659. if (gazer._teleportationRequestInitiated) {
  81660. return;
  81661. }
  81662. // Teleport backwards
  81663. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81664. if (!gazer._teleportationBackRequestInitiated) {
  81665. if (!this.currentVRCamera) {
  81666. return;
  81667. }
  81668. // Get rotation and position of the current camera
  81669. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81670. var position = this.currentVRCamera.position;
  81671. // If the camera has device position, use that instead
  81672. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81673. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81674. position = this.currentVRCamera.devicePosition;
  81675. }
  81676. // Get matrix with only the y rotation of the device rotation
  81677. rotation.toEulerAnglesToRef(this._workingVector);
  81678. this._workingVector.z = 0;
  81679. this._workingVector.x = 0;
  81680. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81681. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81682. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81683. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81684. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81685. var ray = new BABYLON.Ray(position, this._workingVector);
  81686. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81687. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81688. this._teleportCamera(hit.pickedPoint);
  81689. }
  81690. gazer._teleportationBackRequestInitiated = true;
  81691. }
  81692. }
  81693. else {
  81694. gazer._teleportationBackRequestInitiated = false;
  81695. }
  81696. };
  81697. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81698. var _this = this;
  81699. var controllerMesh = controller.webVRController.mesh;
  81700. if (controllerMesh) {
  81701. if (!controller._interactionsEnabled) {
  81702. this._enableInteractionOnController(controller);
  81703. }
  81704. controller._interactionsEnabled = true;
  81705. controller._teleportationEnabled = true;
  81706. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81707. controller._dpadPressed = false;
  81708. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81709. controller._dpadPressed = stateObject.pressed;
  81710. if (!controller._dpadPressed) {
  81711. _this._rotationLeftAsked = false;
  81712. _this._rotationRightAsked = false;
  81713. controller._teleportationBackRequestInitiated = false;
  81714. }
  81715. });
  81716. }
  81717. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81718. if (_this.teleportationEnabled) {
  81719. _this._checkTeleportBackwards(stateObject, controller);
  81720. _this._checkTeleportWithRay(stateObject, controller);
  81721. }
  81722. _this._checkRotate(stateObject, controller);
  81723. });
  81724. }
  81725. };
  81726. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81727. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81728. this._teleportationTarget.isPickable = false;
  81729. var length = 512;
  81730. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81731. dynamicTexture.hasAlpha = true;
  81732. var context = dynamicTexture.getContext();
  81733. var centerX = length / 2;
  81734. var centerY = length / 2;
  81735. var radius = 200;
  81736. context.beginPath();
  81737. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81738. context.fillStyle = this._teleportationFillColor;
  81739. context.fill();
  81740. context.lineWidth = 10;
  81741. context.strokeStyle = this._teleportationBorderColor;
  81742. context.stroke();
  81743. context.closePath();
  81744. dynamicTexture.update();
  81745. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81746. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81747. this._teleportationTarget.material = teleportationCircleMaterial;
  81748. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81749. torus.isPickable = false;
  81750. torus.parent = this._teleportationTarget;
  81751. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81752. var keys = [];
  81753. keys.push({
  81754. frame: 0,
  81755. value: 0
  81756. });
  81757. keys.push({
  81758. frame: 30,
  81759. value: 0.4
  81760. });
  81761. keys.push({
  81762. frame: 60,
  81763. value: 0
  81764. });
  81765. animationInnerCircle.setKeys(keys);
  81766. var easingFunction = new BABYLON.SineEase();
  81767. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81768. animationInnerCircle.setEasingFunction(easingFunction);
  81769. torus.animations = [];
  81770. torus.animations.push(animationInnerCircle);
  81771. this._scene.beginAnimation(torus, 0, 60, true);
  81772. this._hideTeleportationTarget();
  81773. };
  81774. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81775. this._teleportActive = true;
  81776. if (this._teleportationInitialized) {
  81777. this._teleportationTarget.isVisible = true;
  81778. if (this._isDefaultTeleportationTarget) {
  81779. this._teleportationTarget.getChildren()[0].isVisible = true;
  81780. }
  81781. }
  81782. };
  81783. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81784. this._teleportActive = false;
  81785. if (this._teleportationInitialized) {
  81786. this._teleportationTarget.isVisible = false;
  81787. if (this._isDefaultTeleportationTarget) {
  81788. this._teleportationTarget.getChildren()[0].isVisible = false;
  81789. }
  81790. }
  81791. };
  81792. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81793. var _this = this;
  81794. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81795. return;
  81796. }
  81797. if (right) {
  81798. this._rotationAngle++;
  81799. }
  81800. else {
  81801. this._rotationAngle--;
  81802. }
  81803. this.currentVRCamera.animations = [];
  81804. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81805. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81806. var animationRotationKeys = [];
  81807. animationRotationKeys.push({
  81808. frame: 0,
  81809. value: this.currentVRCamera.rotationQuaternion
  81810. });
  81811. animationRotationKeys.push({
  81812. frame: 6,
  81813. value: target
  81814. });
  81815. animationRotation.setKeys(animationRotationKeys);
  81816. animationRotation.setEasingFunction(this._circleEase);
  81817. this.currentVRCamera.animations.push(animationRotation);
  81818. this._postProcessMove.animations = [];
  81819. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81820. var vignetteWeightKeys = [];
  81821. vignetteWeightKeys.push({
  81822. frame: 0,
  81823. value: 0
  81824. });
  81825. vignetteWeightKeys.push({
  81826. frame: 3,
  81827. value: 4
  81828. });
  81829. vignetteWeightKeys.push({
  81830. frame: 6,
  81831. value: 0
  81832. });
  81833. animationPP.setKeys(vignetteWeightKeys);
  81834. animationPP.setEasingFunction(this._circleEase);
  81835. this._postProcessMove.animations.push(animationPP);
  81836. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81837. var vignetteStretchKeys = [];
  81838. vignetteStretchKeys.push({
  81839. frame: 0,
  81840. value: 0
  81841. });
  81842. vignetteStretchKeys.push({
  81843. frame: 3,
  81844. value: 10
  81845. });
  81846. vignetteStretchKeys.push({
  81847. frame: 6,
  81848. value: 0
  81849. });
  81850. animationPP2.setKeys(vignetteStretchKeys);
  81851. animationPP2.setEasingFunction(this._circleEase);
  81852. this._postProcessMove.animations.push(animationPP2);
  81853. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81854. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81855. this._postProcessMove.samples = 4;
  81856. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81857. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81858. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81859. });
  81860. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81861. };
  81862. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81863. if (hit.pickedPoint) {
  81864. if (gazer._teleportationRequestInitiated) {
  81865. this._displayTeleportationTarget();
  81866. this._haloCenter.copyFrom(hit.pickedPoint);
  81867. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81868. }
  81869. var pickNormal = hit.getNormal(true, false);
  81870. if (pickNormal) {
  81871. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81872. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81873. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81874. }
  81875. this._teleportationTarget.position.y += 0.1;
  81876. }
  81877. };
  81878. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81879. var _this = this;
  81880. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81881. return;
  81882. }
  81883. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81884. // offset of the headset from the anchor.
  81885. if (this.webVRCamera.leftCamera) {
  81886. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81887. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81888. location.subtractToRef(this._workingVector, this._workingVector);
  81889. }
  81890. else {
  81891. this._workingVector.copyFrom(location);
  81892. }
  81893. // Add height to account for user's height offset
  81894. if (this.isInVRMode) {
  81895. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81896. }
  81897. else {
  81898. this._workingVector.y += this._defaultHeight;
  81899. }
  81900. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81901. // Create animation from the camera's position to the new location
  81902. this.currentVRCamera.animations = [];
  81903. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81904. var animationCameraTeleportationKeys = [{
  81905. frame: 0,
  81906. value: this.currentVRCamera.position
  81907. },
  81908. {
  81909. frame: 11,
  81910. value: this._workingVector
  81911. }
  81912. ];
  81913. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81914. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81915. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81916. this._postProcessMove.animations = [];
  81917. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81918. var vignetteWeightKeys = [];
  81919. vignetteWeightKeys.push({
  81920. frame: 0,
  81921. value: 0
  81922. });
  81923. vignetteWeightKeys.push({
  81924. frame: 5,
  81925. value: 8
  81926. });
  81927. vignetteWeightKeys.push({
  81928. frame: 11,
  81929. value: 0
  81930. });
  81931. animationPP.setKeys(vignetteWeightKeys);
  81932. this._postProcessMove.animations.push(animationPP);
  81933. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81934. var vignetteStretchKeys = [];
  81935. vignetteStretchKeys.push({
  81936. frame: 0,
  81937. value: 0
  81938. });
  81939. vignetteStretchKeys.push({
  81940. frame: 5,
  81941. value: 10
  81942. });
  81943. vignetteStretchKeys.push({
  81944. frame: 11,
  81945. value: 0
  81946. });
  81947. animationPP2.setKeys(vignetteStretchKeys);
  81948. this._postProcessMove.animations.push(animationPP2);
  81949. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81950. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81951. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81952. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81953. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81954. });
  81955. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81956. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81957. });
  81958. this._hideTeleportationTarget();
  81959. };
  81960. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81961. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81962. return;
  81963. }
  81964. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81965. // Moving the gazeTracker on the mesh face targetted
  81966. if (hit && hit.pickedPoint) {
  81967. if (this._displayGaze) {
  81968. var multiplier = 1;
  81969. gazer._gazeTracker.isVisible = true;
  81970. if (gazer._isActionableMesh) {
  81971. multiplier = 3;
  81972. }
  81973. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81974. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81975. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81976. var pickNormal = hit.getNormal();
  81977. // To avoid z-fighting
  81978. var deltaFighting = 0.002;
  81979. if (pickNormal) {
  81980. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81981. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81982. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81983. }
  81984. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81985. if (gazer._gazeTracker.position.x < 0) {
  81986. gazer._gazeTracker.position.x += deltaFighting;
  81987. }
  81988. else {
  81989. gazer._gazeTracker.position.x -= deltaFighting;
  81990. }
  81991. if (gazer._gazeTracker.position.y < 0) {
  81992. gazer._gazeTracker.position.y += deltaFighting;
  81993. }
  81994. else {
  81995. gazer._gazeTracker.position.y -= deltaFighting;
  81996. }
  81997. if (gazer._gazeTracker.position.z < 0) {
  81998. gazer._gazeTracker.position.z += deltaFighting;
  81999. }
  82000. else {
  82001. gazer._gazeTracker.position.z -= deltaFighting;
  82002. }
  82003. }
  82004. // Changing the size of the laser pointer based on the distance from the targetted point
  82005. gazer._updatePointerDistance(hit.distance);
  82006. }
  82007. else {
  82008. gazer._gazeTracker.isVisible = false;
  82009. }
  82010. if (hit && hit.pickedMesh) {
  82011. gazer._currentHit = hit;
  82012. if (gazer._pointerDownOnMeshAsked) {
  82013. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82014. }
  82015. // The object selected is the floor, we're in a teleportation scenario
  82016. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82017. // Moving the teleportation area to this targetted point
  82018. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82019. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82020. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82021. }
  82022. gazer._currentMeshSelected = null;
  82023. if (gazer._teleportationRequestInitiated) {
  82024. this._moveTeleportationSelectorTo(hit, gazer);
  82025. }
  82026. return;
  82027. }
  82028. // If not, we're in a selection scenario
  82029. //this._teleportationAllowed = false;
  82030. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82031. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82032. this.onNewMeshPicked.notifyObservers(hit);
  82033. gazer._currentMeshSelected = hit.pickedMesh;
  82034. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82035. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82036. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82037. gazer._isActionableMesh = true;
  82038. }
  82039. else {
  82040. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82041. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82042. gazer._isActionableMesh = false;
  82043. }
  82044. try {
  82045. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82046. }
  82047. catch (err) {
  82048. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82049. }
  82050. }
  82051. else {
  82052. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82053. gazer._currentMeshSelected = null;
  82054. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82055. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82056. }
  82057. }
  82058. }
  82059. else {
  82060. gazer._currentHit = null;
  82061. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82062. gazer._currentMeshSelected = null;
  82063. //this._teleportationAllowed = false;
  82064. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82065. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82066. }
  82067. };
  82068. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82069. if (mesh) {
  82070. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82071. }
  82072. };
  82073. /**
  82074. * Sets the color of the laser ray from the vr controllers.
  82075. * @param color new color for the ray.
  82076. */
  82077. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82078. if (this.leftController) {
  82079. this.leftController._setLaserPointerColor(color);
  82080. }
  82081. if (this.rightController) {
  82082. this.rightController._setLaserPointerColor(color);
  82083. }
  82084. };
  82085. /**
  82086. * Sets the color of the ray from the vr headsets gaze.
  82087. * @param color new color for the ray.
  82088. */
  82089. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82090. if (!this._cameraGazer._gazeTracker.material) {
  82091. return;
  82092. }
  82093. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82094. if (this.leftController) {
  82095. this.leftController._gazeTracker.material.emissiveColor = color;
  82096. }
  82097. if (this.rightController) {
  82098. this.rightController._gazeTracker.material.emissiveColor = color;
  82099. }
  82100. };
  82101. /**
  82102. * Exits VR and disposes of the vr experience helper
  82103. */
  82104. VRExperienceHelper.prototype.dispose = function () {
  82105. if (this.isInVRMode) {
  82106. this.exitVR();
  82107. }
  82108. if (this._postProcessMove) {
  82109. this._postProcessMove.dispose();
  82110. }
  82111. if (this._webVRCamera) {
  82112. this._webVRCamera.dispose();
  82113. }
  82114. if (this._vrDeviceOrientationCamera) {
  82115. this._vrDeviceOrientationCamera.dispose();
  82116. }
  82117. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82118. document.body.removeChild(this._btnVR);
  82119. }
  82120. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82121. this._deviceOrientationCamera.dispose();
  82122. }
  82123. if (this._cameraGazer) {
  82124. this._cameraGazer.dispose();
  82125. }
  82126. if (this.leftController) {
  82127. this.leftController.dispose();
  82128. }
  82129. if (this.rightController) {
  82130. this.rightController.dispose();
  82131. }
  82132. if (this._teleportationTarget) {
  82133. this._teleportationTarget.dispose();
  82134. }
  82135. this._floorMeshesCollection = [];
  82136. document.removeEventListener("keydown", this._onKeyDown);
  82137. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82138. window.removeEventListener("resize", this._onResize);
  82139. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82140. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82141. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82142. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82143. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82144. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82145. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82146. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82147. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82148. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82149. this._scene.unregisterBeforeRender(this.beforeRender);
  82150. };
  82151. /**
  82152. * Gets the name of the VRExperienceHelper class
  82153. * @returns "VRExperienceHelper"
  82154. */
  82155. VRExperienceHelper.prototype.getClassName = function () {
  82156. return "VRExperienceHelper";
  82157. };
  82158. return VRExperienceHelper;
  82159. }());
  82160. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82161. })(BABYLON || (BABYLON = {}));
  82162. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82163. // Mainly based on these 2 articles :
  82164. // 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
  82165. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82166. var BABYLON;
  82167. (function (BABYLON) {
  82168. var JoystickAxis;
  82169. (function (JoystickAxis) {
  82170. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82171. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82172. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82173. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82174. var VirtualJoystick = /** @class */ (function () {
  82175. function VirtualJoystick(leftJoystick) {
  82176. var _this = this;
  82177. if (leftJoystick) {
  82178. this._leftJoystick = true;
  82179. }
  82180. else {
  82181. this._leftJoystick = false;
  82182. }
  82183. VirtualJoystick._globalJoystickIndex++;
  82184. // By default left & right arrow keys are moving the X
  82185. // and up & down keys are moving the Y
  82186. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82187. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82188. this.reverseLeftRight = false;
  82189. this.reverseUpDown = false;
  82190. // collections of pointers
  82191. this._touches = new BABYLON.StringDictionary();
  82192. this.deltaPosition = BABYLON.Vector3.Zero();
  82193. this._joystickSensibility = 25;
  82194. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82195. this._onResize = function (evt) {
  82196. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82197. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82198. if (VirtualJoystick.vjCanvas) {
  82199. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82200. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82201. }
  82202. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82203. };
  82204. // injecting a canvas element on top of the canvas 3D game
  82205. if (!VirtualJoystick.vjCanvas) {
  82206. window.addEventListener("resize", this._onResize, false);
  82207. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82208. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82209. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82210. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82211. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82212. VirtualJoystick.vjCanvas.style.width = "100%";
  82213. VirtualJoystick.vjCanvas.style.height = "100%";
  82214. VirtualJoystick.vjCanvas.style.position = "absolute";
  82215. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82216. VirtualJoystick.vjCanvas.style.top = "0px";
  82217. VirtualJoystick.vjCanvas.style.left = "0px";
  82218. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82219. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82220. // Support for jQuery PEP polyfill
  82221. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82222. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82223. if (!context) {
  82224. throw new Error("Unable to create canvas for virtual joystick");
  82225. }
  82226. VirtualJoystick.vjCanvasContext = context;
  82227. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82228. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82229. document.body.appendChild(VirtualJoystick.vjCanvas);
  82230. }
  82231. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82232. this.pressed = false;
  82233. // default joystick color
  82234. this._joystickColor = "cyan";
  82235. this._joystickPointerID = -1;
  82236. // current joystick position
  82237. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82238. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82239. // origin joystick position
  82240. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82241. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82242. this._onPointerDownHandlerRef = function (evt) {
  82243. _this._onPointerDown(evt);
  82244. };
  82245. this._onPointerMoveHandlerRef = function (evt) {
  82246. _this._onPointerMove(evt);
  82247. };
  82248. this._onPointerUpHandlerRef = function (evt) {
  82249. _this._onPointerUp(evt);
  82250. };
  82251. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82252. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82253. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82254. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82255. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82256. evt.preventDefault(); // Disables system menu
  82257. }, false);
  82258. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82259. }
  82260. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82261. this._joystickSensibility = newJoystickSensibility;
  82262. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82263. };
  82264. VirtualJoystick.prototype._onPointerDown = function (e) {
  82265. var positionOnScreenCondition;
  82266. e.preventDefault();
  82267. if (this._leftJoystick === true) {
  82268. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82269. }
  82270. else {
  82271. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82272. }
  82273. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82274. // First contact will be dedicated to the virtual joystick
  82275. this._joystickPointerID = e.pointerId;
  82276. this._joystickPointerStartPos.x = e.clientX;
  82277. this._joystickPointerStartPos.y = e.clientY;
  82278. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82279. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82280. this._deltaJoystickVector.x = 0;
  82281. this._deltaJoystickVector.y = 0;
  82282. this.pressed = true;
  82283. this._touches.add(e.pointerId.toString(), e);
  82284. }
  82285. else {
  82286. // You can only trigger the action buttons with a joystick declared
  82287. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82288. this._action();
  82289. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82290. }
  82291. }
  82292. };
  82293. VirtualJoystick.prototype._onPointerMove = function (e) {
  82294. // If the current pointer is the one associated to the joystick (first touch contact)
  82295. if (this._joystickPointerID == e.pointerId) {
  82296. this._joystickPointerPos.x = e.clientX;
  82297. this._joystickPointerPos.y = e.clientY;
  82298. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82299. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82300. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82301. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82302. switch (this._axisTargetedByLeftAndRight) {
  82303. case JoystickAxis.X:
  82304. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82305. break;
  82306. case JoystickAxis.Y:
  82307. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82308. break;
  82309. case JoystickAxis.Z:
  82310. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82311. break;
  82312. }
  82313. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82314. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82315. switch (this._axisTargetedByUpAndDown) {
  82316. case JoystickAxis.X:
  82317. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82318. break;
  82319. case JoystickAxis.Y:
  82320. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82321. break;
  82322. case JoystickAxis.Z:
  82323. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82324. break;
  82325. }
  82326. }
  82327. else {
  82328. var data = this._touches.get(e.pointerId.toString());
  82329. if (data) {
  82330. data.x = e.clientX;
  82331. data.y = e.clientY;
  82332. }
  82333. }
  82334. };
  82335. VirtualJoystick.prototype._onPointerUp = function (e) {
  82336. if (this._joystickPointerID == e.pointerId) {
  82337. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82338. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82339. this._joystickPointerID = -1;
  82340. this.pressed = false;
  82341. }
  82342. else {
  82343. var touch = this._touches.get(e.pointerId.toString());
  82344. if (touch) {
  82345. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82346. }
  82347. }
  82348. this._deltaJoystickVector.x = 0;
  82349. this._deltaJoystickVector.y = 0;
  82350. this._touches.remove(e.pointerId.toString());
  82351. };
  82352. /**
  82353. * Change the color of the virtual joystick
  82354. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82355. */
  82356. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82357. this._joystickColor = newColor;
  82358. };
  82359. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82360. this._action = action;
  82361. };
  82362. // Define which axis you'd like to control for left & right
  82363. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82364. switch (axis) {
  82365. case JoystickAxis.X:
  82366. case JoystickAxis.Y:
  82367. case JoystickAxis.Z:
  82368. this._axisTargetedByLeftAndRight = axis;
  82369. break;
  82370. default:
  82371. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82372. break;
  82373. }
  82374. };
  82375. // Define which axis you'd like to control for up & down
  82376. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82377. switch (axis) {
  82378. case JoystickAxis.X:
  82379. case JoystickAxis.Y:
  82380. case JoystickAxis.Z:
  82381. this._axisTargetedByUpAndDown = axis;
  82382. break;
  82383. default:
  82384. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82385. break;
  82386. }
  82387. };
  82388. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82389. var _this = this;
  82390. if (this.pressed) {
  82391. this._touches.forEach(function (key, touch) {
  82392. if (touch.pointerId === _this._joystickPointerID) {
  82393. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82394. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82395. VirtualJoystick.vjCanvasContext.beginPath();
  82396. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82397. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82398. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82399. VirtualJoystick.vjCanvasContext.stroke();
  82400. VirtualJoystick.vjCanvasContext.closePath();
  82401. VirtualJoystick.vjCanvasContext.beginPath();
  82402. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82403. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82404. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82405. VirtualJoystick.vjCanvasContext.stroke();
  82406. VirtualJoystick.vjCanvasContext.closePath();
  82407. VirtualJoystick.vjCanvasContext.beginPath();
  82408. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82409. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82410. VirtualJoystick.vjCanvasContext.stroke();
  82411. VirtualJoystick.vjCanvasContext.closePath();
  82412. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82413. }
  82414. else {
  82415. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82416. VirtualJoystick.vjCanvasContext.beginPath();
  82417. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82418. VirtualJoystick.vjCanvasContext.beginPath();
  82419. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82420. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82421. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82422. VirtualJoystick.vjCanvasContext.stroke();
  82423. VirtualJoystick.vjCanvasContext.closePath();
  82424. touch.prevX = touch.x;
  82425. touch.prevY = touch.y;
  82426. }
  82427. ;
  82428. });
  82429. }
  82430. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82431. };
  82432. VirtualJoystick.prototype.releaseCanvas = function () {
  82433. if (VirtualJoystick.vjCanvas) {
  82434. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82435. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82436. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82437. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82438. window.removeEventListener("resize", this._onResize);
  82439. document.body.removeChild(VirtualJoystick.vjCanvas);
  82440. VirtualJoystick.vjCanvas = null;
  82441. }
  82442. };
  82443. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82444. VirtualJoystick._globalJoystickIndex = 0;
  82445. return VirtualJoystick;
  82446. }());
  82447. BABYLON.VirtualJoystick = VirtualJoystick;
  82448. })(BABYLON || (BABYLON = {}));
  82449. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82450. var BABYLON;
  82451. (function (BABYLON) {
  82452. // We're mainly based on the logic defined into the FreeCamera code
  82453. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82454. __extends(VirtualJoysticksCamera, _super);
  82455. function VirtualJoysticksCamera(name, position, scene) {
  82456. var _this = _super.call(this, name, position, scene) || this;
  82457. _this.inputs.addVirtualJoystick();
  82458. return _this;
  82459. }
  82460. VirtualJoysticksCamera.prototype.getClassName = function () {
  82461. return "VirtualJoysticksCamera";
  82462. };
  82463. return VirtualJoysticksCamera;
  82464. }(BABYLON.FreeCamera));
  82465. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82466. })(BABYLON || (BABYLON = {}));
  82467. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82468. var BABYLON;
  82469. (function (BABYLON) {
  82470. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82471. function FreeCameraVirtualJoystickInput() {
  82472. }
  82473. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82474. return this._leftjoystick;
  82475. };
  82476. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82477. return this._rightjoystick;
  82478. };
  82479. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82480. if (this._leftjoystick) {
  82481. var camera = this.camera;
  82482. var speed = camera._computeLocalCameraSpeed() * 50;
  82483. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82484. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82485. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82486. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82487. if (!this._leftjoystick.pressed) {
  82488. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82489. }
  82490. if (!this._rightjoystick.pressed) {
  82491. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82492. }
  82493. }
  82494. };
  82495. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82496. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82497. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82498. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82499. this._leftjoystick.setJoystickSensibility(0.15);
  82500. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82501. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82502. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82503. this._rightjoystick.reverseUpDown = true;
  82504. this._rightjoystick.setJoystickSensibility(0.05);
  82505. this._rightjoystick.setJoystickColor("yellow");
  82506. };
  82507. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82508. this._leftjoystick.releaseCanvas();
  82509. this._rightjoystick.releaseCanvas();
  82510. };
  82511. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82512. return "FreeCameraVirtualJoystickInput";
  82513. };
  82514. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82515. return "virtualJoystick";
  82516. };
  82517. return FreeCameraVirtualJoystickInput;
  82518. }());
  82519. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82520. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82521. })(BABYLON || (BABYLON = {}));
  82522. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82523. var BABYLON;
  82524. (function (BABYLON) {
  82525. var SimplificationSettings = /** @class */ (function () {
  82526. function SimplificationSettings(quality, distance, optimizeMesh) {
  82527. this.quality = quality;
  82528. this.distance = distance;
  82529. this.optimizeMesh = optimizeMesh;
  82530. }
  82531. return SimplificationSettings;
  82532. }());
  82533. BABYLON.SimplificationSettings = SimplificationSettings;
  82534. var SimplificationQueue = /** @class */ (function () {
  82535. function SimplificationQueue() {
  82536. this.running = false;
  82537. this._simplificationArray = [];
  82538. }
  82539. SimplificationQueue.prototype.addTask = function (task) {
  82540. this._simplificationArray.push(task);
  82541. };
  82542. SimplificationQueue.prototype.executeNext = function () {
  82543. var task = this._simplificationArray.pop();
  82544. if (task) {
  82545. this.running = true;
  82546. this.runSimplification(task);
  82547. }
  82548. else {
  82549. this.running = false;
  82550. }
  82551. };
  82552. SimplificationQueue.prototype.runSimplification = function (task) {
  82553. var _this = this;
  82554. if (task.parallelProcessing) {
  82555. //parallel simplifier
  82556. task.settings.forEach(function (setting) {
  82557. var simplifier = _this.getSimplifier(task);
  82558. simplifier.simplify(setting, function (newMesh) {
  82559. task.mesh.addLODLevel(setting.distance, newMesh);
  82560. newMesh.isVisible = true;
  82561. //check if it is the last
  82562. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82563. //all done, run the success callback.
  82564. task.successCallback();
  82565. }
  82566. _this.executeNext();
  82567. });
  82568. });
  82569. }
  82570. else {
  82571. //single simplifier.
  82572. var simplifier = this.getSimplifier(task);
  82573. var runDecimation = function (setting, callback) {
  82574. simplifier.simplify(setting, function (newMesh) {
  82575. task.mesh.addLODLevel(setting.distance, newMesh);
  82576. newMesh.isVisible = true;
  82577. //run the next quality level
  82578. callback();
  82579. });
  82580. };
  82581. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82582. runDecimation(task.settings[loop.index], function () {
  82583. loop.executeNext();
  82584. });
  82585. }, function () {
  82586. //execution ended, run the success callback.
  82587. if (task.successCallback) {
  82588. task.successCallback();
  82589. }
  82590. _this.executeNext();
  82591. });
  82592. }
  82593. };
  82594. SimplificationQueue.prototype.getSimplifier = function (task) {
  82595. switch (task.simplificationType) {
  82596. case SimplificationType.QUADRATIC:
  82597. default:
  82598. return new QuadraticErrorSimplification(task.mesh);
  82599. }
  82600. };
  82601. return SimplificationQueue;
  82602. }());
  82603. BABYLON.SimplificationQueue = SimplificationQueue;
  82604. /**
  82605. * The implemented types of simplification.
  82606. * At the moment only Quadratic Error Decimation is implemented.
  82607. */
  82608. var SimplificationType;
  82609. (function (SimplificationType) {
  82610. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82611. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82612. var DecimationTriangle = /** @class */ (function () {
  82613. function DecimationTriangle(vertices) {
  82614. this.vertices = vertices;
  82615. this.error = new Array(4);
  82616. this.deleted = false;
  82617. this.isDirty = false;
  82618. this.deletePending = false;
  82619. this.borderFactor = 0;
  82620. }
  82621. return DecimationTriangle;
  82622. }());
  82623. BABYLON.DecimationTriangle = DecimationTriangle;
  82624. var DecimationVertex = /** @class */ (function () {
  82625. function DecimationVertex(position, id) {
  82626. this.position = position;
  82627. this.id = id;
  82628. this.isBorder = true;
  82629. this.q = new QuadraticMatrix();
  82630. this.triangleCount = 0;
  82631. this.triangleStart = 0;
  82632. this.originalOffsets = [];
  82633. }
  82634. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82635. this.position.copyFrom(newPosition);
  82636. };
  82637. return DecimationVertex;
  82638. }());
  82639. BABYLON.DecimationVertex = DecimationVertex;
  82640. var QuadraticMatrix = /** @class */ (function () {
  82641. function QuadraticMatrix(data) {
  82642. this.data = new Array(10);
  82643. for (var i = 0; i < 10; ++i) {
  82644. if (data && data[i]) {
  82645. this.data[i] = data[i];
  82646. }
  82647. else {
  82648. this.data[i] = 0;
  82649. }
  82650. }
  82651. }
  82652. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82653. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82654. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82655. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82656. return det;
  82657. };
  82658. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82659. for (var i = 0; i < 10; ++i) {
  82660. this.data[i] += matrix.data[i];
  82661. }
  82662. };
  82663. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82664. for (var i = 0; i < 10; ++i) {
  82665. this.data[i] += data[i];
  82666. }
  82667. };
  82668. QuadraticMatrix.prototype.add = function (matrix) {
  82669. var m = new QuadraticMatrix();
  82670. for (var i = 0; i < 10; ++i) {
  82671. m.data[i] = this.data[i] + matrix.data[i];
  82672. }
  82673. return m;
  82674. };
  82675. QuadraticMatrix.FromData = function (a, b, c, d) {
  82676. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82677. };
  82678. //returning an array to avoid garbage collection
  82679. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82680. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82681. };
  82682. return QuadraticMatrix;
  82683. }());
  82684. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82685. var Reference = /** @class */ (function () {
  82686. function Reference(vertexId, triangleId) {
  82687. this.vertexId = vertexId;
  82688. this.triangleId = triangleId;
  82689. }
  82690. return Reference;
  82691. }());
  82692. BABYLON.Reference = Reference;
  82693. /**
  82694. * An implementation of the Quadratic Error simplification algorithm.
  82695. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82696. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82697. * @author RaananW
  82698. */
  82699. var QuadraticErrorSimplification = /** @class */ (function () {
  82700. function QuadraticErrorSimplification(_mesh) {
  82701. this._mesh = _mesh;
  82702. this.syncIterations = 5000;
  82703. this.aggressiveness = 7;
  82704. this.decimationIterations = 100;
  82705. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82706. }
  82707. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82708. var _this = this;
  82709. this.initDecimatedMesh();
  82710. //iterating through the submeshes array, one after the other.
  82711. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82712. _this.initWithMesh(loop.index, function () {
  82713. _this.runDecimation(settings, loop.index, function () {
  82714. loop.executeNext();
  82715. });
  82716. }, settings.optimizeMesh);
  82717. }, function () {
  82718. setTimeout(function () {
  82719. successCallback(_this._reconstructedMesh);
  82720. }, 0);
  82721. });
  82722. };
  82723. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82724. var _this = this;
  82725. var targetCount = ~~(this.triangles.length * settings.quality);
  82726. var deletedTriangles = 0;
  82727. var triangleCount = this.triangles.length;
  82728. var iterationFunction = function (iteration, callback) {
  82729. setTimeout(function () {
  82730. if (iteration % 5 === 0) {
  82731. _this.updateMesh(iteration === 0);
  82732. }
  82733. for (var i = 0; i < _this.triangles.length; ++i) {
  82734. _this.triangles[i].isDirty = false;
  82735. }
  82736. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82737. var trianglesIterator = function (i) {
  82738. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82739. var t = _this.triangles[tIdx];
  82740. if (!t)
  82741. return;
  82742. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82743. return;
  82744. }
  82745. for (var j = 0; j < 3; ++j) {
  82746. if (t.error[j] < threshold) {
  82747. var deleted0 = [];
  82748. var deleted1 = [];
  82749. var v0 = t.vertices[j];
  82750. var v1 = t.vertices[(j + 1) % 3];
  82751. if (v0.isBorder || v1.isBorder)
  82752. continue;
  82753. var p = BABYLON.Vector3.Zero();
  82754. var n = BABYLON.Vector3.Zero();
  82755. var uv = BABYLON.Vector2.Zero();
  82756. var color = new BABYLON.Color4(0, 0, 0, 1);
  82757. _this.calculateError(v0, v1, p, n, uv, color);
  82758. var delTr = new Array();
  82759. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82760. continue;
  82761. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82762. continue;
  82763. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82764. continue;
  82765. var uniqueArray = new Array();
  82766. delTr.forEach(function (deletedT) {
  82767. if (uniqueArray.indexOf(deletedT) === -1) {
  82768. deletedT.deletePending = true;
  82769. uniqueArray.push(deletedT);
  82770. }
  82771. });
  82772. if (uniqueArray.length % 2 !== 0) {
  82773. continue;
  82774. }
  82775. v0.q = v1.q.add(v0.q);
  82776. v0.updatePosition(p);
  82777. var tStart = _this.references.length;
  82778. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82779. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82780. var tCount = _this.references.length - tStart;
  82781. if (tCount <= v0.triangleCount) {
  82782. if (tCount) {
  82783. for (var c = 0; c < tCount; c++) {
  82784. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82785. }
  82786. }
  82787. }
  82788. else {
  82789. v0.triangleStart = tStart;
  82790. }
  82791. v0.triangleCount = tCount;
  82792. break;
  82793. }
  82794. }
  82795. };
  82796. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82797. }, 0);
  82798. };
  82799. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82800. if (triangleCount - deletedTriangles <= targetCount)
  82801. loop.breakLoop();
  82802. else {
  82803. iterationFunction(loop.index, function () {
  82804. loop.executeNext();
  82805. });
  82806. }
  82807. }, function () {
  82808. setTimeout(function () {
  82809. //reconstruct this part of the mesh
  82810. _this.reconstructMesh(submeshIndex);
  82811. successCallback();
  82812. }, 0);
  82813. });
  82814. };
  82815. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82816. var _this = this;
  82817. this.vertices = [];
  82818. this.triangles = [];
  82819. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82820. var indices = this._mesh.getIndices();
  82821. var submesh = this._mesh.subMeshes[submeshIndex];
  82822. var findInVertices = function (positionToSearch) {
  82823. if (optimizeMesh) {
  82824. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82825. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82826. return _this.vertices[ii];
  82827. }
  82828. }
  82829. }
  82830. return null;
  82831. };
  82832. var vertexReferences = [];
  82833. var vertexInit = function (i) {
  82834. if (!positionData) {
  82835. return;
  82836. }
  82837. var offset = i + submesh.verticesStart;
  82838. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82839. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82840. vertex.originalOffsets.push(offset);
  82841. if (vertex.id === _this.vertices.length) {
  82842. _this.vertices.push(vertex);
  82843. }
  82844. vertexReferences.push(vertex.id);
  82845. };
  82846. //var totalVertices = mesh.getTotalVertices();
  82847. var totalVertices = submesh.verticesCount;
  82848. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82849. var indicesInit = function (i) {
  82850. if (!indices) {
  82851. return;
  82852. }
  82853. var offset = (submesh.indexStart / 3) + i;
  82854. var pos = (offset * 3);
  82855. var i0 = indices[pos + 0];
  82856. var i1 = indices[pos + 1];
  82857. var i2 = indices[pos + 2];
  82858. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82859. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82860. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82861. var triangle = new DecimationTriangle([v0, v1, v2]);
  82862. triangle.originalOffset = pos;
  82863. _this.triangles.push(triangle);
  82864. };
  82865. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82866. _this.init(callback);
  82867. });
  82868. });
  82869. };
  82870. QuadraticErrorSimplification.prototype.init = function (callback) {
  82871. var _this = this;
  82872. var triangleInit1 = function (i) {
  82873. var t = _this.triangles[i];
  82874. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82875. for (var j = 0; j < 3; j++) {
  82876. 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))));
  82877. }
  82878. };
  82879. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82880. var triangleInit2 = function (i) {
  82881. var t = _this.triangles[i];
  82882. for (var j = 0; j < 3; ++j) {
  82883. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82884. }
  82885. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82886. };
  82887. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82888. callback();
  82889. });
  82890. });
  82891. };
  82892. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82893. var newTriangles = [];
  82894. var i;
  82895. for (i = 0; i < this.vertices.length; ++i) {
  82896. this.vertices[i].triangleCount = 0;
  82897. }
  82898. var t;
  82899. var j;
  82900. for (i = 0; i < this.triangles.length; ++i) {
  82901. if (!this.triangles[i].deleted) {
  82902. t = this.triangles[i];
  82903. for (j = 0; j < 3; ++j) {
  82904. t.vertices[j].triangleCount = 1;
  82905. }
  82906. newTriangles.push(t);
  82907. }
  82908. }
  82909. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82910. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82911. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82912. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82913. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82914. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82915. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82916. var vertexCount = 0;
  82917. for (i = 0; i < this.vertices.length; ++i) {
  82918. var vertex = this.vertices[i];
  82919. vertex.id = vertexCount;
  82920. if (vertex.triangleCount) {
  82921. vertex.originalOffsets.forEach(function (originalOffset) {
  82922. if (!normalData) {
  82923. return;
  82924. }
  82925. newPositionData.push(vertex.position.x);
  82926. newPositionData.push(vertex.position.y);
  82927. newPositionData.push(vertex.position.z);
  82928. newNormalData.push(normalData[originalOffset * 3]);
  82929. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82930. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82931. if (uvs && uvs.length) {
  82932. newUVsData.push(uvs[(originalOffset * 2)]);
  82933. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82934. }
  82935. else if (colorsData && colorsData.length) {
  82936. newColorsData.push(colorsData[(originalOffset * 4)]);
  82937. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82938. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82939. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82940. }
  82941. ++vertexCount;
  82942. });
  82943. }
  82944. }
  82945. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82946. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82947. var submeshesArray = this._reconstructedMesh.subMeshes;
  82948. this._reconstructedMesh.subMeshes = [];
  82949. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82950. var originalIndices = this._mesh.getIndices();
  82951. for (i = 0; i < newTriangles.length; ++i) {
  82952. t = newTriangles[i]; //now get the new referencing point for each vertex
  82953. [0, 1, 2].forEach(function (idx) {
  82954. var id = originalIndices[t.originalOffset + idx];
  82955. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82956. if (offset < 0)
  82957. offset = 0;
  82958. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82959. });
  82960. }
  82961. //overwriting the old vertex buffers and indices.
  82962. this._reconstructedMesh.setIndices(newIndicesArray);
  82963. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82964. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82965. if (newUVsData.length > 0)
  82966. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82967. if (newColorsData.length > 0)
  82968. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82969. //create submesh
  82970. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82971. if (submeshIndex > 0) {
  82972. this._reconstructedMesh.subMeshes = [];
  82973. submeshesArray.forEach(function (submesh) {
  82974. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82975. });
  82976. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82977. }
  82978. };
  82979. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82980. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82981. this._reconstructedMesh.material = this._mesh.material;
  82982. this._reconstructedMesh.parent = this._mesh.parent;
  82983. this._reconstructedMesh.isVisible = false;
  82984. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82985. };
  82986. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82987. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82988. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82989. if (t.deleted)
  82990. continue;
  82991. var s = this.references[vertex1.triangleStart + i].vertexId;
  82992. var v1 = t.vertices[(s + 1) % 3];
  82993. var v2 = t.vertices[(s + 2) % 3];
  82994. if ((v1 === vertex2 || v2 === vertex2)) {
  82995. deletedArray[i] = true;
  82996. delTr.push(t);
  82997. continue;
  82998. }
  82999. var d1 = v1.position.subtract(point);
  83000. d1 = d1.normalize();
  83001. var d2 = v2.position.subtract(point);
  83002. d2 = d2.normalize();
  83003. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83004. return true;
  83005. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83006. deletedArray[i] = false;
  83007. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83008. return true;
  83009. }
  83010. return false;
  83011. };
  83012. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83013. var newDeleted = deletedTriangles;
  83014. for (var i = 0; i < vertex.triangleCount; ++i) {
  83015. var ref = this.references[vertex.triangleStart + i];
  83016. var t = this.triangles[ref.triangleId];
  83017. if (t.deleted)
  83018. continue;
  83019. if (deletedArray[i] && t.deletePending) {
  83020. t.deleted = true;
  83021. newDeleted++;
  83022. continue;
  83023. }
  83024. t.vertices[ref.vertexId] = origVertex;
  83025. t.isDirty = true;
  83026. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83027. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83028. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83029. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83030. this.references.push(ref);
  83031. }
  83032. return newDeleted;
  83033. };
  83034. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83035. for (var i = 0; i < this.vertices.length; ++i) {
  83036. var vCount = [];
  83037. var vId = [];
  83038. var v = this.vertices[i];
  83039. var j;
  83040. for (j = 0; j < v.triangleCount; ++j) {
  83041. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83042. for (var ii = 0; ii < 3; ii++) {
  83043. var ofs = 0;
  83044. var vv = triangle.vertices[ii];
  83045. while (ofs < vCount.length) {
  83046. if (vId[ofs] === vv.id)
  83047. break;
  83048. ++ofs;
  83049. }
  83050. if (ofs === vCount.length) {
  83051. vCount.push(1);
  83052. vId.push(vv.id);
  83053. }
  83054. else {
  83055. vCount[ofs]++;
  83056. }
  83057. }
  83058. }
  83059. for (j = 0; j < vCount.length; ++j) {
  83060. if (vCount[j] === 1) {
  83061. this.vertices[vId[j]].isBorder = true;
  83062. }
  83063. else {
  83064. this.vertices[vId[j]].isBorder = false;
  83065. }
  83066. }
  83067. }
  83068. };
  83069. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83070. if (identifyBorders === void 0) { identifyBorders = false; }
  83071. var i;
  83072. if (!identifyBorders) {
  83073. var newTrianglesVector = [];
  83074. for (i = 0; i < this.triangles.length; ++i) {
  83075. if (!this.triangles[i].deleted) {
  83076. newTrianglesVector.push(this.triangles[i]);
  83077. }
  83078. }
  83079. this.triangles = newTrianglesVector;
  83080. }
  83081. for (i = 0; i < this.vertices.length; ++i) {
  83082. this.vertices[i].triangleCount = 0;
  83083. this.vertices[i].triangleStart = 0;
  83084. }
  83085. var t;
  83086. var j;
  83087. var v;
  83088. for (i = 0; i < this.triangles.length; ++i) {
  83089. t = this.triangles[i];
  83090. for (j = 0; j < 3; ++j) {
  83091. v = t.vertices[j];
  83092. v.triangleCount++;
  83093. }
  83094. }
  83095. var tStart = 0;
  83096. for (i = 0; i < this.vertices.length; ++i) {
  83097. this.vertices[i].triangleStart = tStart;
  83098. tStart += this.vertices[i].triangleCount;
  83099. this.vertices[i].triangleCount = 0;
  83100. }
  83101. var newReferences = new Array(this.triangles.length * 3);
  83102. for (i = 0; i < this.triangles.length; ++i) {
  83103. t = this.triangles[i];
  83104. for (j = 0; j < 3; ++j) {
  83105. v = t.vertices[j];
  83106. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83107. v.triangleCount++;
  83108. }
  83109. }
  83110. this.references = newReferences;
  83111. if (identifyBorders) {
  83112. this.identifyBorder();
  83113. }
  83114. };
  83115. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83116. var x = point.x;
  83117. var y = point.y;
  83118. var z = point.z;
  83119. 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
  83120. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83121. };
  83122. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83123. var q = vertex1.q.add(vertex2.q);
  83124. var border = vertex1.isBorder && vertex2.isBorder;
  83125. var error = 0;
  83126. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83127. if (qDet !== 0 && !border) {
  83128. if (!pointResult) {
  83129. pointResult = BABYLON.Vector3.Zero();
  83130. }
  83131. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83132. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83133. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83134. error = this.vertexError(q, pointResult);
  83135. }
  83136. else {
  83137. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83138. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83139. var error1 = this.vertexError(q, vertex1.position);
  83140. var error2 = this.vertexError(q, vertex2.position);
  83141. var error3 = this.vertexError(q, p3);
  83142. error = Math.min(error1, error2, error3);
  83143. if (error === error1) {
  83144. if (pointResult) {
  83145. pointResult.copyFrom(vertex1.position);
  83146. }
  83147. }
  83148. else if (error === error2) {
  83149. if (pointResult) {
  83150. pointResult.copyFrom(vertex2.position);
  83151. }
  83152. }
  83153. else {
  83154. if (pointResult) {
  83155. pointResult.copyFrom(p3);
  83156. }
  83157. }
  83158. }
  83159. return error;
  83160. };
  83161. return QuadraticErrorSimplification;
  83162. }());
  83163. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83164. })(BABYLON || (BABYLON = {}));
  83165. //# sourceMappingURL=babylon.meshSimplification.js.map
  83166. var BABYLON;
  83167. (function (BABYLON) {
  83168. var MeshLODLevel = /** @class */ (function () {
  83169. function MeshLODLevel(distance, mesh) {
  83170. this.distance = distance;
  83171. this.mesh = mesh;
  83172. }
  83173. return MeshLODLevel;
  83174. }());
  83175. BABYLON.MeshLODLevel = MeshLODLevel;
  83176. })(BABYLON || (BABYLON = {}));
  83177. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83178. var BABYLON;
  83179. (function (BABYLON) {
  83180. /**
  83181. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83182. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83183. */
  83184. var SceneOptimization = /** @class */ (function () {
  83185. /**
  83186. * Creates the SceneOptimization object
  83187. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83188. * @param desc defines the description associated with the optimization
  83189. */
  83190. function SceneOptimization(
  83191. /**
  83192. * Defines the priority of this optimization (0 by default which means first in the list)
  83193. */
  83194. priority) {
  83195. if (priority === void 0) { priority = 0; }
  83196. this.priority = priority;
  83197. }
  83198. /**
  83199. * Gets a string describing the action executed by the current optimization
  83200. * @returns description string
  83201. */
  83202. SceneOptimization.prototype.getDescription = function () {
  83203. return "";
  83204. };
  83205. /**
  83206. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83207. * @param scene defines the current scene where to apply this optimization
  83208. * @param optimizer defines the current optimizer
  83209. * @returns true if everything that can be done was applied
  83210. */
  83211. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83212. return true;
  83213. };
  83214. ;
  83215. return SceneOptimization;
  83216. }());
  83217. BABYLON.SceneOptimization = SceneOptimization;
  83218. /**
  83219. * Defines an optimization used to reduce the size of render target textures
  83220. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83221. */
  83222. var TextureOptimization = /** @class */ (function (_super) {
  83223. __extends(TextureOptimization, _super);
  83224. /**
  83225. * Creates the TextureOptimization object
  83226. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83227. * @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
  83228. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83229. */
  83230. function TextureOptimization(
  83231. /**
  83232. * Defines the priority of this optimization (0 by default which means first in the list)
  83233. */
  83234. priority,
  83235. /**
  83236. * 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
  83237. */
  83238. maximumSize,
  83239. /**
  83240. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83241. */
  83242. step) {
  83243. if (priority === void 0) { priority = 0; }
  83244. if (maximumSize === void 0) { maximumSize = 1024; }
  83245. if (step === void 0) { step = 0.5; }
  83246. var _this = _super.call(this, priority) || this;
  83247. _this.priority = priority;
  83248. _this.maximumSize = maximumSize;
  83249. _this.step = step;
  83250. return _this;
  83251. }
  83252. /**
  83253. * Gets a string describing the action executed by the current optimization
  83254. * @returns description string
  83255. */
  83256. TextureOptimization.prototype.getDescription = function () {
  83257. return "Reducing render target texture size to " + this.maximumSize;
  83258. };
  83259. /**
  83260. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83261. * @param scene defines the current scene where to apply this optimization
  83262. * @param optimizer defines the current optimizer
  83263. * @returns true if everything that can be done was applied
  83264. */
  83265. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83266. var allDone = true;
  83267. for (var index = 0; index < scene.textures.length; index++) {
  83268. var texture = scene.textures[index];
  83269. if (!texture.canRescale || texture.getContext) {
  83270. continue;
  83271. }
  83272. var currentSize = texture.getSize();
  83273. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83274. if (maxDimension > this.maximumSize) {
  83275. texture.scale(this.step);
  83276. allDone = false;
  83277. }
  83278. }
  83279. return allDone;
  83280. };
  83281. return TextureOptimization;
  83282. }(SceneOptimization));
  83283. BABYLON.TextureOptimization = TextureOptimization;
  83284. /**
  83285. * Defines an optimization used to increase or decrease the rendering resolution
  83286. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83287. */
  83288. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83289. __extends(HardwareScalingOptimization, _super);
  83290. /**
  83291. * Creates the HardwareScalingOptimization object
  83292. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83293. * @param maximumScale defines the maximum scale to use (2 by default)
  83294. * @param step defines the step to use between two passes (0.5 by default)
  83295. */
  83296. function HardwareScalingOptimization(
  83297. /**
  83298. * Defines the priority of this optimization (0 by default which means first in the list)
  83299. */
  83300. priority,
  83301. /**
  83302. * Defines the maximum scale to use (2 by default)
  83303. */
  83304. maximumScale,
  83305. /**
  83306. * Defines the step to use between two passes (0.5 by default)
  83307. */
  83308. step) {
  83309. if (priority === void 0) { priority = 0; }
  83310. if (maximumScale === void 0) { maximumScale = 2; }
  83311. if (step === void 0) { step = 0.25; }
  83312. var _this = _super.call(this, priority) || this;
  83313. _this.priority = priority;
  83314. _this.maximumScale = maximumScale;
  83315. _this.step = step;
  83316. _this._currentScale = -1;
  83317. _this._directionOffset = 1;
  83318. return _this;
  83319. }
  83320. /**
  83321. * Gets a string describing the action executed by the current optimization
  83322. * @return description string
  83323. */
  83324. HardwareScalingOptimization.prototype.getDescription = function () {
  83325. return "Setting hardware scaling level to " + this._currentScale;
  83326. };
  83327. /**
  83328. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83329. * @param scene defines the current scene where to apply this optimization
  83330. * @param optimizer defines the current optimizer
  83331. * @returns true if everything that can be done was applied
  83332. */
  83333. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83334. if (this._currentScale === -1) {
  83335. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83336. if (this._currentScale > this.maximumScale) {
  83337. this._directionOffset = -1;
  83338. }
  83339. }
  83340. this._currentScale += this._directionOffset * this.step;
  83341. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83342. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83343. };
  83344. ;
  83345. return HardwareScalingOptimization;
  83346. }(SceneOptimization));
  83347. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83348. /**
  83349. * Defines an optimization used to remove shadows
  83350. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83351. */
  83352. var ShadowsOptimization = /** @class */ (function (_super) {
  83353. __extends(ShadowsOptimization, _super);
  83354. function ShadowsOptimization() {
  83355. return _super !== null && _super.apply(this, arguments) || this;
  83356. }
  83357. /**
  83358. * Gets a string describing the action executed by the current optimization
  83359. * @return description string
  83360. */
  83361. ShadowsOptimization.prototype.getDescription = function () {
  83362. return "Turning shadows on/off";
  83363. };
  83364. /**
  83365. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83366. * @param scene defines the current scene where to apply this optimization
  83367. * @param optimizer defines the current optimizer
  83368. * @returns true if everything that can be done was applied
  83369. */
  83370. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83371. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83372. return true;
  83373. };
  83374. ;
  83375. return ShadowsOptimization;
  83376. }(SceneOptimization));
  83377. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83378. /**
  83379. * Defines an optimization used to turn post-processes off
  83380. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83381. */
  83382. var PostProcessesOptimization = /** @class */ (function (_super) {
  83383. __extends(PostProcessesOptimization, _super);
  83384. function PostProcessesOptimization() {
  83385. return _super !== null && _super.apply(this, arguments) || this;
  83386. }
  83387. /**
  83388. * Gets a string describing the action executed by the current optimization
  83389. * @return description string
  83390. */
  83391. PostProcessesOptimization.prototype.getDescription = function () {
  83392. return "Turning post-processes on/off";
  83393. };
  83394. /**
  83395. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83396. * @param scene defines the current scene where to apply this optimization
  83397. * @param optimizer defines the current optimizer
  83398. * @returns true if everything that can be done was applied
  83399. */
  83400. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83401. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83402. return true;
  83403. };
  83404. ;
  83405. return PostProcessesOptimization;
  83406. }(SceneOptimization));
  83407. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83408. /**
  83409. * Defines an optimization used to turn lens flares off
  83410. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83411. */
  83412. var LensFlaresOptimization = /** @class */ (function (_super) {
  83413. __extends(LensFlaresOptimization, _super);
  83414. function LensFlaresOptimization() {
  83415. return _super !== null && _super.apply(this, arguments) || this;
  83416. }
  83417. /**
  83418. * Gets a string describing the action executed by the current optimization
  83419. * @return description string
  83420. */
  83421. LensFlaresOptimization.prototype.getDescription = function () {
  83422. return "Turning lens flares on/off";
  83423. };
  83424. /**
  83425. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83426. * @param scene defines the current scene where to apply this optimization
  83427. * @param optimizer defines the current optimizer
  83428. * @returns true if everything that can be done was applied
  83429. */
  83430. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83431. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83432. return true;
  83433. };
  83434. ;
  83435. return LensFlaresOptimization;
  83436. }(SceneOptimization));
  83437. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83438. /**
  83439. * Defines an optimization based on user defined callback.
  83440. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83441. */
  83442. var CustomOptimization = /** @class */ (function (_super) {
  83443. __extends(CustomOptimization, _super);
  83444. function CustomOptimization() {
  83445. return _super !== null && _super.apply(this, arguments) || this;
  83446. }
  83447. /**
  83448. * Gets a string describing the action executed by the current optimization
  83449. * @returns description string
  83450. */
  83451. CustomOptimization.prototype.getDescription = function () {
  83452. if (this.onGetDescription) {
  83453. return this.onGetDescription();
  83454. }
  83455. return "Running user defined callback";
  83456. };
  83457. /**
  83458. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83459. * @param scene defines the current scene where to apply this optimization
  83460. * @param optimizer defines the current optimizer
  83461. * @returns true if everything that can be done was applied
  83462. */
  83463. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83464. if (this.onApply) {
  83465. return this.onApply(scene, optimizer);
  83466. }
  83467. return true;
  83468. };
  83469. ;
  83470. return CustomOptimization;
  83471. }(SceneOptimization));
  83472. BABYLON.CustomOptimization = CustomOptimization;
  83473. /**
  83474. * Defines an optimization used to turn particles off
  83475. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83476. */
  83477. var ParticlesOptimization = /** @class */ (function (_super) {
  83478. __extends(ParticlesOptimization, _super);
  83479. function ParticlesOptimization() {
  83480. return _super !== null && _super.apply(this, arguments) || this;
  83481. }
  83482. /**
  83483. * Gets a string describing the action executed by the current optimization
  83484. * @return description string
  83485. */
  83486. ParticlesOptimization.prototype.getDescription = function () {
  83487. return "Turning particles on/off";
  83488. };
  83489. /**
  83490. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83491. * @param scene defines the current scene where to apply this optimization
  83492. * @param optimizer defines the current optimizer
  83493. * @returns true if everything that can be done was applied
  83494. */
  83495. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83496. scene.particlesEnabled = optimizer.isInImprovementMode;
  83497. return true;
  83498. };
  83499. ;
  83500. return ParticlesOptimization;
  83501. }(SceneOptimization));
  83502. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83503. /**
  83504. * Defines an optimization used to turn render targets off
  83505. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83506. */
  83507. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83508. __extends(RenderTargetsOptimization, _super);
  83509. function RenderTargetsOptimization() {
  83510. return _super !== null && _super.apply(this, arguments) || this;
  83511. }
  83512. /**
  83513. * Gets a string describing the action executed by the current optimization
  83514. * @return description string
  83515. */
  83516. RenderTargetsOptimization.prototype.getDescription = function () {
  83517. return "Turning render targets off";
  83518. };
  83519. /**
  83520. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83521. * @param scene defines the current scene where to apply this optimization
  83522. * @param optimizer defines the current optimizer
  83523. * @returns true if everything that can be done was applied
  83524. */
  83525. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83526. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83527. return true;
  83528. };
  83529. ;
  83530. return RenderTargetsOptimization;
  83531. }(SceneOptimization));
  83532. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83533. /**
  83534. * Defines an optimization used to merge meshes with compatible materials
  83535. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83536. */
  83537. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83538. __extends(MergeMeshesOptimization, _super);
  83539. function MergeMeshesOptimization() {
  83540. var _this = _super !== null && _super.apply(this, arguments) || this;
  83541. _this._canBeMerged = function (abstractMesh) {
  83542. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83543. return false;
  83544. }
  83545. var mesh = abstractMesh;
  83546. if (!mesh.isVisible || !mesh.isEnabled()) {
  83547. return false;
  83548. }
  83549. if (mesh.instances.length > 0) {
  83550. return false;
  83551. }
  83552. if (mesh.skeleton || mesh.hasLODLevels) {
  83553. return false;
  83554. }
  83555. if (mesh.parent) {
  83556. return false;
  83557. }
  83558. return true;
  83559. };
  83560. return _this;
  83561. }
  83562. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83563. /**
  83564. * Gets or sets a boolean which defines if optimization octree has to be updated
  83565. */
  83566. get: function () {
  83567. return MergeMeshesOptimization._UpdateSelectionTree;
  83568. },
  83569. /**
  83570. * Gets or sets a boolean which defines if optimization octree has to be updated
  83571. */
  83572. set: function (value) {
  83573. MergeMeshesOptimization._UpdateSelectionTree = value;
  83574. },
  83575. enumerable: true,
  83576. configurable: true
  83577. });
  83578. /**
  83579. * Gets a string describing the action executed by the current optimization
  83580. * @return description string
  83581. */
  83582. MergeMeshesOptimization.prototype.getDescription = function () {
  83583. return "Merging similar meshes together";
  83584. };
  83585. /**
  83586. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83587. * @param scene defines the current scene where to apply this optimization
  83588. * @param optimizer defines the current optimizer
  83589. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83590. * @returns true if everything that can be done was applied
  83591. */
  83592. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83593. var globalPool = scene.meshes.slice(0);
  83594. var globalLength = globalPool.length;
  83595. for (var index = 0; index < globalLength; index++) {
  83596. var currentPool = new Array();
  83597. var current = globalPool[index];
  83598. // Checks
  83599. if (!this._canBeMerged(current)) {
  83600. continue;
  83601. }
  83602. currentPool.push(current);
  83603. // Find compatible meshes
  83604. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83605. var otherMesh = globalPool[subIndex];
  83606. if (!this._canBeMerged(otherMesh)) {
  83607. continue;
  83608. }
  83609. if (otherMesh.material !== current.material) {
  83610. continue;
  83611. }
  83612. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83613. continue;
  83614. }
  83615. currentPool.push(otherMesh);
  83616. globalLength--;
  83617. globalPool.splice(subIndex, 1);
  83618. subIndex--;
  83619. }
  83620. if (currentPool.length < 2) {
  83621. continue;
  83622. }
  83623. // Merge meshes
  83624. BABYLON.Mesh.MergeMeshes(currentPool);
  83625. }
  83626. if (updateSelectionTree != undefined) {
  83627. if (updateSelectionTree) {
  83628. scene.createOrUpdateSelectionOctree();
  83629. }
  83630. }
  83631. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83632. scene.createOrUpdateSelectionOctree();
  83633. }
  83634. return true;
  83635. };
  83636. ;
  83637. MergeMeshesOptimization._UpdateSelectionTree = false;
  83638. return MergeMeshesOptimization;
  83639. }(SceneOptimization));
  83640. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83641. /**
  83642. * Defines a list of options used by SceneOptimizer
  83643. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83644. */
  83645. var SceneOptimizerOptions = /** @class */ (function () {
  83646. /**
  83647. * Creates a new list of options used by SceneOptimizer
  83648. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83649. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83650. */
  83651. function SceneOptimizerOptions(
  83652. /**
  83653. * Defines the target frame rate to reach (60 by default)
  83654. */
  83655. targetFrameRate,
  83656. /**
  83657. * Defines the interval between two checkes (2000ms by default)
  83658. */
  83659. trackerDuration) {
  83660. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83661. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83662. this.targetFrameRate = targetFrameRate;
  83663. this.trackerDuration = trackerDuration;
  83664. /**
  83665. * Gets the list of optimizations to apply
  83666. */
  83667. this.optimizations = new Array();
  83668. }
  83669. /**
  83670. * Add a new optimization
  83671. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83672. * @returns the current SceneOptimizerOptions
  83673. */
  83674. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83675. this.optimizations.push(optimization);
  83676. return this;
  83677. };
  83678. /**
  83679. * Add a new custom optimization
  83680. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83681. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83682. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83683. * @returns the current SceneOptimizerOptions
  83684. */
  83685. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83686. if (priority === void 0) { priority = 0; }
  83687. var optimization = new CustomOptimization(priority);
  83688. optimization.onApply = onApply;
  83689. optimization.onGetDescription = onGetDescription;
  83690. this.optimizations.push(optimization);
  83691. return this;
  83692. };
  83693. /**
  83694. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83695. * @param targetFrameRate defines the target frame rate (60 by default)
  83696. * @returns a SceneOptimizerOptions object
  83697. */
  83698. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83699. var result = new SceneOptimizerOptions(targetFrameRate);
  83700. var priority = 0;
  83701. result.addOptimization(new MergeMeshesOptimization(priority));
  83702. result.addOptimization(new ShadowsOptimization(priority));
  83703. result.addOptimization(new LensFlaresOptimization(priority));
  83704. // Next priority
  83705. priority++;
  83706. result.addOptimization(new PostProcessesOptimization(priority));
  83707. result.addOptimization(new ParticlesOptimization(priority));
  83708. // Next priority
  83709. priority++;
  83710. result.addOptimization(new TextureOptimization(priority, 1024));
  83711. return result;
  83712. };
  83713. /**
  83714. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83715. * @param targetFrameRate defines the target frame rate (60 by default)
  83716. * @returns a SceneOptimizerOptions object
  83717. */
  83718. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83719. var result = new SceneOptimizerOptions(targetFrameRate);
  83720. var priority = 0;
  83721. result.addOptimization(new MergeMeshesOptimization(priority));
  83722. result.addOptimization(new ShadowsOptimization(priority));
  83723. result.addOptimization(new LensFlaresOptimization(priority));
  83724. // Next priority
  83725. priority++;
  83726. result.addOptimization(new PostProcessesOptimization(priority));
  83727. result.addOptimization(new ParticlesOptimization(priority));
  83728. // Next priority
  83729. priority++;
  83730. result.addOptimization(new TextureOptimization(priority, 512));
  83731. // Next priority
  83732. priority++;
  83733. result.addOptimization(new RenderTargetsOptimization(priority));
  83734. // Next priority
  83735. priority++;
  83736. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83737. return result;
  83738. };
  83739. /**
  83740. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83741. * @param targetFrameRate defines the target frame rate (60 by default)
  83742. * @returns a SceneOptimizerOptions object
  83743. */
  83744. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83745. var result = new SceneOptimizerOptions(targetFrameRate);
  83746. var priority = 0;
  83747. result.addOptimization(new MergeMeshesOptimization(priority));
  83748. result.addOptimization(new ShadowsOptimization(priority));
  83749. result.addOptimization(new LensFlaresOptimization(priority));
  83750. // Next priority
  83751. priority++;
  83752. result.addOptimization(new PostProcessesOptimization(priority));
  83753. result.addOptimization(new ParticlesOptimization(priority));
  83754. // Next priority
  83755. priority++;
  83756. result.addOptimization(new TextureOptimization(priority, 256));
  83757. // Next priority
  83758. priority++;
  83759. result.addOptimization(new RenderTargetsOptimization(priority));
  83760. // Next priority
  83761. priority++;
  83762. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83763. return result;
  83764. };
  83765. return SceneOptimizerOptions;
  83766. }());
  83767. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83768. /**
  83769. * Class used to run optimizations in order to reach a target frame rate
  83770. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83771. */
  83772. var SceneOptimizer = /** @class */ (function () {
  83773. /**
  83774. * Creates a new SceneOptimizer
  83775. * @param scene defines the scene to work on
  83776. * @param options defines the options to use with the SceneOptimizer
  83777. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83778. * @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)
  83779. */
  83780. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83781. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83782. if (improvementMode === void 0) { improvementMode = false; }
  83783. var _this = this;
  83784. this._isRunning = false;
  83785. this._currentPriorityLevel = 0;
  83786. this._targetFrameRate = 60;
  83787. this._trackerDuration = 2000;
  83788. this._currentFrameRate = 0;
  83789. this._improvementMode = false;
  83790. /**
  83791. * Defines an observable called when the optimizer reaches the target frame rate
  83792. */
  83793. this.onSuccessObservable = new BABYLON.Observable();
  83794. /**
  83795. * Defines an observable called when the optimizer enables an optimization
  83796. */
  83797. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83798. /**
  83799. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83800. */
  83801. this.onFailureObservable = new BABYLON.Observable();
  83802. if (!options) {
  83803. this._options = new SceneOptimizerOptions();
  83804. }
  83805. else {
  83806. this._options = options;
  83807. }
  83808. if (this._options.targetFrameRate) {
  83809. this._targetFrameRate = this._options.targetFrameRate;
  83810. }
  83811. if (this._options.trackerDuration) {
  83812. this._trackerDuration = this._options.trackerDuration;
  83813. }
  83814. if (autoGeneratePriorities) {
  83815. var priority = 0;
  83816. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83817. var optim = _a[_i];
  83818. optim.priority = priority++;
  83819. }
  83820. }
  83821. this._improvementMode = improvementMode;
  83822. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83823. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83824. _this._sceneDisposeObserver = null;
  83825. _this.dispose();
  83826. });
  83827. }
  83828. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83829. /**
  83830. * Gets a boolean indicating if the optimizer is in improvement mode
  83831. */
  83832. get: function () {
  83833. return this._improvementMode;
  83834. },
  83835. enumerable: true,
  83836. configurable: true
  83837. });
  83838. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83839. /**
  83840. * Gets the current priority level (0 at start)
  83841. */
  83842. get: function () {
  83843. return this._currentPriorityLevel;
  83844. },
  83845. enumerable: true,
  83846. configurable: true
  83847. });
  83848. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83849. /**
  83850. * Gets the current frame rate checked by the SceneOptimizer
  83851. */
  83852. get: function () {
  83853. return this._currentFrameRate;
  83854. },
  83855. enumerable: true,
  83856. configurable: true
  83857. });
  83858. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83859. /**
  83860. * Gets or sets the current target frame rate (60 by default)
  83861. */
  83862. get: function () {
  83863. return this._targetFrameRate;
  83864. },
  83865. /**
  83866. * Gets or sets the current target frame rate (60 by default)
  83867. */
  83868. set: function (value) {
  83869. this._targetFrameRate = value;
  83870. },
  83871. enumerable: true,
  83872. configurable: true
  83873. });
  83874. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83875. /**
  83876. * Gets or sets the current interval between two checks (every 2000ms by default)
  83877. */
  83878. get: function () {
  83879. return this._trackerDuration;
  83880. },
  83881. /**
  83882. * Gets or sets the current interval between two checks (every 2000ms by default)
  83883. */
  83884. set: function (value) {
  83885. this._trackerDuration = value;
  83886. },
  83887. enumerable: true,
  83888. configurable: true
  83889. });
  83890. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83891. /**
  83892. * Gets the list of active optimizations
  83893. */
  83894. get: function () {
  83895. return this._options.optimizations;
  83896. },
  83897. enumerable: true,
  83898. configurable: true
  83899. });
  83900. /**
  83901. * Stops the current optimizer
  83902. */
  83903. SceneOptimizer.prototype.stop = function () {
  83904. this._isRunning = false;
  83905. };
  83906. /**
  83907. * Reset the optimizer to initial step (current priority level = 0)
  83908. */
  83909. SceneOptimizer.prototype.reset = function () {
  83910. this._currentPriorityLevel = 0;
  83911. };
  83912. /**
  83913. * Start the optimizer. By default it will try to reach a specific framerate
  83914. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83915. */
  83916. SceneOptimizer.prototype.start = function () {
  83917. var _this = this;
  83918. if (this._isRunning) {
  83919. return;
  83920. }
  83921. this._isRunning = true;
  83922. // Let's wait for the scene to be ready before running our check
  83923. this._scene.executeWhenReady(function () {
  83924. setTimeout(function () {
  83925. _this._checkCurrentState();
  83926. }, _this._trackerDuration);
  83927. });
  83928. };
  83929. SceneOptimizer.prototype._checkCurrentState = function () {
  83930. var _this = this;
  83931. if (!this._isRunning) {
  83932. return;
  83933. }
  83934. var scene = this._scene;
  83935. var options = this._options;
  83936. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83937. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83938. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83939. this._isRunning = false;
  83940. this.onSuccessObservable.notifyObservers(this);
  83941. return;
  83942. }
  83943. // Apply current level of optimizations
  83944. var allDone = true;
  83945. var noOptimizationApplied = true;
  83946. for (var index = 0; index < options.optimizations.length; index++) {
  83947. var optimization = options.optimizations[index];
  83948. if (optimization.priority === this._currentPriorityLevel) {
  83949. noOptimizationApplied = false;
  83950. allDone = allDone && optimization.apply(scene, this);
  83951. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83952. }
  83953. }
  83954. // If no optimization was applied, this is a failure :(
  83955. if (noOptimizationApplied) {
  83956. this._isRunning = false;
  83957. this.onFailureObservable.notifyObservers(this);
  83958. return;
  83959. }
  83960. // If all optimizations were done, move to next level
  83961. if (allDone) {
  83962. this._currentPriorityLevel++;
  83963. }
  83964. // Let's the system running for a specific amount of time before checking FPS
  83965. scene.executeWhenReady(function () {
  83966. setTimeout(function () {
  83967. _this._checkCurrentState();
  83968. }, _this._trackerDuration);
  83969. });
  83970. };
  83971. /**
  83972. * Release all resources
  83973. */
  83974. SceneOptimizer.prototype.dispose = function () {
  83975. this.stop();
  83976. this.onSuccessObservable.clear();
  83977. this.onFailureObservable.clear();
  83978. this.onNewOptimizationAppliedObservable.clear();
  83979. if (this._sceneDisposeObserver) {
  83980. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83981. }
  83982. };
  83983. /**
  83984. * Helper function to create a SceneOptimizer with one single line of code
  83985. * @param scene defines the scene to work on
  83986. * @param options defines the options to use with the SceneOptimizer
  83987. * @param onSuccess defines a callback to call on success
  83988. * @param onFailure defines a callback to call on failure
  83989. * @returns the new SceneOptimizer object
  83990. */
  83991. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83992. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83993. if (onSuccess) {
  83994. optimizer.onSuccessObservable.add(function () {
  83995. onSuccess();
  83996. });
  83997. }
  83998. if (onFailure) {
  83999. optimizer.onFailureObservable.add(function () {
  84000. onFailure();
  84001. });
  84002. }
  84003. optimizer.start();
  84004. return optimizer;
  84005. };
  84006. return SceneOptimizer;
  84007. }());
  84008. BABYLON.SceneOptimizer = SceneOptimizer;
  84009. })(BABYLON || (BABYLON = {}));
  84010. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84011. var BABYLON;
  84012. (function (BABYLON) {
  84013. var OutlineRenderer = /** @class */ (function () {
  84014. function OutlineRenderer(scene) {
  84015. this.zOffset = 1;
  84016. this._scene = scene;
  84017. }
  84018. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84019. var _this = this;
  84020. if (useOverlay === void 0) { useOverlay = false; }
  84021. var scene = this._scene;
  84022. var engine = this._scene.getEngine();
  84023. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84024. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84025. return;
  84026. }
  84027. var mesh = subMesh.getRenderingMesh();
  84028. var material = subMesh.getMaterial();
  84029. if (!material || !scene.activeCamera) {
  84030. return;
  84031. }
  84032. engine.enableEffect(this._effect);
  84033. // Logarithmic depth
  84034. if (material.useLogarithmicDepth) {
  84035. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84036. }
  84037. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84038. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84039. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84040. // Bones
  84041. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84042. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84043. }
  84044. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84045. // Alpha test
  84046. if (material && material.needAlphaTesting()) {
  84047. var alphaTexture = material.getAlphaTestTexture();
  84048. if (alphaTexture) {
  84049. this._effect.setTexture("diffuseSampler", alphaTexture);
  84050. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84051. }
  84052. }
  84053. engine.setZOffset(-this.zOffset);
  84054. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84055. engine.setZOffset(0);
  84056. };
  84057. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84058. var defines = [];
  84059. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84060. var mesh = subMesh.getMesh();
  84061. var material = subMesh.getMaterial();
  84062. if (material) {
  84063. // Alpha test
  84064. if (material.needAlphaTesting()) {
  84065. defines.push("#define ALPHATEST");
  84066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84067. attribs.push(BABYLON.VertexBuffer.UVKind);
  84068. defines.push("#define UV1");
  84069. }
  84070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84072. defines.push("#define UV2");
  84073. }
  84074. }
  84075. //Logarithmic depth
  84076. if (material.useLogarithmicDepth) {
  84077. defines.push("#define LOGARITHMICDEPTH");
  84078. }
  84079. }
  84080. // Bones
  84081. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84082. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84083. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84084. if (mesh.numBoneInfluencers > 4) {
  84085. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84086. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84087. }
  84088. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84089. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84090. }
  84091. else {
  84092. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84093. }
  84094. // Instances
  84095. if (useInstances) {
  84096. defines.push("#define INSTANCES");
  84097. attribs.push("world0");
  84098. attribs.push("world1");
  84099. attribs.push("world2");
  84100. attribs.push("world3");
  84101. }
  84102. // Get correct effect
  84103. var join = defines.join("\n");
  84104. if (this._cachedDefines !== join) {
  84105. this._cachedDefines = join;
  84106. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84107. }
  84108. return this._effect.isReady();
  84109. };
  84110. return OutlineRenderer;
  84111. }());
  84112. BABYLON.OutlineRenderer = OutlineRenderer;
  84113. })(BABYLON || (BABYLON = {}));
  84114. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84115. var BABYLON;
  84116. (function (BABYLON) {
  84117. var FaceAdjacencies = /** @class */ (function () {
  84118. function FaceAdjacencies() {
  84119. this.edges = new Array();
  84120. this.edgesConnectedCount = 0;
  84121. }
  84122. return FaceAdjacencies;
  84123. }());
  84124. var EdgesRenderer = /** @class */ (function () {
  84125. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84126. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84127. if (epsilon === void 0) { epsilon = 0.95; }
  84128. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84129. this.edgesWidthScalerForOrthographic = 1000.0;
  84130. this.edgesWidthScalerForPerspective = 50.0;
  84131. this._linesPositions = new Array();
  84132. this._linesNormals = new Array();
  84133. this._linesIndices = new Array();
  84134. this._buffers = {};
  84135. this._checkVerticesInsteadOfIndices = false;
  84136. this._source = source;
  84137. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84138. this._epsilon = epsilon;
  84139. this._prepareRessources();
  84140. this._generateEdgesLines();
  84141. }
  84142. EdgesRenderer.prototype._prepareRessources = function () {
  84143. if (this._lineShader) {
  84144. return;
  84145. }
  84146. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84147. attributes: ["position", "normal"],
  84148. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84149. });
  84150. this._lineShader.disableDepthWrite = true;
  84151. this._lineShader.backFaceCulling = false;
  84152. };
  84153. EdgesRenderer.prototype._rebuild = function () {
  84154. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84155. if (buffer) {
  84156. buffer._rebuild();
  84157. }
  84158. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84159. if (buffer) {
  84160. buffer._rebuild();
  84161. }
  84162. var scene = this._source.getScene();
  84163. var engine = scene.getEngine();
  84164. this._ib = engine.createIndexBuffer(this._linesIndices);
  84165. };
  84166. EdgesRenderer.prototype.dispose = function () {
  84167. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84168. if (buffer) {
  84169. buffer.dispose();
  84170. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84171. }
  84172. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84173. if (buffer) {
  84174. buffer.dispose();
  84175. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84176. }
  84177. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84178. this._lineShader.dispose();
  84179. };
  84180. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84181. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84182. return 0;
  84183. }
  84184. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84185. return 1;
  84186. }
  84187. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84188. return 2;
  84189. }
  84190. return -1;
  84191. };
  84192. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84193. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84194. return 0;
  84195. }
  84196. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84197. return 1;
  84198. }
  84199. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84200. return 2;
  84201. }
  84202. return -1;
  84203. };
  84204. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84205. var needToCreateLine;
  84206. if (edge === undefined) {
  84207. needToCreateLine = true;
  84208. }
  84209. else {
  84210. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84211. needToCreateLine = dotProduct < this._epsilon;
  84212. }
  84213. if (needToCreateLine) {
  84214. var offset = this._linesPositions.length / 3;
  84215. var normal = p0.subtract(p1);
  84216. normal.normalize();
  84217. // Positions
  84218. this._linesPositions.push(p0.x);
  84219. this._linesPositions.push(p0.y);
  84220. this._linesPositions.push(p0.z);
  84221. this._linesPositions.push(p0.x);
  84222. this._linesPositions.push(p0.y);
  84223. this._linesPositions.push(p0.z);
  84224. this._linesPositions.push(p1.x);
  84225. this._linesPositions.push(p1.y);
  84226. this._linesPositions.push(p1.z);
  84227. this._linesPositions.push(p1.x);
  84228. this._linesPositions.push(p1.y);
  84229. this._linesPositions.push(p1.z);
  84230. // Normals
  84231. this._linesNormals.push(p1.x);
  84232. this._linesNormals.push(p1.y);
  84233. this._linesNormals.push(p1.z);
  84234. this._linesNormals.push(-1);
  84235. this._linesNormals.push(p1.x);
  84236. this._linesNormals.push(p1.y);
  84237. this._linesNormals.push(p1.z);
  84238. this._linesNormals.push(1);
  84239. this._linesNormals.push(p0.x);
  84240. this._linesNormals.push(p0.y);
  84241. this._linesNormals.push(p0.z);
  84242. this._linesNormals.push(-1);
  84243. this._linesNormals.push(p0.x);
  84244. this._linesNormals.push(p0.y);
  84245. this._linesNormals.push(p0.z);
  84246. this._linesNormals.push(1);
  84247. // Indices
  84248. this._linesIndices.push(offset);
  84249. this._linesIndices.push(offset + 1);
  84250. this._linesIndices.push(offset + 2);
  84251. this._linesIndices.push(offset);
  84252. this._linesIndices.push(offset + 2);
  84253. this._linesIndices.push(offset + 3);
  84254. }
  84255. };
  84256. EdgesRenderer.prototype._generateEdgesLines = function () {
  84257. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84258. var indices = this._source.getIndices();
  84259. if (!indices || !positions) {
  84260. return;
  84261. }
  84262. // First let's find adjacencies
  84263. var adjacencies = new Array();
  84264. var faceNormals = new Array();
  84265. var index;
  84266. var faceAdjacencies;
  84267. // Prepare faces
  84268. for (index = 0; index < indices.length; index += 3) {
  84269. faceAdjacencies = new FaceAdjacencies();
  84270. var p0Index = indices[index];
  84271. var p1Index = indices[index + 1];
  84272. var p2Index = indices[index + 2];
  84273. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84274. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84275. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84276. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84277. faceNormal.normalize();
  84278. faceNormals.push(faceNormal);
  84279. adjacencies.push(faceAdjacencies);
  84280. }
  84281. // Scan
  84282. for (index = 0; index < adjacencies.length; index++) {
  84283. faceAdjacencies = adjacencies[index];
  84284. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84285. var otherFaceAdjacencies = adjacencies[otherIndex];
  84286. if (faceAdjacencies.edgesConnectedCount === 3) {
  84287. break;
  84288. }
  84289. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84290. continue;
  84291. }
  84292. var otherP0 = indices[otherIndex * 3];
  84293. var otherP1 = indices[otherIndex * 3 + 1];
  84294. var otherP2 = indices[otherIndex * 3 + 2];
  84295. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84296. var otherEdgeIndex = 0;
  84297. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84298. continue;
  84299. }
  84300. switch (edgeIndex) {
  84301. case 0:
  84302. if (this._checkVerticesInsteadOfIndices) {
  84303. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84304. }
  84305. else {
  84306. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84307. }
  84308. break;
  84309. case 1:
  84310. if (this._checkVerticesInsteadOfIndices) {
  84311. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84312. }
  84313. else {
  84314. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84315. }
  84316. break;
  84317. case 2:
  84318. if (this._checkVerticesInsteadOfIndices) {
  84319. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84320. }
  84321. else {
  84322. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84323. }
  84324. break;
  84325. }
  84326. if (otherEdgeIndex === -1) {
  84327. continue;
  84328. }
  84329. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84330. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84331. faceAdjacencies.edgesConnectedCount++;
  84332. otherFaceAdjacencies.edgesConnectedCount++;
  84333. if (faceAdjacencies.edgesConnectedCount === 3) {
  84334. break;
  84335. }
  84336. }
  84337. }
  84338. }
  84339. // Create lines
  84340. for (index = 0; index < adjacencies.length; index++) {
  84341. // 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
  84342. var current = adjacencies[index];
  84343. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84344. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84345. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84346. }
  84347. // Merge into a single mesh
  84348. var engine = this._source.getScene().getEngine();
  84349. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84350. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84351. this._ib = engine.createIndexBuffer(this._linesIndices);
  84352. this._indicesCount = this._linesIndices.length;
  84353. };
  84354. EdgesRenderer.prototype.render = function () {
  84355. var scene = this._source.getScene();
  84356. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84357. return;
  84358. }
  84359. var engine = scene.getEngine();
  84360. this._lineShader._preBind();
  84361. // VBOs
  84362. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84363. scene.resetCachedMaterial();
  84364. this._lineShader.setColor4("color", this._source.edgesColor);
  84365. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84366. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84367. }
  84368. else {
  84369. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84370. }
  84371. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84372. this._lineShader.bind(this._source.getWorldMatrix());
  84373. // Draw order
  84374. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84375. this._lineShader.unbind();
  84376. engine.setDepthWrite(true);
  84377. };
  84378. return EdgesRenderer;
  84379. }());
  84380. BABYLON.EdgesRenderer = EdgesRenderer;
  84381. })(BABYLON || (BABYLON = {}));
  84382. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84383. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84384. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84385. s = arguments[i];
  84386. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84387. t[p] = s[p];
  84388. }
  84389. return t;
  84390. };
  84391. var BABYLON;
  84392. (function (BABYLON) {
  84393. /**
  84394. * The effect layer Helps adding post process effect blended with the main pass.
  84395. *
  84396. * This can be for instance use to generate glow or higlight effects on the scene.
  84397. *
  84398. * The effect layer class can not be used directly and is intented to inherited from to be
  84399. * customized per effects.
  84400. */
  84401. var EffectLayer = /** @class */ (function () {
  84402. /**
  84403. * Instantiates a new effect Layer and references it in the scene.
  84404. * @param name The name of the layer
  84405. * @param scene The scene to use the layer in
  84406. */
  84407. function EffectLayer(
  84408. /** The Friendly of the effect in the scene */
  84409. name, scene) {
  84410. this.name = name;
  84411. this._vertexBuffers = {};
  84412. this._maxSize = 0;
  84413. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84414. this._shouldRender = true;
  84415. this._postProcesses = [];
  84416. this._textures = [];
  84417. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84418. /**
  84419. * The clear color of the texture used to generate the glow map.
  84420. */
  84421. this.neutralColor = new BABYLON.Color4();
  84422. /**
  84423. * Specifies wether the highlight layer is enabled or not.
  84424. */
  84425. this.isEnabled = true;
  84426. /**
  84427. * An event triggered when the effect layer has been disposed.
  84428. */
  84429. this.onDisposeObservable = new BABYLON.Observable();
  84430. /**
  84431. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84432. */
  84433. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84434. /**
  84435. * An event triggered when the generated texture is being merged in the scene.
  84436. */
  84437. this.onBeforeComposeObservable = new BABYLON.Observable();
  84438. /**
  84439. * An event triggered when the generated texture has been merged in the scene.
  84440. */
  84441. this.onAfterComposeObservable = new BABYLON.Observable();
  84442. /**
  84443. * An event triggered when the efffect layer changes its size.
  84444. */
  84445. this.onSizeChangedObservable = new BABYLON.Observable();
  84446. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84447. this._engine = scene.getEngine();
  84448. this._maxSize = this._engine.getCaps().maxTextureSize;
  84449. this._scene.effectLayers.push(this);
  84450. // Generate Buffers
  84451. this._generateIndexBuffer();
  84452. this._genrateVertexBuffer();
  84453. }
  84454. Object.defineProperty(EffectLayer.prototype, "camera", {
  84455. /**
  84456. * Gets the camera attached to the layer.
  84457. */
  84458. get: function () {
  84459. return this._effectLayerOptions.camera;
  84460. },
  84461. enumerable: true,
  84462. configurable: true
  84463. });
  84464. /**
  84465. * Initializes the effect layer with the required options.
  84466. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84467. */
  84468. EffectLayer.prototype._init = function (options) {
  84469. // Adapt options
  84470. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84471. this._setMainTextureSize();
  84472. this._createMainTexture();
  84473. this._createTextureAndPostProcesses();
  84474. this._mergeEffect = this._createMergeEffect();
  84475. };
  84476. /**
  84477. * Generates the index buffer of the full screen quad blending to the main canvas.
  84478. */
  84479. EffectLayer.prototype._generateIndexBuffer = function () {
  84480. // Indices
  84481. var indices = [];
  84482. indices.push(0);
  84483. indices.push(1);
  84484. indices.push(2);
  84485. indices.push(0);
  84486. indices.push(2);
  84487. indices.push(3);
  84488. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84489. };
  84490. /**
  84491. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84492. */
  84493. EffectLayer.prototype._genrateVertexBuffer = function () {
  84494. // VBO
  84495. var vertices = [];
  84496. vertices.push(1, 1);
  84497. vertices.push(-1, 1);
  84498. vertices.push(-1, -1);
  84499. vertices.push(1, -1);
  84500. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84502. };
  84503. /**
  84504. * Sets the main texture desired size which is the closest power of two
  84505. * of the engine canvas size.
  84506. */
  84507. EffectLayer.prototype._setMainTextureSize = function () {
  84508. if (this._effectLayerOptions.mainTextureFixedSize) {
  84509. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84510. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84511. }
  84512. else {
  84513. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84514. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84515. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84516. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84517. }
  84518. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84519. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84520. };
  84521. /**
  84522. * Creates the main texture for the effect layer.
  84523. */
  84524. EffectLayer.prototype._createMainTexture = function () {
  84525. var _this = this;
  84526. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84527. width: this._mainTextureDesiredSize.width,
  84528. height: this._mainTextureDesiredSize.height
  84529. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84530. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84531. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84532. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84533. this._mainTexture.anisotropicFilteringLevel = 1;
  84534. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84535. this._mainTexture.renderParticles = false;
  84536. this._mainTexture.renderList = null;
  84537. this._mainTexture.ignoreCameraViewport = true;
  84538. // Custom render function
  84539. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84540. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84541. var index;
  84542. var engine = _this._scene.getEngine();
  84543. if (depthOnlySubMeshes.length) {
  84544. engine.setColorWrite(false);
  84545. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84546. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84547. }
  84548. engine.setColorWrite(true);
  84549. }
  84550. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84551. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84552. }
  84553. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84554. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84555. }
  84556. for (index = 0; index < transparentSubMeshes.length; index++) {
  84557. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84558. }
  84559. };
  84560. this._mainTexture.onClearObservable.add(function (engine) {
  84561. engine.clear(_this.neutralColor, true, true, true);
  84562. });
  84563. };
  84564. /**
  84565. * Checks for the readiness of the element composing the layer.
  84566. * @param subMesh the mesh to check for
  84567. * @param useInstances specify wether or not to use instances to render the mesh
  84568. * @param emissiveTexture the associated emissive texture used to generate the glow
  84569. * @return true if ready otherwise, false
  84570. */
  84571. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84572. var material = subMesh.getMaterial();
  84573. if (!material) {
  84574. return false;
  84575. }
  84576. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84577. return false;
  84578. }
  84579. var defines = [];
  84580. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84581. var mesh = subMesh.getMesh();
  84582. var uv1 = false;
  84583. var uv2 = false;
  84584. // Alpha test
  84585. if (material && material.needAlphaTesting()) {
  84586. var alphaTexture = material.getAlphaTestTexture();
  84587. if (alphaTexture) {
  84588. defines.push("#define ALPHATEST");
  84589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84590. alphaTexture.coordinatesIndex === 1) {
  84591. defines.push("#define DIFFUSEUV2");
  84592. uv2 = true;
  84593. }
  84594. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84595. defines.push("#define DIFFUSEUV1");
  84596. uv1 = true;
  84597. }
  84598. }
  84599. }
  84600. // Emissive
  84601. if (emissiveTexture) {
  84602. defines.push("#define EMISSIVE");
  84603. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84604. emissiveTexture.coordinatesIndex === 1) {
  84605. defines.push("#define EMISSIVEUV2");
  84606. uv2 = true;
  84607. }
  84608. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84609. defines.push("#define EMISSIVEUV1");
  84610. uv1 = true;
  84611. }
  84612. }
  84613. if (uv1) {
  84614. attribs.push(BABYLON.VertexBuffer.UVKind);
  84615. defines.push("#define UV1");
  84616. }
  84617. if (uv2) {
  84618. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84619. defines.push("#define UV2");
  84620. }
  84621. // Bones
  84622. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84623. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84624. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84625. if (mesh.numBoneInfluencers > 4) {
  84626. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84627. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84628. }
  84629. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84630. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84631. }
  84632. else {
  84633. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84634. }
  84635. // Instances
  84636. if (useInstances) {
  84637. defines.push("#define INSTANCES");
  84638. attribs.push("world0");
  84639. attribs.push("world1");
  84640. attribs.push("world2");
  84641. attribs.push("world3");
  84642. }
  84643. // Get correct effect
  84644. var join = defines.join("\n");
  84645. if (this._cachedDefines !== join) {
  84646. this._cachedDefines = join;
  84647. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84648. }
  84649. return this._effectLayerMapGenerationEffect.isReady();
  84650. };
  84651. /**
  84652. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84653. */
  84654. EffectLayer.prototype.render = function () {
  84655. var currentEffect = this._mergeEffect;
  84656. // Check
  84657. if (!currentEffect.isReady())
  84658. return;
  84659. for (var i = 0; i < this._postProcesses.length; i++) {
  84660. if (!this._postProcesses[i].isReady()) {
  84661. return;
  84662. }
  84663. }
  84664. var engine = this._scene.getEngine();
  84665. this.onBeforeComposeObservable.notifyObservers(this);
  84666. // Render
  84667. engine.enableEffect(currentEffect);
  84668. engine.setState(false);
  84669. // VBOs
  84670. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84671. // Cache
  84672. var previousAlphaMode = engine.getAlphaMode();
  84673. // Go Blend.
  84674. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84675. // Blends the map on the main canvas.
  84676. this._internalRender(currentEffect);
  84677. // Restore Alpha
  84678. engine.setAlphaMode(previousAlphaMode);
  84679. this.onAfterComposeObservable.notifyObservers(this);
  84680. // Handle size changes.
  84681. var size = this._mainTexture.getSize();
  84682. this._setMainTextureSize();
  84683. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84684. // Recreate RTT and post processes on size change.
  84685. this.onSizeChangedObservable.notifyObservers(this);
  84686. this._disposeTextureAndPostProcesses();
  84687. this._createMainTexture();
  84688. this._createTextureAndPostProcesses();
  84689. }
  84690. };
  84691. /**
  84692. * Determine if a given mesh will be used in the current effect.
  84693. * @param mesh mesh to test
  84694. * @returns true if the mesh will be used
  84695. */
  84696. EffectLayer.prototype.hasMesh = function (mesh) {
  84697. return true;
  84698. };
  84699. /**
  84700. * Returns true if the layer contains information to display, otherwise false.
  84701. * @returns true if the glow layer should be rendered
  84702. */
  84703. EffectLayer.prototype.shouldRender = function () {
  84704. return this.isEnabled && this._shouldRender;
  84705. };
  84706. /**
  84707. * Returns true if the mesh should render, otherwise false.
  84708. * @param mesh The mesh to render
  84709. * @returns true if it should render otherwise false
  84710. */
  84711. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84712. return true;
  84713. };
  84714. /**
  84715. * Returns true if the mesh should render, otherwise false.
  84716. * @param mesh The mesh to render
  84717. * @returns true if it should render otherwise false
  84718. */
  84719. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84720. return true;
  84721. };
  84722. /**
  84723. * Renders the submesh passed in parameter to the generation map.
  84724. */
  84725. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84726. var _this = this;
  84727. if (!this.shouldRender()) {
  84728. return;
  84729. }
  84730. var material = subMesh.getMaterial();
  84731. var mesh = subMesh.getRenderingMesh();
  84732. var scene = this._scene;
  84733. var engine = scene.getEngine();
  84734. if (!material) {
  84735. return;
  84736. }
  84737. // Do not block in blend mode.
  84738. if (material.needAlphaBlendingForMesh(mesh)) {
  84739. return;
  84740. }
  84741. // Culling
  84742. engine.setState(material.backFaceCulling);
  84743. // Managing instances
  84744. var batch = mesh._getInstancesRenderList(subMesh._id);
  84745. if (batch.mustReturn) {
  84746. return;
  84747. }
  84748. // Early Exit per mesh
  84749. if (!this._shouldRenderMesh(mesh)) {
  84750. return;
  84751. }
  84752. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84753. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84754. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84755. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84756. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84757. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84758. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84759. // Alpha test
  84760. if (material && material.needAlphaTesting()) {
  84761. var alphaTexture = material.getAlphaTestTexture();
  84762. if (alphaTexture) {
  84763. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84764. var textureMatrix = alphaTexture.getTextureMatrix();
  84765. if (textureMatrix) {
  84766. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84767. }
  84768. }
  84769. }
  84770. // Glow emissive only
  84771. if (this._emissiveTextureAndColor.texture) {
  84772. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84773. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84774. }
  84775. // Bones
  84776. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84777. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84778. }
  84779. // Draw
  84780. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84781. }
  84782. else {
  84783. // Need to reset refresh rate of the shadowMap
  84784. this._mainTexture.resetRefreshCounter();
  84785. }
  84786. };
  84787. /**
  84788. * Rebuild the required buffers.
  84789. * @ignore Internal use only.
  84790. */
  84791. EffectLayer.prototype._rebuild = function () {
  84792. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84793. if (vb) {
  84794. vb._rebuild();
  84795. }
  84796. this._generateIndexBuffer();
  84797. };
  84798. /**
  84799. * Dispose only the render target textures and post process.
  84800. */
  84801. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84802. this._mainTexture.dispose();
  84803. for (var i = 0; i < this._postProcesses.length; i++) {
  84804. if (this._postProcesses[i]) {
  84805. this._postProcesses[i].dispose();
  84806. }
  84807. }
  84808. this._postProcesses = [];
  84809. for (var i = 0; i < this._textures.length; i++) {
  84810. if (this._textures[i]) {
  84811. this._textures[i].dispose();
  84812. }
  84813. }
  84814. this._textures = [];
  84815. };
  84816. /**
  84817. * Dispose the highlight layer and free resources.
  84818. */
  84819. EffectLayer.prototype.dispose = function () {
  84820. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84821. if (vertexBuffer) {
  84822. vertexBuffer.dispose();
  84823. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84824. }
  84825. if (this._indexBuffer) {
  84826. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84827. this._indexBuffer = null;
  84828. }
  84829. // Clean textures and post processes
  84830. this._disposeTextureAndPostProcesses();
  84831. // Remove from scene
  84832. var index = this._scene.effectLayers.indexOf(this, 0);
  84833. if (index > -1) {
  84834. this._scene.effectLayers.splice(index, 1);
  84835. }
  84836. // Callback
  84837. this.onDisposeObservable.notifyObservers(this);
  84838. this.onDisposeObservable.clear();
  84839. this.onBeforeRenderMainTextureObservable.clear();
  84840. this.onBeforeComposeObservable.clear();
  84841. this.onAfterComposeObservable.clear();
  84842. this.onSizeChangedObservable.clear();
  84843. };
  84844. return EffectLayer;
  84845. }());
  84846. BABYLON.EffectLayer = EffectLayer;
  84847. })(BABYLON || (BABYLON = {}));
  84848. //# sourceMappingURL=babylon.effectLayer.js.map
  84849. var BABYLON;
  84850. (function (BABYLON) {
  84851. /**
  84852. * Special Glow Blur post process only blurring the alpha channel
  84853. * It enforces keeping the most luminous color in the color channel.
  84854. */
  84855. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84856. __extends(GlowBlurPostProcess, _super);
  84857. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84859. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84860. _this.direction = direction;
  84861. _this.kernel = kernel;
  84862. _this.onApplyObservable.add(function (effect) {
  84863. effect.setFloat2("screenSize", _this.width, _this.height);
  84864. effect.setVector2("direction", _this.direction);
  84865. effect.setFloat("blurWidth", _this.kernel);
  84866. });
  84867. return _this;
  84868. }
  84869. return GlowBlurPostProcess;
  84870. }(BABYLON.PostProcess));
  84871. /**
  84872. * The highlight layer Helps adding a glow effect around a mesh.
  84873. *
  84874. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84875. * glowy meshes to your scene.
  84876. *
  84877. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84878. */
  84879. var HighlightLayer = /** @class */ (function (_super) {
  84880. __extends(HighlightLayer, _super);
  84881. /**
  84882. * Instantiates a new highlight Layer and references it to the scene..
  84883. * @param name The name of the layer
  84884. * @param scene The scene to use the layer in
  84885. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84886. */
  84887. function HighlightLayer(name, scene, options) {
  84888. var _this = _super.call(this, name, scene) || this;
  84889. _this.name = name;
  84890. /**
  84891. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84892. */
  84893. _this.innerGlow = true;
  84894. /**
  84895. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84896. */
  84897. _this.outerGlow = true;
  84898. /**
  84899. * An event triggered when the highlight layer is being blurred.
  84900. */
  84901. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84902. /**
  84903. * An event triggered when the highlight layer has been blurred.
  84904. */
  84905. _this.onAfterBlurObservable = new BABYLON.Observable();
  84906. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84907. _this._meshes = {};
  84908. _this._excludedMeshes = {};
  84909. _this.neutralColor = HighlightLayer.NeutralColor;
  84910. // Warn on stencil
  84911. if (!_this._engine.isStencilEnable) {
  84912. 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 }");
  84913. }
  84914. // Adapt options
  84915. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84916. // Initialize the layer
  84917. _this._init({
  84918. alphaBlendingMode: _this._options.alphaBlendingMode,
  84919. camera: _this._options.camera,
  84920. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84921. mainTextureRatio: _this._options.mainTextureRatio
  84922. });
  84923. // Do not render as long as no meshes have been added
  84924. _this._shouldRender = false;
  84925. return _this;
  84926. }
  84927. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84928. /**
  84929. * Gets the horizontal size of the blur.
  84930. */
  84931. get: function () {
  84932. return this._horizontalBlurPostprocess.kernel;
  84933. },
  84934. /**
  84935. * Specifies the horizontal size of the blur.
  84936. */
  84937. set: function (value) {
  84938. this._horizontalBlurPostprocess.kernel = value;
  84939. },
  84940. enumerable: true,
  84941. configurable: true
  84942. });
  84943. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84944. /**
  84945. * Gets the vertical size of the blur.
  84946. */
  84947. get: function () {
  84948. return this._verticalBlurPostprocess.kernel;
  84949. },
  84950. /**
  84951. * Specifies the vertical size of the blur.
  84952. */
  84953. set: function (value) {
  84954. this._verticalBlurPostprocess.kernel = value;
  84955. },
  84956. enumerable: true,
  84957. configurable: true
  84958. });
  84959. /**
  84960. * Get the effect name of the layer.
  84961. * @return The effect name
  84962. */
  84963. HighlightLayer.prototype.getEffectName = function () {
  84964. return HighlightLayer.EffectName;
  84965. };
  84966. /**
  84967. * Create the merge effect. This is the shader use to blit the information back
  84968. * to the main canvas at the end of the scene rendering.
  84969. */
  84970. HighlightLayer.prototype._createMergeEffect = function () {
  84971. // Effect
  84972. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84973. };
  84974. /**
  84975. * Creates the render target textures and post processes used in the highlight layer.
  84976. */
  84977. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84978. var _this = this;
  84979. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84980. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84981. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84982. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84983. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84984. width: blurTextureWidth,
  84985. height: blurTextureHeight
  84986. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84987. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84988. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84989. this._blurTexture.anisotropicFilteringLevel = 16;
  84990. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84991. this._blurTexture.renderParticles = false;
  84992. this._blurTexture.ignoreCameraViewport = true;
  84993. this._textures = [this._blurTexture];
  84994. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84995. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84996. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84997. effect.setTexture("textureSampler", _this._mainTexture);
  84998. });
  84999. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85000. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85001. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85002. });
  85003. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85004. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85005. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85006. });
  85007. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85008. }
  85009. else {
  85010. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85011. width: blurTextureWidth,
  85012. height: blurTextureHeight
  85013. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85014. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85015. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85016. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85017. effect.setTexture("textureSampler", _this._mainTexture);
  85018. });
  85019. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85020. width: blurTextureWidth,
  85021. height: blurTextureHeight
  85022. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85023. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85024. }
  85025. this._mainTexture.onAfterUnbindObservable.add(function () {
  85026. _this.onBeforeBlurObservable.notifyObservers(_this);
  85027. var internalTexture = _this._blurTexture.getInternalTexture();
  85028. if (internalTexture) {
  85029. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85030. }
  85031. _this.onAfterBlurObservable.notifyObservers(_this);
  85032. });
  85033. // Prevent autoClear.
  85034. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85035. };
  85036. /**
  85037. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85038. */
  85039. HighlightLayer.prototype.needStencil = function () {
  85040. return true;
  85041. };
  85042. /**
  85043. * Checks for the readiness of the element composing the layer.
  85044. * @param subMesh the mesh to check for
  85045. * @param useInstances specify wether or not to use instances to render the mesh
  85046. * @param emissiveTexture the associated emissive texture used to generate the glow
  85047. * @return true if ready otherwise, false
  85048. */
  85049. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85050. var material = subMesh.getMaterial();
  85051. var mesh = subMesh.getRenderingMesh();
  85052. if (!material || !mesh || !this._meshes) {
  85053. return false;
  85054. }
  85055. var emissiveTexture = null;
  85056. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85057. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85058. emissiveTexture = material.emissiveTexture;
  85059. }
  85060. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85061. };
  85062. /**
  85063. * Implementation specific of rendering the generating effect on the main canvas.
  85064. * @param effect The effect used to render through
  85065. */
  85066. HighlightLayer.prototype._internalRender = function (effect) {
  85067. // Texture
  85068. effect.setTexture("textureSampler", this._blurTexture);
  85069. // Cache
  85070. var engine = this._engine;
  85071. var previousStencilBuffer = engine.getStencilBuffer();
  85072. var previousStencilFunction = engine.getStencilFunction();
  85073. var previousStencilMask = engine.getStencilMask();
  85074. var previousStencilOperationPass = engine.getStencilOperationPass();
  85075. var previousStencilOperationFail = engine.getStencilOperationFail();
  85076. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85077. var previousStencilReference = engine.getStencilFunctionReference();
  85078. // Stencil operations
  85079. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85080. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85081. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85082. // Draw order
  85083. engine.setStencilMask(0x00);
  85084. engine.setStencilBuffer(true);
  85085. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85086. // 2 passes inner outer
  85087. if (this.outerGlow) {
  85088. effect.setFloat("offset", 0);
  85089. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85090. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85091. }
  85092. if (this.innerGlow) {
  85093. effect.setFloat("offset", 1);
  85094. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85095. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85096. }
  85097. // Restore Cache
  85098. engine.setStencilFunction(previousStencilFunction);
  85099. engine.setStencilMask(previousStencilMask);
  85100. engine.setStencilBuffer(previousStencilBuffer);
  85101. engine.setStencilOperationPass(previousStencilOperationPass);
  85102. engine.setStencilOperationFail(previousStencilOperationFail);
  85103. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85104. engine.setStencilFunctionReference(previousStencilReference);
  85105. };
  85106. /**
  85107. * Returns true if the layer contains information to display, otherwise false.
  85108. */
  85109. HighlightLayer.prototype.shouldRender = function () {
  85110. if (_super.prototype.shouldRender.call(this)) {
  85111. return this._meshes ? true : false;
  85112. }
  85113. return false;
  85114. };
  85115. /**
  85116. * Returns true if the mesh should render, otherwise false.
  85117. * @param mesh The mesh to render
  85118. * @returns true if it should render otherwise false
  85119. */
  85120. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85121. // Excluded Mesh
  85122. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85123. return false;
  85124. }
  85125. ;
  85126. return true;
  85127. };
  85128. /**
  85129. * Sets the required values for both the emissive texture and and the main color.
  85130. */
  85131. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85132. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85133. if (highlightLayerMesh) {
  85134. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85135. }
  85136. else {
  85137. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85138. }
  85139. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85140. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85141. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85142. }
  85143. else {
  85144. this._emissiveTextureAndColor.texture = null;
  85145. }
  85146. };
  85147. /**
  85148. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85149. * @param mesh The mesh to exclude from the highlight layer
  85150. */
  85151. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85152. if (!this._excludedMeshes) {
  85153. return;
  85154. }
  85155. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85156. if (!meshExcluded) {
  85157. this._excludedMeshes[mesh.uniqueId] = {
  85158. mesh: mesh,
  85159. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85160. mesh.getEngine().setStencilBuffer(false);
  85161. }),
  85162. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85163. mesh.getEngine().setStencilBuffer(true);
  85164. }),
  85165. };
  85166. }
  85167. };
  85168. /**
  85169. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85170. * @param mesh The mesh to highlight
  85171. */
  85172. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85173. if (!this._excludedMeshes) {
  85174. return;
  85175. }
  85176. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85177. if (meshExcluded) {
  85178. if (meshExcluded.beforeRender) {
  85179. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85180. }
  85181. if (meshExcluded.afterRender) {
  85182. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85183. }
  85184. }
  85185. this._excludedMeshes[mesh.uniqueId] = null;
  85186. };
  85187. /**
  85188. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85189. * @param mesh mesh to test
  85190. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85191. */
  85192. HighlightLayer.prototype.hasMesh = function (mesh) {
  85193. if (!this._meshes) {
  85194. return false;
  85195. }
  85196. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85197. };
  85198. /**
  85199. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85200. * @param mesh The mesh to highlight
  85201. * @param color The color of the highlight
  85202. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85203. */
  85204. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85205. var _this = this;
  85206. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85207. if (!this._meshes) {
  85208. return;
  85209. }
  85210. var meshHighlight = this._meshes[mesh.uniqueId];
  85211. if (meshHighlight) {
  85212. meshHighlight.color = color;
  85213. }
  85214. else {
  85215. this._meshes[mesh.uniqueId] = {
  85216. mesh: mesh,
  85217. color: color,
  85218. // Lambda required for capture due to Observable this context
  85219. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85220. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85221. _this._defaultStencilReference(mesh);
  85222. }
  85223. else {
  85224. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85225. }
  85226. }),
  85227. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85228. glowEmissiveOnly: glowEmissiveOnly
  85229. };
  85230. }
  85231. this._shouldRender = true;
  85232. };
  85233. /**
  85234. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85235. * @param mesh The mesh to highlight
  85236. */
  85237. HighlightLayer.prototype.removeMesh = function (mesh) {
  85238. if (!this._meshes) {
  85239. return;
  85240. }
  85241. var meshHighlight = this._meshes[mesh.uniqueId];
  85242. if (meshHighlight) {
  85243. if (meshHighlight.observerHighlight) {
  85244. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85245. }
  85246. if (meshHighlight.observerDefault) {
  85247. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85248. }
  85249. delete this._meshes[mesh.uniqueId];
  85250. }
  85251. this._shouldRender = false;
  85252. for (var meshHighlightToCheck in this._meshes) {
  85253. if (this._meshes[meshHighlightToCheck]) {
  85254. this._shouldRender = true;
  85255. break;
  85256. }
  85257. }
  85258. };
  85259. /**
  85260. * Force the stencil to the normal expected value for none glowing parts
  85261. */
  85262. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85263. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85264. };
  85265. /**
  85266. * Free any resources and references associated to a mesh.
  85267. * Internal use
  85268. * @param mesh The mesh to free.
  85269. */
  85270. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85271. this.removeMesh(mesh);
  85272. this.removeExcludedMesh(mesh);
  85273. };
  85274. /**
  85275. * Dispose the highlight layer and free resources.
  85276. */
  85277. HighlightLayer.prototype.dispose = function () {
  85278. if (this._meshes) {
  85279. // Clean mesh references
  85280. for (var id in this._meshes) {
  85281. var meshHighlight = this._meshes[id];
  85282. if (meshHighlight && meshHighlight.mesh) {
  85283. if (meshHighlight.observerHighlight) {
  85284. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85285. }
  85286. if (meshHighlight.observerDefault) {
  85287. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85288. }
  85289. }
  85290. }
  85291. this._meshes = null;
  85292. }
  85293. if (this._excludedMeshes) {
  85294. for (var id in this._excludedMeshes) {
  85295. var meshHighlight = this._excludedMeshes[id];
  85296. if (meshHighlight) {
  85297. if (meshHighlight.beforeRender) {
  85298. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85299. }
  85300. if (meshHighlight.afterRender) {
  85301. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85302. }
  85303. }
  85304. }
  85305. this._excludedMeshes = null;
  85306. }
  85307. _super.prototype.dispose.call(this);
  85308. };
  85309. /**
  85310. * Effect Name of the highlight layer.
  85311. */
  85312. HighlightLayer.EffectName = "HighlightLayer";
  85313. /**
  85314. * The neutral color used during the preparation of the glow effect.
  85315. * This is black by default as the blend operation is a blend operation.
  85316. */
  85317. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85318. /**
  85319. * Stencil value used for glowing meshes.
  85320. */
  85321. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85322. /**
  85323. * Stencil value used for the other meshes in the scene.
  85324. */
  85325. HighlightLayer.NormalMeshStencilReference = 0x01;
  85326. return HighlightLayer;
  85327. }(BABYLON.EffectLayer));
  85328. BABYLON.HighlightLayer = HighlightLayer;
  85329. })(BABYLON || (BABYLON = {}));
  85330. //# sourceMappingURL=babylon.highlightLayer.js.map
  85331. var BABYLON;
  85332. (function (BABYLON) {
  85333. /**
  85334. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85335. *
  85336. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85337. * glowy meshes to your scene.
  85338. *
  85339. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85340. */
  85341. var GlowLayer = /** @class */ (function (_super) {
  85342. __extends(GlowLayer, _super);
  85343. /**
  85344. * Instantiates a new glow Layer and references it to the scene.
  85345. * @param name The name of the layer
  85346. * @param scene The scene to use the layer in
  85347. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85348. */
  85349. function GlowLayer(name, scene, options) {
  85350. var _this = _super.call(this, name, scene) || this;
  85351. _this.name = name;
  85352. _this._intensity = 1.0;
  85353. _this._includedOnlyMeshes = [];
  85354. _this._excludedMeshes = [];
  85355. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85356. // Adapt options
  85357. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85358. // Initialize the layer
  85359. _this._init({
  85360. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85361. camera: _this._options.camera,
  85362. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85363. mainTextureRatio: _this._options.mainTextureRatio
  85364. });
  85365. return _this;
  85366. }
  85367. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85368. /**
  85369. * Gets the kernel size of the blur.
  85370. */
  85371. get: function () {
  85372. return this._horizontalBlurPostprocess1.kernel;
  85373. },
  85374. /**
  85375. * Sets the kernel size of the blur.
  85376. */
  85377. set: function (value) {
  85378. this._horizontalBlurPostprocess1.kernel = value;
  85379. this._verticalBlurPostprocess1.kernel = value;
  85380. this._horizontalBlurPostprocess2.kernel = value;
  85381. this._verticalBlurPostprocess2.kernel = value;
  85382. },
  85383. enumerable: true,
  85384. configurable: true
  85385. });
  85386. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85387. /**
  85388. * Gets the glow intensity.
  85389. */
  85390. get: function () {
  85391. return this._intensity;
  85392. },
  85393. /**
  85394. * Sets the glow intensity.
  85395. */
  85396. set: function (value) {
  85397. this._intensity = value;
  85398. },
  85399. enumerable: true,
  85400. configurable: true
  85401. });
  85402. /**
  85403. * Get the effect name of the layer.
  85404. * @return The effect name
  85405. */
  85406. GlowLayer.prototype.getEffectName = function () {
  85407. return GlowLayer.EffectName;
  85408. };
  85409. /**
  85410. * Create the merge effect. This is the shader use to blit the information back
  85411. * to the main canvas at the end of the scene rendering.
  85412. */
  85413. GlowLayer.prototype._createMergeEffect = function () {
  85414. // Effect
  85415. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85416. };
  85417. /**
  85418. * Creates the render target textures and post processes used in the glow layer.
  85419. */
  85420. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85421. var _this = this;
  85422. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85423. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85424. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85425. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85426. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85427. width: blurTextureWidth,
  85428. height: blurTextureHeight
  85429. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85430. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85431. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85432. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85433. this._blurTexture1.renderParticles = false;
  85434. this._blurTexture1.ignoreCameraViewport = true;
  85435. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85436. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85437. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85438. width: blurTextureWidth2,
  85439. height: blurTextureHeight2
  85440. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85441. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85442. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85443. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85444. this._blurTexture2.renderParticles = false;
  85445. this._blurTexture2.ignoreCameraViewport = true;
  85446. this._textures = [this._blurTexture1, this._blurTexture2];
  85447. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85448. width: blurTextureWidth,
  85449. height: blurTextureHeight
  85450. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85451. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85452. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85453. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85454. effect.setTexture("textureSampler", _this._mainTexture);
  85455. });
  85456. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85457. width: blurTextureWidth,
  85458. height: blurTextureHeight
  85459. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85460. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85461. width: blurTextureWidth2,
  85462. height: blurTextureHeight2
  85463. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85464. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85465. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85466. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85467. effect.setTexture("textureSampler", _this._blurTexture1);
  85468. });
  85469. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85470. width: blurTextureWidth2,
  85471. height: blurTextureHeight2
  85472. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85473. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85474. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85475. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85476. this._mainTexture.samples = this._options.mainTextureSamples;
  85477. this._mainTexture.onAfterUnbindObservable.add(function () {
  85478. var internalTexture = _this._blurTexture1.getInternalTexture();
  85479. if (internalTexture) {
  85480. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85481. internalTexture = _this._blurTexture2.getInternalTexture();
  85482. if (internalTexture) {
  85483. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85484. }
  85485. }
  85486. });
  85487. // Prevent autoClear.
  85488. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85489. };
  85490. /**
  85491. * Checks for the readiness of the element composing the layer.
  85492. * @param subMesh the mesh to check for
  85493. * @param useInstances specify wether or not to use instances to render the mesh
  85494. * @param emissiveTexture the associated emissive texture used to generate the glow
  85495. * @return true if ready otherwise, false
  85496. */
  85497. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85498. var material = subMesh.getMaterial();
  85499. var mesh = subMesh.getRenderingMesh();
  85500. if (!material || !mesh) {
  85501. return false;
  85502. }
  85503. var emissiveTexture = material.emissiveTexture;
  85504. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85505. };
  85506. /**
  85507. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85508. */
  85509. GlowLayer.prototype.needStencil = function () {
  85510. return false;
  85511. };
  85512. /**
  85513. * Implementation specific of rendering the generating effect on the main canvas.
  85514. * @param effect The effect used to render through
  85515. */
  85516. GlowLayer.prototype._internalRender = function (effect) {
  85517. // Texture
  85518. effect.setTexture("textureSampler", this._blurTexture1);
  85519. effect.setTexture("textureSampler2", this._blurTexture2);
  85520. effect.setFloat("offset", this._intensity);
  85521. // Cache
  85522. var engine = this._engine;
  85523. var previousStencilBuffer = engine.getStencilBuffer();
  85524. // Draw order
  85525. engine.setStencilBuffer(false);
  85526. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85527. // Draw order
  85528. engine.setStencilBuffer(previousStencilBuffer);
  85529. };
  85530. /**
  85531. * Sets the required values for both the emissive texture and and the main color.
  85532. */
  85533. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85534. var textureLevel = 1.0;
  85535. if (this.customEmissiveTextureSelector) {
  85536. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85537. }
  85538. else {
  85539. if (material) {
  85540. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85541. if (this._emissiveTextureAndColor.texture) {
  85542. textureLevel = this._emissiveTextureAndColor.texture.level;
  85543. }
  85544. }
  85545. else {
  85546. this._emissiveTextureAndColor.texture = null;
  85547. }
  85548. }
  85549. if (this.customEmissiveColorSelector) {
  85550. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85551. }
  85552. else {
  85553. if (material.emissiveColor) {
  85554. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85555. }
  85556. else {
  85557. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85558. }
  85559. }
  85560. };
  85561. /**
  85562. * Returns true if the mesh should render, otherwise false.
  85563. * @param mesh The mesh to render
  85564. * @returns true if it should render otherwise false
  85565. */
  85566. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85567. return this.hasMesh(mesh);
  85568. };
  85569. /**
  85570. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85571. * @param mesh The mesh to exclude from the glow layer
  85572. */
  85573. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85574. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85575. this._excludedMeshes.push(mesh.uniqueId);
  85576. }
  85577. };
  85578. /**
  85579. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85580. * @param mesh The mesh to remove
  85581. */
  85582. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85583. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85584. if (index !== -1) {
  85585. this._excludedMeshes.splice(index, 1);
  85586. }
  85587. };
  85588. /**
  85589. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85590. * @param mesh The mesh to include in the glow layer
  85591. */
  85592. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85593. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85594. this._includedOnlyMeshes.push(mesh.uniqueId);
  85595. }
  85596. };
  85597. /**
  85598. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85599. * @param mesh The mesh to remove
  85600. */
  85601. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85602. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85603. if (index !== -1) {
  85604. this._includedOnlyMeshes.splice(index, 1);
  85605. }
  85606. };
  85607. /**
  85608. * Determine if a given mesh will be used in the glow layer
  85609. * @param mesh The mesh to test
  85610. * @returns true if the mesh will be highlighted by the current glow layer
  85611. */
  85612. GlowLayer.prototype.hasMesh = function (mesh) {
  85613. // Included Mesh
  85614. if (this._includedOnlyMeshes.length) {
  85615. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85616. }
  85617. ;
  85618. // Excluded Mesh
  85619. if (this._excludedMeshes.length) {
  85620. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85621. }
  85622. ;
  85623. return true;
  85624. };
  85625. /**
  85626. * Free any resources and references associated to a mesh.
  85627. * Internal use
  85628. * @param mesh The mesh to free.
  85629. */
  85630. GlowLayer.prototype._disposeMesh = function (mesh) {
  85631. this.removeIncludedOnlyMesh(mesh);
  85632. this.removeExcludedMesh(mesh);
  85633. };
  85634. /**
  85635. * Effect Name of the layer.
  85636. */
  85637. GlowLayer.EffectName = "GlowLayer";
  85638. /**
  85639. * The default blur kernel size used for the glow.
  85640. */
  85641. GlowLayer.DefaultBlurKernelSize = 32;
  85642. /**
  85643. * The default texture size ratio used for the glow.
  85644. */
  85645. GlowLayer.DefaultTextureRatio = 0.5;
  85646. return GlowLayer;
  85647. }(BABYLON.EffectLayer));
  85648. BABYLON.GlowLayer = GlowLayer;
  85649. })(BABYLON || (BABYLON = {}));
  85650. //# sourceMappingURL=babylon.glowLayer.js.map
  85651. var BABYLON;
  85652. (function (BABYLON) {
  85653. /**
  85654. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85655. */
  85656. var AssetTaskState;
  85657. (function (AssetTaskState) {
  85658. /**
  85659. * Initialization
  85660. */
  85661. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85662. /**
  85663. * Running
  85664. */
  85665. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85666. /**
  85667. * Done
  85668. */
  85669. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85670. /**
  85671. * Error
  85672. */
  85673. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85674. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85675. /**
  85676. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85677. */
  85678. var AbstractAssetTask = /** @class */ (function () {
  85679. /**
  85680. * Creates a new {BABYLON.AssetsManager}
  85681. * @param name defines the name of the task
  85682. */
  85683. function AbstractAssetTask(
  85684. /**
  85685. * Task name
  85686. */ name) {
  85687. this.name = name;
  85688. this._isCompleted = false;
  85689. this._taskState = AssetTaskState.INIT;
  85690. }
  85691. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85692. /**
  85693. * Get if the task is completed
  85694. */
  85695. get: function () {
  85696. return this._isCompleted;
  85697. },
  85698. enumerable: true,
  85699. configurable: true
  85700. });
  85701. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85702. /**
  85703. * Gets the current state of the task
  85704. */
  85705. get: function () {
  85706. return this._taskState;
  85707. },
  85708. enumerable: true,
  85709. configurable: true
  85710. });
  85711. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85712. /**
  85713. * Gets the current error object (if task is in error)
  85714. */
  85715. get: function () {
  85716. return this._errorObject;
  85717. },
  85718. enumerable: true,
  85719. configurable: true
  85720. });
  85721. /**
  85722. * Internal only
  85723. * @ignore
  85724. */
  85725. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85726. if (this._errorObject) {
  85727. return;
  85728. }
  85729. this._errorObject = {
  85730. message: message,
  85731. exception: exception
  85732. };
  85733. };
  85734. /**
  85735. * Execute the current task
  85736. * @param scene defines the scene where you want your assets to be loaded
  85737. * @param onSuccess is a callback called when the task is successfully executed
  85738. * @param onError is a callback called if an error occurs
  85739. */
  85740. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85741. var _this = this;
  85742. this._taskState = AssetTaskState.RUNNING;
  85743. this.runTask(scene, function () {
  85744. _this.onDoneCallback(onSuccess, onError);
  85745. }, function (msg, exception) {
  85746. _this.onErrorCallback(onError, msg, exception);
  85747. });
  85748. };
  85749. /**
  85750. * Execute the current task
  85751. * @param scene defines the scene where you want your assets to be loaded
  85752. * @param onSuccess is a callback called when the task is successfully executed
  85753. * @param onError is a callback called if an error occurs
  85754. */
  85755. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85756. throw new Error("runTask is not implemented");
  85757. };
  85758. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85759. this._taskState = AssetTaskState.ERROR;
  85760. this._errorObject = {
  85761. message: message,
  85762. exception: exception
  85763. };
  85764. if (this.onError) {
  85765. this.onError(this, message, exception);
  85766. }
  85767. onError();
  85768. };
  85769. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85770. try {
  85771. this._taskState = AssetTaskState.DONE;
  85772. this._isCompleted = true;
  85773. if (this.onSuccess) {
  85774. this.onSuccess(this);
  85775. }
  85776. onSuccess();
  85777. }
  85778. catch (e) {
  85779. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85780. }
  85781. };
  85782. return AbstractAssetTask;
  85783. }());
  85784. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85785. /**
  85786. * Class used to share progress information about assets loading
  85787. */
  85788. var AssetsProgressEvent = /** @class */ (function () {
  85789. /**
  85790. * Creates a {BABYLON.AssetsProgressEvent}
  85791. * @param remainingCount defines the number of remaining tasks to process
  85792. * @param totalCount defines the total number of tasks
  85793. * @param task defines the task that was just processed
  85794. */
  85795. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85796. this.remainingCount = remainingCount;
  85797. this.totalCount = totalCount;
  85798. this.task = task;
  85799. }
  85800. return AssetsProgressEvent;
  85801. }());
  85802. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85803. /**
  85804. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85805. */
  85806. var MeshAssetTask = /** @class */ (function (_super) {
  85807. __extends(MeshAssetTask, _super);
  85808. /**
  85809. * Creates a new {BABYLON.MeshAssetTask}
  85810. * @param name defines the name of the task
  85811. * @param meshesNames defines the list of mesh's names you want to load
  85812. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85813. * @param sceneFilename defines the filename of the scene to load from
  85814. */
  85815. function MeshAssetTask(
  85816. /**
  85817. * Defines the name of the task
  85818. */
  85819. name,
  85820. /**
  85821. * Defines the list of mesh's names you want to load
  85822. */
  85823. meshesNames,
  85824. /**
  85825. * Defines the root url to use as a base to load your meshes and associated resources
  85826. */
  85827. rootUrl,
  85828. /**
  85829. * Defines the filename of the scene to load from
  85830. */
  85831. sceneFilename) {
  85832. var _this = _super.call(this, name) || this;
  85833. _this.name = name;
  85834. _this.meshesNames = meshesNames;
  85835. _this.rootUrl = rootUrl;
  85836. _this.sceneFilename = sceneFilename;
  85837. return _this;
  85838. }
  85839. /**
  85840. * Execute the current task
  85841. * @param scene defines the scene where you want your assets to be loaded
  85842. * @param onSuccess is a callback called when the task is successfully executed
  85843. * @param onError is a callback called if an error occurs
  85844. */
  85845. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85846. var _this = this;
  85847. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85848. _this.loadedMeshes = meshes;
  85849. _this.loadedParticleSystems = particleSystems;
  85850. _this.loadedSkeletons = skeletons;
  85851. onSuccess();
  85852. }, null, function (scene, message, exception) {
  85853. onError(message, exception);
  85854. });
  85855. };
  85856. return MeshAssetTask;
  85857. }(AbstractAssetTask));
  85858. BABYLON.MeshAssetTask = MeshAssetTask;
  85859. /**
  85860. * Define a task used by {BABYLON.AssetsManager} to load text content
  85861. */
  85862. var TextFileAssetTask = /** @class */ (function (_super) {
  85863. __extends(TextFileAssetTask, _super);
  85864. /**
  85865. * Creates a new TextFileAssetTask object
  85866. * @param name defines the name of the task
  85867. * @param url defines the location of the file to load
  85868. */
  85869. function TextFileAssetTask(
  85870. /**
  85871. * Defines the name of the task
  85872. */
  85873. name,
  85874. /**
  85875. * Defines the location of the file to load
  85876. */
  85877. url) {
  85878. var _this = _super.call(this, name) || this;
  85879. _this.name = name;
  85880. _this.url = url;
  85881. return _this;
  85882. }
  85883. /**
  85884. * Execute the current task
  85885. * @param scene defines the scene where you want your assets to be loaded
  85886. * @param onSuccess is a callback called when the task is successfully executed
  85887. * @param onError is a callback called if an error occurs
  85888. */
  85889. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85890. var _this = this;
  85891. scene._loadFile(this.url, function (data) {
  85892. _this.text = data;
  85893. onSuccess();
  85894. }, undefined, false, false, function (request, exception) {
  85895. if (request) {
  85896. onError(request.status + " " + request.statusText, exception);
  85897. }
  85898. });
  85899. };
  85900. return TextFileAssetTask;
  85901. }(AbstractAssetTask));
  85902. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85903. /**
  85904. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85905. */
  85906. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85907. __extends(BinaryFileAssetTask, _super);
  85908. /**
  85909. * Creates a new BinaryFileAssetTask object
  85910. * @param name defines the name of the new task
  85911. * @param url defines the location of the file to load
  85912. */
  85913. function BinaryFileAssetTask(
  85914. /**
  85915. * Defines the name of the task
  85916. */
  85917. name,
  85918. /**
  85919. * Defines the location of the file to load
  85920. */
  85921. url) {
  85922. var _this = _super.call(this, name) || this;
  85923. _this.name = name;
  85924. _this.url = url;
  85925. return _this;
  85926. }
  85927. /**
  85928. * Execute the current task
  85929. * @param scene defines the scene where you want your assets to be loaded
  85930. * @param onSuccess is a callback called when the task is successfully executed
  85931. * @param onError is a callback called if an error occurs
  85932. */
  85933. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85934. var _this = this;
  85935. scene._loadFile(this.url, function (data) {
  85936. _this.data = data;
  85937. onSuccess();
  85938. }, undefined, true, true, function (request, exception) {
  85939. if (request) {
  85940. onError(request.status + " " + request.statusText, exception);
  85941. }
  85942. });
  85943. };
  85944. return BinaryFileAssetTask;
  85945. }(AbstractAssetTask));
  85946. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85947. /**
  85948. * Define a task used by {BABYLON.AssetsManager} to load images
  85949. */
  85950. var ImageAssetTask = /** @class */ (function (_super) {
  85951. __extends(ImageAssetTask, _super);
  85952. /**
  85953. * Creates a new ImageAssetTask
  85954. * @param name defines the name of the task
  85955. * @param url defines the location of the image to load
  85956. */
  85957. function ImageAssetTask(
  85958. /**
  85959. * Defines the name of the task
  85960. */
  85961. name,
  85962. /**
  85963. * Defines the location of the image to load
  85964. */
  85965. url) {
  85966. var _this = _super.call(this, name) || this;
  85967. _this.name = name;
  85968. _this.url = url;
  85969. return _this;
  85970. }
  85971. /**
  85972. * Execute the current task
  85973. * @param scene defines the scene where you want your assets to be loaded
  85974. * @param onSuccess is a callback called when the task is successfully executed
  85975. * @param onError is a callback called if an error occurs
  85976. */
  85977. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85978. var _this = this;
  85979. var img = new Image();
  85980. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85981. img.onload = function () {
  85982. _this.image = img;
  85983. onSuccess();
  85984. };
  85985. img.onerror = function (err) {
  85986. onError("Error loading image", err);
  85987. };
  85988. img.src = this.url;
  85989. };
  85990. return ImageAssetTask;
  85991. }(AbstractAssetTask));
  85992. BABYLON.ImageAssetTask = ImageAssetTask;
  85993. /**
  85994. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85995. */
  85996. var TextureAssetTask = /** @class */ (function (_super) {
  85997. __extends(TextureAssetTask, _super);
  85998. /**
  85999. * Creates a new TextureAssetTask object
  86000. * @param name defines the name of the task
  86001. * @param url defines the location of the file to load
  86002. * @param noMipmap defines if mipmap should not be generated (default is false)
  86003. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86004. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86005. */
  86006. function TextureAssetTask(
  86007. /**
  86008. * Defines the name of the task
  86009. */
  86010. name,
  86011. /**
  86012. * Defines the location of the file to load
  86013. */
  86014. url,
  86015. /**
  86016. * Defines if mipmap should not be generated (default is false)
  86017. */
  86018. noMipmap,
  86019. /**
  86020. * Defines if texture must be inverted on Y axis (default is false)
  86021. */
  86022. invertY,
  86023. /**
  86024. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86025. */
  86026. samplingMode) {
  86027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86028. var _this = _super.call(this, name) || this;
  86029. _this.name = name;
  86030. _this.url = url;
  86031. _this.noMipmap = noMipmap;
  86032. _this.invertY = invertY;
  86033. _this.samplingMode = samplingMode;
  86034. return _this;
  86035. }
  86036. /**
  86037. * Execute the current task
  86038. * @param scene defines the scene where you want your assets to be loaded
  86039. * @param onSuccess is a callback called when the task is successfully executed
  86040. * @param onError is a callback called if an error occurs
  86041. */
  86042. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86043. var onload = function () {
  86044. onSuccess();
  86045. };
  86046. var onerror = function (message, exception) {
  86047. onError(message, exception);
  86048. };
  86049. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86050. };
  86051. return TextureAssetTask;
  86052. }(AbstractAssetTask));
  86053. BABYLON.TextureAssetTask = TextureAssetTask;
  86054. /**
  86055. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86056. */
  86057. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86058. __extends(CubeTextureAssetTask, _super);
  86059. /**
  86060. * Creates a new CubeTextureAssetTask
  86061. * @param name defines the name of the task
  86062. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86063. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86064. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86065. * @param files defines the explicit list of files (undefined by default)
  86066. */
  86067. function CubeTextureAssetTask(
  86068. /**
  86069. * Defines the name of the task
  86070. */
  86071. name,
  86072. /**
  86073. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86074. */
  86075. url,
  86076. /**
  86077. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86078. */
  86079. extensions,
  86080. /**
  86081. * Defines if mipmaps should not be generated (default is false)
  86082. */
  86083. noMipmap,
  86084. /**
  86085. * Defines the explicit list of files (undefined by default)
  86086. */
  86087. files) {
  86088. var _this = _super.call(this, name) || this;
  86089. _this.name = name;
  86090. _this.url = url;
  86091. _this.extensions = extensions;
  86092. _this.noMipmap = noMipmap;
  86093. _this.files = files;
  86094. return _this;
  86095. }
  86096. /**
  86097. * Execute the current task
  86098. * @param scene defines the scene where you want your assets to be loaded
  86099. * @param onSuccess is a callback called when the task is successfully executed
  86100. * @param onError is a callback called if an error occurs
  86101. */
  86102. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86103. var onload = function () {
  86104. onSuccess();
  86105. };
  86106. var onerror = function (message, exception) {
  86107. onError(message, exception);
  86108. };
  86109. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86110. };
  86111. return CubeTextureAssetTask;
  86112. }(AbstractAssetTask));
  86113. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86114. /**
  86115. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86116. */
  86117. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86118. __extends(HDRCubeTextureAssetTask, _super);
  86119. /**
  86120. * Creates a new HDRCubeTextureAssetTask object
  86121. * @param name defines the name of the task
  86122. * @param url defines the location of the file to load
  86123. * @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.
  86124. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86125. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86126. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  86127. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86128. */
  86129. function HDRCubeTextureAssetTask(
  86130. /**
  86131. * Defines the name of the task
  86132. */
  86133. name,
  86134. /**
  86135. * Defines the location of the file to load
  86136. */
  86137. url,
  86138. /**
  86139. * 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.
  86140. */
  86141. size,
  86142. /**
  86143. * Defines if mipmaps should not be generated (default is false)
  86144. */
  86145. noMipmap,
  86146. /**
  86147. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86148. */
  86149. generateHarmonics,
  86150. /**
  86151. * 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)
  86152. */
  86153. useInGammaSpace,
  86154. /**
  86155. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86156. */
  86157. usePMREMGenerator) {
  86158. if (noMipmap === void 0) { noMipmap = false; }
  86159. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86160. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86161. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86162. var _this = _super.call(this, name) || this;
  86163. _this.name = name;
  86164. _this.url = url;
  86165. _this.size = size;
  86166. _this.noMipmap = noMipmap;
  86167. _this.generateHarmonics = generateHarmonics;
  86168. _this.useInGammaSpace = useInGammaSpace;
  86169. _this.usePMREMGenerator = usePMREMGenerator;
  86170. return _this;
  86171. }
  86172. /**
  86173. * Execute the current task
  86174. * @param scene defines the scene where you want your assets to be loaded
  86175. * @param onSuccess is a callback called when the task is successfully executed
  86176. * @param onError is a callback called if an error occurs
  86177. */
  86178. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86179. var onload = function () {
  86180. onSuccess();
  86181. };
  86182. var onerror = function (message, exception) {
  86183. onError(message, exception);
  86184. };
  86185. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86186. };
  86187. return HDRCubeTextureAssetTask;
  86188. }(AbstractAssetTask));
  86189. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86190. /**
  86191. * This class can be used to easily import assets into a scene
  86192. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86193. */
  86194. var AssetsManager = /** @class */ (function () {
  86195. /**
  86196. * Creates a new AssetsManager
  86197. * @param scene defines the scene to work on
  86198. */
  86199. function AssetsManager(scene) {
  86200. this._isLoading = false;
  86201. this._tasks = new Array();
  86202. this._waitingTasksCount = 0;
  86203. this._totalTasksCount = 0;
  86204. /**
  86205. * Observable called when all tasks are processed
  86206. */
  86207. this.onTaskSuccessObservable = new BABYLON.Observable();
  86208. /**
  86209. * Observable called when a task had an error
  86210. */
  86211. this.onTaskErrorObservable = new BABYLON.Observable();
  86212. /**
  86213. * Observable called when a task is successful
  86214. */
  86215. this.onTasksDoneObservable = new BABYLON.Observable();
  86216. /**
  86217. * Observable called when a task is done (whatever the result is)
  86218. */
  86219. this.onProgressObservable = new BABYLON.Observable();
  86220. /**
  86221. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86222. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86223. */
  86224. this.useDefaultLoadingScreen = true;
  86225. this._scene = scene;
  86226. }
  86227. /**
  86228. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86229. * @param taskName defines the name of the new task
  86230. * @param meshesNames defines the name of meshes to load
  86231. * @param rootUrl defines the root url to use to locate files
  86232. * @param sceneFilename defines the filename of the scene file
  86233. * @returns a new {BABYLON.MeshAssetTask} object
  86234. */
  86235. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86236. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86237. this._tasks.push(task);
  86238. return task;
  86239. };
  86240. /**
  86241. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86242. * @param taskName defines the name of the new task
  86243. * @param url defines the url of the file to load
  86244. * @returns a new {BABYLON.TextFileAssetTask} object
  86245. */
  86246. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86247. var task = new TextFileAssetTask(taskName, url);
  86248. this._tasks.push(task);
  86249. return task;
  86250. };
  86251. /**
  86252. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86253. * @param taskName defines the name of the new task
  86254. * @param url defines the url of the file to load
  86255. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86256. */
  86257. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86258. var task = new BinaryFileAssetTask(taskName, url);
  86259. this._tasks.push(task);
  86260. return task;
  86261. };
  86262. /**
  86263. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86264. * @param taskName defines the name of the new task
  86265. * @param url defines the url of the file to load
  86266. * @returns a new {BABYLON.ImageAssetTask} object
  86267. */
  86268. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86269. var task = new ImageAssetTask(taskName, url);
  86270. this._tasks.push(task);
  86271. return task;
  86272. };
  86273. /**
  86274. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86275. * @param taskName defines the name of the new task
  86276. * @param url defines the url of the file to load
  86277. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86278. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86279. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86280. * @returns a new {BABYLON.TextureAssetTask} object
  86281. */
  86282. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86284. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86285. this._tasks.push(task);
  86286. return task;
  86287. };
  86288. /**
  86289. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86290. * @param taskName defines the name of the new task
  86291. * @param url defines the url of the file to load
  86292. * @param extensions defines the extension to use to load the cube map (can be null)
  86293. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86294. * @param files defines the list of files to load (can be null)
  86295. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86296. */
  86297. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86298. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86299. this._tasks.push(task);
  86300. return task;
  86301. };
  86302. /**
  86303. *
  86304. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86305. * @param taskName defines the name of the new task
  86306. * @param url defines the url of the file to load
  86307. * @param size defines the size you want for the cubemap (can be null)
  86308. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86309. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86310. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86311. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86312. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86313. */
  86314. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86315. if (noMipmap === void 0) { noMipmap = false; }
  86316. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86317. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86318. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86319. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86320. this._tasks.push(task);
  86321. return task;
  86322. };
  86323. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86324. var _this = this;
  86325. this._waitingTasksCount--;
  86326. try {
  86327. if (task.taskState === AssetTaskState.DONE) {
  86328. // Let's remove successfull tasks
  86329. BABYLON.Tools.SetImmediate(function () {
  86330. var index = _this._tasks.indexOf(task);
  86331. if (index > -1) {
  86332. _this._tasks.splice(index, 1);
  86333. }
  86334. });
  86335. }
  86336. if (this.onProgress) {
  86337. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86338. }
  86339. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86340. }
  86341. catch (e) {
  86342. BABYLON.Tools.Error("Error running progress callbacks.");
  86343. console.log(e);
  86344. }
  86345. if (this._waitingTasksCount === 0) {
  86346. try {
  86347. if (this.onFinish) {
  86348. this.onFinish(this._tasks);
  86349. }
  86350. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86351. }
  86352. catch (e) {
  86353. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86354. console.log(e);
  86355. }
  86356. this._isLoading = false;
  86357. this._scene.getEngine().hideLoadingUI();
  86358. }
  86359. };
  86360. AssetsManager.prototype._runTask = function (task) {
  86361. var _this = this;
  86362. var done = function () {
  86363. try {
  86364. if (_this.onTaskSuccess) {
  86365. _this.onTaskSuccess(task);
  86366. }
  86367. _this.onTaskSuccessObservable.notifyObservers(task);
  86368. _this._decreaseWaitingTasksCount(task);
  86369. }
  86370. catch (e) {
  86371. error("Error executing task success callbacks", e);
  86372. }
  86373. };
  86374. var error = function (message, exception) {
  86375. task._setErrorObject(message, exception);
  86376. if (_this.onTaskError) {
  86377. _this.onTaskError(task);
  86378. }
  86379. _this.onTaskErrorObservable.notifyObservers(task);
  86380. _this._decreaseWaitingTasksCount(task);
  86381. };
  86382. task.run(this._scene, done, error);
  86383. };
  86384. /**
  86385. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86386. * @return the current instance of the {BABYLON.AssetsManager}
  86387. */
  86388. AssetsManager.prototype.reset = function () {
  86389. this._isLoading = false;
  86390. this._tasks = new Array();
  86391. return this;
  86392. };
  86393. /**
  86394. * Start the loading process
  86395. * @return the current instance of the {BABYLON.AssetsManager}
  86396. */
  86397. AssetsManager.prototype.load = function () {
  86398. if (this._isLoading) {
  86399. return this;
  86400. }
  86401. this._isLoading = true;
  86402. this._waitingTasksCount = this._tasks.length;
  86403. this._totalTasksCount = this._tasks.length;
  86404. if (this._waitingTasksCount === 0) {
  86405. this._isLoading = false;
  86406. if (this.onFinish) {
  86407. this.onFinish(this._tasks);
  86408. }
  86409. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86410. return this;
  86411. }
  86412. if (this.useDefaultLoadingScreen) {
  86413. this._scene.getEngine().displayLoadingUI();
  86414. }
  86415. for (var index = 0; index < this._tasks.length; index++) {
  86416. var task = this._tasks[index];
  86417. this._runTask(task);
  86418. }
  86419. return this;
  86420. };
  86421. return AssetsManager;
  86422. }());
  86423. BABYLON.AssetsManager = AssetsManager;
  86424. })(BABYLON || (BABYLON = {}));
  86425. //# sourceMappingURL=babylon.assetsManager.js.map
  86426. var BABYLON;
  86427. (function (BABYLON) {
  86428. var serializedGeometries = [];
  86429. var serializeGeometry = function (geometry, serializationGeometries) {
  86430. if (serializedGeometries[geometry.id]) {
  86431. return;
  86432. }
  86433. if (geometry.doNotSerialize) {
  86434. return;
  86435. }
  86436. if (geometry instanceof BABYLON.BoxGeometry) {
  86437. serializationGeometries.boxes.push(geometry.serialize());
  86438. }
  86439. else if (geometry instanceof BABYLON.SphereGeometry) {
  86440. serializationGeometries.spheres.push(geometry.serialize());
  86441. }
  86442. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86443. serializationGeometries.cylinders.push(geometry.serialize());
  86444. }
  86445. else if (geometry instanceof BABYLON.TorusGeometry) {
  86446. serializationGeometries.toruses.push(geometry.serialize());
  86447. }
  86448. else if (geometry instanceof BABYLON.GroundGeometry) {
  86449. serializationGeometries.grounds.push(geometry.serialize());
  86450. }
  86451. else if (geometry instanceof BABYLON.Plane) {
  86452. serializationGeometries.planes.push(geometry.serialize());
  86453. }
  86454. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86455. serializationGeometries.torusKnots.push(geometry.serialize());
  86456. }
  86457. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86458. throw new Error("Unknown primitive type");
  86459. }
  86460. else {
  86461. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86462. }
  86463. serializedGeometries[geometry.id] = true;
  86464. };
  86465. var serializeMesh = function (mesh, serializationScene) {
  86466. var serializationObject = {};
  86467. // Geometry
  86468. var geometry = mesh._geometry;
  86469. if (geometry) {
  86470. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86471. // 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
  86472. serializeGeometry(geometry, serializationScene.geometries);
  86473. }
  86474. }
  86475. // Custom
  86476. if (mesh.serialize) {
  86477. mesh.serialize(serializationObject);
  86478. }
  86479. return serializationObject;
  86480. };
  86481. var finalizeSingleMesh = function (mesh, serializationObject) {
  86482. //only works if the mesh is already loaded
  86483. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86484. //serialize material
  86485. if (mesh.material) {
  86486. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86487. serializationObject.materials = serializationObject.materials || [];
  86488. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86489. serializationObject.materials.push(mesh.material.serialize());
  86490. }
  86491. }
  86492. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86493. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86494. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86495. serializationObject.multiMaterials.push(mesh.material.serialize());
  86496. }
  86497. }
  86498. }
  86499. //serialize geometry
  86500. var geometry = mesh._geometry;
  86501. if (geometry) {
  86502. if (!serializationObject.geometries) {
  86503. serializationObject.geometries = {};
  86504. serializationObject.geometries.boxes = [];
  86505. serializationObject.geometries.spheres = [];
  86506. serializationObject.geometries.cylinders = [];
  86507. serializationObject.geometries.toruses = [];
  86508. serializationObject.geometries.grounds = [];
  86509. serializationObject.geometries.planes = [];
  86510. serializationObject.geometries.torusKnots = [];
  86511. serializationObject.geometries.vertexData = [];
  86512. }
  86513. serializeGeometry(geometry, serializationObject.geometries);
  86514. }
  86515. // Skeletons
  86516. if (mesh.skeleton) {
  86517. serializationObject.skeletons = serializationObject.skeletons || [];
  86518. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86519. }
  86520. //serialize the actual mesh
  86521. serializationObject.meshes = serializationObject.meshes || [];
  86522. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86523. }
  86524. };
  86525. var SceneSerializer = /** @class */ (function () {
  86526. function SceneSerializer() {
  86527. }
  86528. SceneSerializer.ClearCache = function () {
  86529. serializedGeometries = [];
  86530. };
  86531. SceneSerializer.Serialize = function (scene) {
  86532. var serializationObject = {};
  86533. SceneSerializer.ClearCache();
  86534. // Scene
  86535. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86536. serializationObject.autoClear = scene.autoClear;
  86537. serializationObject.clearColor = scene.clearColor.asArray();
  86538. serializationObject.ambientColor = scene.ambientColor.asArray();
  86539. serializationObject.gravity = scene.gravity.asArray();
  86540. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86541. serializationObject.workerCollisions = scene.workerCollisions;
  86542. // Fog
  86543. if (scene.fogMode && scene.fogMode !== 0) {
  86544. serializationObject.fogMode = scene.fogMode;
  86545. serializationObject.fogColor = scene.fogColor.asArray();
  86546. serializationObject.fogStart = scene.fogStart;
  86547. serializationObject.fogEnd = scene.fogEnd;
  86548. serializationObject.fogDensity = scene.fogDensity;
  86549. }
  86550. //Physics
  86551. if (scene.isPhysicsEnabled()) {
  86552. var physicEngine = scene.getPhysicsEngine();
  86553. if (physicEngine) {
  86554. serializationObject.physicsEnabled = true;
  86555. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86556. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86557. }
  86558. }
  86559. // Metadata
  86560. if (scene.metadata) {
  86561. serializationObject.metadata = scene.metadata;
  86562. }
  86563. // Morph targets
  86564. serializationObject.morphTargetManagers = [];
  86565. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86566. var abstractMesh = _a[_i];
  86567. var manager = abstractMesh.morphTargetManager;
  86568. if (manager) {
  86569. serializationObject.morphTargetManagers.push(manager.serialize());
  86570. }
  86571. }
  86572. // Lights
  86573. serializationObject.lights = [];
  86574. var index;
  86575. var light;
  86576. for (index = 0; index < scene.lights.length; index++) {
  86577. light = scene.lights[index];
  86578. if (!light.doNotSerialize) {
  86579. serializationObject.lights.push(light.serialize());
  86580. }
  86581. }
  86582. // Cameras
  86583. serializationObject.cameras = [];
  86584. for (index = 0; index < scene.cameras.length; index++) {
  86585. var camera = scene.cameras[index];
  86586. if (!camera.doNotSerialize) {
  86587. serializationObject.cameras.push(camera.serialize());
  86588. }
  86589. }
  86590. if (scene.activeCamera) {
  86591. serializationObject.activeCameraID = scene.activeCamera.id;
  86592. }
  86593. // Animations
  86594. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86595. // Materials
  86596. serializationObject.materials = [];
  86597. serializationObject.multiMaterials = [];
  86598. var material;
  86599. for (index = 0; index < scene.materials.length; index++) {
  86600. material = scene.materials[index];
  86601. if (!material.doNotSerialize) {
  86602. serializationObject.materials.push(material.serialize());
  86603. }
  86604. }
  86605. // MultiMaterials
  86606. serializationObject.multiMaterials = [];
  86607. for (index = 0; index < scene.multiMaterials.length; index++) {
  86608. var multiMaterial = scene.multiMaterials[index];
  86609. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86610. }
  86611. // Environment texture
  86612. if (scene.environmentTexture) {
  86613. serializationObject.environmentTexture = scene.environmentTexture.name;
  86614. }
  86615. // Skeletons
  86616. serializationObject.skeletons = [];
  86617. for (index = 0; index < scene.skeletons.length; index++) {
  86618. var skeleton = scene.skeletons[index];
  86619. if (!skeleton.doNotSerialize) {
  86620. serializationObject.skeletons.push(skeleton.serialize());
  86621. }
  86622. }
  86623. // Transform nodes
  86624. serializationObject.transformNodes = [];
  86625. for (index = 0; index < scene.transformNodes.length; index++) {
  86626. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86627. }
  86628. // Geometries
  86629. serializationObject.geometries = {};
  86630. serializationObject.geometries.boxes = [];
  86631. serializationObject.geometries.spheres = [];
  86632. serializationObject.geometries.cylinders = [];
  86633. serializationObject.geometries.toruses = [];
  86634. serializationObject.geometries.grounds = [];
  86635. serializationObject.geometries.planes = [];
  86636. serializationObject.geometries.torusKnots = [];
  86637. serializationObject.geometries.vertexData = [];
  86638. serializedGeometries = [];
  86639. var geometries = scene.getGeometries();
  86640. for (index = 0; index < geometries.length; index++) {
  86641. var geometry = geometries[index];
  86642. if (geometry.isReady()) {
  86643. serializeGeometry(geometry, serializationObject.geometries);
  86644. }
  86645. }
  86646. // Meshes
  86647. serializationObject.meshes = [];
  86648. for (index = 0; index < scene.meshes.length; index++) {
  86649. var abstractMesh = scene.meshes[index];
  86650. if (abstractMesh instanceof BABYLON.Mesh) {
  86651. var mesh = abstractMesh;
  86652. if (!mesh.doNotSerialize) {
  86653. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86654. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86655. }
  86656. }
  86657. }
  86658. }
  86659. // Particles Systems
  86660. serializationObject.particleSystems = [];
  86661. for (index = 0; index < scene.particleSystems.length; index++) {
  86662. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86663. }
  86664. // Lens flares
  86665. serializationObject.lensFlareSystems = [];
  86666. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86667. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86668. }
  86669. // Shadows
  86670. serializationObject.shadowGenerators = [];
  86671. for (index = 0; index < scene.lights.length; index++) {
  86672. light = scene.lights[index];
  86673. var shadowGenerator = light.getShadowGenerator();
  86674. if (shadowGenerator) {
  86675. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86676. }
  86677. }
  86678. // Action Manager
  86679. if (scene.actionManager) {
  86680. serializationObject.actions = scene.actionManager.serialize("scene");
  86681. }
  86682. // Audio
  86683. serializationObject.sounds = [];
  86684. for (index = 0; index < scene.soundTracks.length; index++) {
  86685. var soundtrack = scene.soundTracks[index];
  86686. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86687. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86688. }
  86689. }
  86690. return serializationObject;
  86691. };
  86692. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86693. if (withParents === void 0) { withParents = false; }
  86694. if (withChildren === void 0) { withChildren = false; }
  86695. var serializationObject = {};
  86696. SceneSerializer.ClearCache();
  86697. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86698. if (withParents || withChildren) {
  86699. //deliberate for loop! not for each, appended should be processed as well.
  86700. for (var i = 0; i < toSerialize.length; ++i) {
  86701. if (withChildren) {
  86702. toSerialize[i].getDescendants().forEach(function (node) {
  86703. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86704. toSerialize.push(node);
  86705. }
  86706. });
  86707. }
  86708. //make sure the array doesn't contain the object already
  86709. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86710. toSerialize.push(toSerialize[i].parent);
  86711. }
  86712. }
  86713. }
  86714. toSerialize.forEach(function (mesh) {
  86715. finalizeSingleMesh(mesh, serializationObject);
  86716. });
  86717. return serializationObject;
  86718. };
  86719. return SceneSerializer;
  86720. }());
  86721. BABYLON.SceneSerializer = SceneSerializer;
  86722. })(BABYLON || (BABYLON = {}));
  86723. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86724. var BABYLON;
  86725. (function (BABYLON) {
  86726. var ReflectionProbe = /** @class */ (function () {
  86727. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86728. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86729. var _this = this;
  86730. this.name = name;
  86731. this._viewMatrix = BABYLON.Matrix.Identity();
  86732. this._target = BABYLON.Vector3.Zero();
  86733. this._add = BABYLON.Vector3.Zero();
  86734. this._invertYAxis = false;
  86735. this.position = BABYLON.Vector3.Zero();
  86736. this._scene = scene;
  86737. this._scene.reflectionProbes.push(this);
  86738. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86739. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86740. switch (faceIndex) {
  86741. case 0:
  86742. _this._add.copyFromFloats(1, 0, 0);
  86743. break;
  86744. case 1:
  86745. _this._add.copyFromFloats(-1, 0, 0);
  86746. break;
  86747. case 2:
  86748. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86749. break;
  86750. case 3:
  86751. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86752. break;
  86753. case 4:
  86754. _this._add.copyFromFloats(0, 0, 1);
  86755. break;
  86756. case 5:
  86757. _this._add.copyFromFloats(0, 0, -1);
  86758. break;
  86759. }
  86760. if (_this._attachedMesh) {
  86761. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86762. }
  86763. _this.position.addToRef(_this._add, _this._target);
  86764. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86765. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86766. scene._forcedViewPosition = _this.position;
  86767. });
  86768. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86769. scene._forcedViewPosition = null;
  86770. scene.updateTransformMatrix(true);
  86771. });
  86772. if (scene.activeCamera) {
  86773. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86774. }
  86775. }
  86776. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86777. get: function () {
  86778. return this._renderTargetTexture.samples;
  86779. },
  86780. set: function (value) {
  86781. this._renderTargetTexture.samples = value;
  86782. },
  86783. enumerable: true,
  86784. configurable: true
  86785. });
  86786. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86787. get: function () {
  86788. return this._renderTargetTexture.refreshRate;
  86789. },
  86790. set: function (value) {
  86791. this._renderTargetTexture.refreshRate = value;
  86792. },
  86793. enumerable: true,
  86794. configurable: true
  86795. });
  86796. ReflectionProbe.prototype.getScene = function () {
  86797. return this._scene;
  86798. };
  86799. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86800. get: function () {
  86801. return this._renderTargetTexture;
  86802. },
  86803. enumerable: true,
  86804. configurable: true
  86805. });
  86806. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86807. get: function () {
  86808. return this._renderTargetTexture.renderList;
  86809. },
  86810. enumerable: true,
  86811. configurable: true
  86812. });
  86813. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86814. this._attachedMesh = mesh;
  86815. };
  86816. /**
  86817. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86818. *
  86819. * @param renderingGroupId The rendering group id corresponding to its index
  86820. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86821. */
  86822. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86823. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86824. };
  86825. ReflectionProbe.prototype.dispose = function () {
  86826. var index = this._scene.reflectionProbes.indexOf(this);
  86827. if (index !== -1) {
  86828. // Remove from the scene if found
  86829. this._scene.reflectionProbes.splice(index, 1);
  86830. }
  86831. if (this._renderTargetTexture) {
  86832. this._renderTargetTexture.dispose();
  86833. this._renderTargetTexture = null;
  86834. }
  86835. };
  86836. return ReflectionProbe;
  86837. }());
  86838. BABYLON.ReflectionProbe = ReflectionProbe;
  86839. })(BABYLON || (BABYLON = {}));
  86840. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86841. var BABYLON;
  86842. (function (BABYLON) {
  86843. var Layer = /** @class */ (function () {
  86844. function Layer(name, imgUrl, scene, isBackground, color) {
  86845. this.name = name;
  86846. this.scale = new BABYLON.Vector2(1, 1);
  86847. this.offset = new BABYLON.Vector2(0, 0);
  86848. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86849. this.layerMask = 0x0FFFFFFF;
  86850. this._vertexBuffers = {};
  86851. // Events
  86852. /**
  86853. * An event triggered when the layer is disposed.
  86854. * @type {BABYLON.Observable}
  86855. */
  86856. this.onDisposeObservable = new BABYLON.Observable();
  86857. /**
  86858. * An event triggered before rendering the scene
  86859. * @type {BABYLON.Observable}
  86860. */
  86861. this.onBeforeRenderObservable = new BABYLON.Observable();
  86862. /**
  86863. * An event triggered after rendering the scene
  86864. * @type {BABYLON.Observable}
  86865. */
  86866. this.onAfterRenderObservable = new BABYLON.Observable();
  86867. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86868. this.isBackground = isBackground === undefined ? true : isBackground;
  86869. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86870. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86871. this._scene.layers.push(this);
  86872. var engine = this._scene.getEngine();
  86873. // VBO
  86874. var vertices = [];
  86875. vertices.push(1, 1);
  86876. vertices.push(-1, 1);
  86877. vertices.push(-1, -1);
  86878. vertices.push(1, -1);
  86879. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86880. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86881. this._createIndexBuffer();
  86882. // Effects
  86883. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86884. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86885. }
  86886. Object.defineProperty(Layer.prototype, "onDispose", {
  86887. set: function (callback) {
  86888. if (this._onDisposeObserver) {
  86889. this.onDisposeObservable.remove(this._onDisposeObserver);
  86890. }
  86891. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86892. },
  86893. enumerable: true,
  86894. configurable: true
  86895. });
  86896. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86897. set: function (callback) {
  86898. if (this._onBeforeRenderObserver) {
  86899. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86900. }
  86901. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86902. },
  86903. enumerable: true,
  86904. configurable: true
  86905. });
  86906. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86907. set: function (callback) {
  86908. if (this._onAfterRenderObserver) {
  86909. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86910. }
  86911. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86912. },
  86913. enumerable: true,
  86914. configurable: true
  86915. });
  86916. Layer.prototype._createIndexBuffer = function () {
  86917. var engine = this._scene.getEngine();
  86918. // Indices
  86919. var indices = [];
  86920. indices.push(0);
  86921. indices.push(1);
  86922. indices.push(2);
  86923. indices.push(0);
  86924. indices.push(2);
  86925. indices.push(3);
  86926. this._indexBuffer = engine.createIndexBuffer(indices);
  86927. };
  86928. Layer.prototype._rebuild = function () {
  86929. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86930. if (vb) {
  86931. vb._rebuild();
  86932. }
  86933. this._createIndexBuffer();
  86934. };
  86935. Layer.prototype.render = function () {
  86936. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86937. // Check
  86938. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86939. return;
  86940. var engine = this._scene.getEngine();
  86941. this.onBeforeRenderObservable.notifyObservers(this);
  86942. // Render
  86943. engine.enableEffect(currentEffect);
  86944. engine.setState(false);
  86945. // Texture
  86946. currentEffect.setTexture("textureSampler", this.texture);
  86947. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86948. // Color
  86949. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86950. // Scale / offset
  86951. currentEffect.setVector2("offset", this.offset);
  86952. currentEffect.setVector2("scale", this.scale);
  86953. // VBOs
  86954. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86955. // Draw order
  86956. if (!this.alphaTest) {
  86957. engine.setAlphaMode(this.alphaBlendingMode);
  86958. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86960. }
  86961. else {
  86962. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86963. }
  86964. this.onAfterRenderObservable.notifyObservers(this);
  86965. };
  86966. Layer.prototype.dispose = function () {
  86967. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86968. if (vertexBuffer) {
  86969. vertexBuffer.dispose();
  86970. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86971. }
  86972. if (this._indexBuffer) {
  86973. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86974. this._indexBuffer = null;
  86975. }
  86976. if (this.texture) {
  86977. this.texture.dispose();
  86978. this.texture = null;
  86979. }
  86980. // Remove from scene
  86981. var index = this._scene.layers.indexOf(this);
  86982. this._scene.layers.splice(index, 1);
  86983. // Callback
  86984. this.onDisposeObservable.notifyObservers(this);
  86985. this.onDisposeObservable.clear();
  86986. this.onAfterRenderObservable.clear();
  86987. this.onBeforeRenderObservable.clear();
  86988. };
  86989. return Layer;
  86990. }());
  86991. BABYLON.Layer = Layer;
  86992. })(BABYLON || (BABYLON = {}));
  86993. //# sourceMappingURL=babylon.layer.js.map
  86994. var BABYLON;
  86995. (function (BABYLON) {
  86996. var TextureTools = /** @class */ (function () {
  86997. function TextureTools() {
  86998. }
  86999. /**
  87000. * Uses the GPU to create a copy texture rescaled at a given size
  87001. * @param texture Texture to copy from
  87002. * @param width Desired width
  87003. * @param height Desired height
  87004. * @return Generated texture
  87005. */
  87006. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87007. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87008. var scene = texture.getScene();
  87009. var engine = scene.getEngine();
  87010. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87011. rtt.wrapU = texture.wrapU;
  87012. rtt.wrapV = texture.wrapV;
  87013. rtt.uOffset = texture.uOffset;
  87014. rtt.vOffset = texture.vOffset;
  87015. rtt.uScale = texture.uScale;
  87016. rtt.vScale = texture.vScale;
  87017. rtt.uAng = texture.uAng;
  87018. rtt.vAng = texture.vAng;
  87019. rtt.wAng = texture.wAng;
  87020. rtt.coordinatesIndex = texture.coordinatesIndex;
  87021. rtt.level = texture.level;
  87022. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87023. rtt._texture.isReady = false;
  87024. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87025. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87026. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87027. passPostProcess.getEffect().executeWhenCompiled(function () {
  87028. passPostProcess.onApply = function (effect) {
  87029. effect.setTexture("textureSampler", texture);
  87030. };
  87031. var internalTexture = rtt.getInternalTexture();
  87032. if (internalTexture) {
  87033. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87034. engine.unBindFramebuffer(internalTexture);
  87035. rtt.disposeFramebufferObjects();
  87036. passPostProcess.dispose();
  87037. internalTexture.isReady = true;
  87038. }
  87039. });
  87040. return rtt;
  87041. };
  87042. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87043. if (!scene._environmentBRDFTexture) {
  87044. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87045. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87046. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87047. scene._environmentBRDFTexture = texture;
  87048. }
  87049. return scene._environmentBRDFTexture;
  87050. };
  87051. 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=";
  87052. return TextureTools;
  87053. }());
  87054. BABYLON.TextureTools = TextureTools;
  87055. })(BABYLON || (BABYLON = {}));
  87056. //# sourceMappingURL=babylon.textureTools.js.map
  87057. var BABYLON;
  87058. (function (BABYLON) {
  87059. var FramingBehavior = /** @class */ (function () {
  87060. function FramingBehavior() {
  87061. this._mode = FramingBehavior.FitFrustumSidesMode;
  87062. this._radiusScale = 1.0;
  87063. this._positionScale = 0.5;
  87064. this._defaultElevation = 0.3;
  87065. this._elevationReturnTime = 1500;
  87066. this._elevationReturnWaitTime = 1000;
  87067. this._zoomStopsAnimation = false;
  87068. this._framingTime = 1500;
  87069. this._isPointerDown = false;
  87070. this._lastInteractionTime = -Infinity;
  87071. // Framing control
  87072. this._animatables = new Array();
  87073. this._betaIsAnimating = false;
  87074. }
  87075. Object.defineProperty(FramingBehavior.prototype, "name", {
  87076. get: function () {
  87077. return "Framing";
  87078. },
  87079. enumerable: true,
  87080. configurable: true
  87081. });
  87082. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87083. /**
  87084. * Gets current mode used by the behavior.
  87085. */
  87086. get: function () {
  87087. return this._mode;
  87088. },
  87089. /**
  87090. * Sets the current mode used by the behavior
  87091. */
  87092. set: function (mode) {
  87093. this._mode = mode;
  87094. },
  87095. enumerable: true,
  87096. configurable: true
  87097. });
  87098. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87099. /**
  87100. * Gets the scale applied to the radius
  87101. */
  87102. get: function () {
  87103. return this._radiusScale;
  87104. },
  87105. /**
  87106. * Sets the scale applied to the radius (1 by default)
  87107. */
  87108. set: function (radius) {
  87109. this._radiusScale = radius;
  87110. },
  87111. enumerable: true,
  87112. configurable: true
  87113. });
  87114. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87115. /**
  87116. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87117. */
  87118. get: function () {
  87119. return this._positionScale;
  87120. },
  87121. /**
  87122. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87123. */
  87124. set: function (scale) {
  87125. this._positionScale = scale;
  87126. },
  87127. enumerable: true,
  87128. configurable: true
  87129. });
  87130. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87131. /**
  87132. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87133. * behaviour is triggered, in radians.
  87134. */
  87135. get: function () {
  87136. return this._defaultElevation;
  87137. },
  87138. /**
  87139. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87140. * behaviour is triggered, in radians.
  87141. */
  87142. set: function (elevation) {
  87143. this._defaultElevation = elevation;
  87144. },
  87145. enumerable: true,
  87146. configurable: true
  87147. });
  87148. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87149. /**
  87150. * Gets the time (in milliseconds) taken to return to the default beta position.
  87151. * Negative value indicates camera should not return to default.
  87152. */
  87153. get: function () {
  87154. return this._elevationReturnTime;
  87155. },
  87156. /**
  87157. * Sets the time (in milliseconds) taken to return to the default beta position.
  87158. * Negative value indicates camera should not return to default.
  87159. */
  87160. set: function (speed) {
  87161. this._elevationReturnTime = speed;
  87162. },
  87163. enumerable: true,
  87164. configurable: true
  87165. });
  87166. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87167. /**
  87168. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87169. */
  87170. get: function () {
  87171. return this._elevationReturnWaitTime;
  87172. },
  87173. /**
  87174. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87175. */
  87176. set: function (time) {
  87177. this._elevationReturnWaitTime = time;
  87178. },
  87179. enumerable: true,
  87180. configurable: true
  87181. });
  87182. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87183. /**
  87184. * Gets the flag that indicates if user zooming should stop animation.
  87185. */
  87186. get: function () {
  87187. return this._zoomStopsAnimation;
  87188. },
  87189. /**
  87190. * Sets the flag that indicates if user zooming should stop animation.
  87191. */
  87192. set: function (flag) {
  87193. this._zoomStopsAnimation = flag;
  87194. },
  87195. enumerable: true,
  87196. configurable: true
  87197. });
  87198. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87199. /**
  87200. * Gets the transition time when framing the mesh, in milliseconds
  87201. */
  87202. get: function () {
  87203. return this._framingTime;
  87204. },
  87205. /**
  87206. * Sets the transition time when framing the mesh, in milliseconds
  87207. */
  87208. set: function (time) {
  87209. this._framingTime = time;
  87210. },
  87211. enumerable: true,
  87212. configurable: true
  87213. });
  87214. FramingBehavior.prototype.init = function () {
  87215. // Do notihng
  87216. };
  87217. FramingBehavior.prototype.attach = function (camera) {
  87218. var _this = this;
  87219. this._attachedCamera = camera;
  87220. var scene = this._attachedCamera.getScene();
  87221. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87222. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87223. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87224. _this._isPointerDown = true;
  87225. return;
  87226. }
  87227. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87228. _this._isPointerDown = false;
  87229. }
  87230. });
  87231. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87232. if (mesh) {
  87233. _this.zoomOnMesh(mesh);
  87234. }
  87235. });
  87236. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87237. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87238. _this._applyUserInteraction();
  87239. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87240. // back to the default position after a given timeout
  87241. _this._maintainCameraAboveGround();
  87242. });
  87243. };
  87244. FramingBehavior.prototype.detach = function () {
  87245. if (!this._attachedCamera) {
  87246. return;
  87247. }
  87248. var scene = this._attachedCamera.getScene();
  87249. if (this._onPrePointerObservableObserver) {
  87250. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87251. }
  87252. if (this._onAfterCheckInputsObserver) {
  87253. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87254. }
  87255. if (this._onMeshTargetChangedObserver) {
  87256. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87257. }
  87258. this._attachedCamera = null;
  87259. };
  87260. /**
  87261. * Targets the given mesh and updates zoom level accordingly.
  87262. * @param mesh The mesh to target.
  87263. * @param radius Optional. If a cached radius position already exists, overrides default.
  87264. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87265. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87266. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87267. */
  87268. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87269. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87270. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87271. mesh.computeWorldMatrix(true);
  87272. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87273. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87274. };
  87275. /**
  87276. * Targets the given mesh with its children and updates zoom level accordingly.
  87277. * @param mesh The mesh to target.
  87278. * @param radius Optional. If a cached radius position already exists, overrides default.
  87279. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87280. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87281. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87282. */
  87283. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87284. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87285. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87286. mesh.computeWorldMatrix(true);
  87287. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87288. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87289. };
  87290. /**
  87291. * Targets the given meshes with their children and updates zoom level accordingly.
  87292. * @param meshes The mesh to target.
  87293. * @param radius Optional. If a cached radius position already exists, overrides default.
  87294. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87295. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87296. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87297. */
  87298. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87299. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87300. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87301. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87302. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87303. for (var i = 0; i < meshes.length; i++) {
  87304. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87305. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87306. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87307. }
  87308. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87309. };
  87310. /**
  87311. * Targets the given mesh and updates zoom level accordingly.
  87312. * @param mesh The mesh to target.
  87313. * @param radius Optional. If a cached radius position already exists, overrides default.
  87314. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87315. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87316. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87317. */
  87318. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87319. var _this = this;
  87320. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87321. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87322. var zoomTarget;
  87323. if (!this._attachedCamera) {
  87324. return;
  87325. }
  87326. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87327. var bottom = minimumWorld.y;
  87328. var top = maximumWorld.y;
  87329. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87330. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87331. if (focusOnOriginXZ) {
  87332. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87333. }
  87334. else {
  87335. var centerWorld = minimumWorld.add(radiusWorld);
  87336. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87337. }
  87338. if (!this._vectorTransition) {
  87339. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87340. }
  87341. this._betaIsAnimating = true;
  87342. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87343. if (animatable) {
  87344. this._animatables.push(animatable);
  87345. }
  87346. // sets the radius and lower radius bounds
  87347. // Small delta ensures camera is not always at lower zoom limit.
  87348. var radius = 0;
  87349. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87350. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87351. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87352. radius = position;
  87353. }
  87354. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87355. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87356. if (this._attachedCamera.lowerRadiusLimit === null) {
  87357. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87358. }
  87359. }
  87360. // Set sensibilities
  87361. var extend = maximumWorld.subtract(minimumWorld).length();
  87362. this._attachedCamera.panningSensibility = 5000 / extend;
  87363. this._attachedCamera.wheelPrecision = 100 / radius;
  87364. // transition to new radius
  87365. if (!this._radiusTransition) {
  87366. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87367. }
  87368. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87369. _this.stopAllAnimations();
  87370. if (onAnimationEnd) {
  87371. onAnimationEnd();
  87372. }
  87373. if (_this._attachedCamera) {
  87374. _this._attachedCamera.storeState();
  87375. }
  87376. });
  87377. if (animatable) {
  87378. this._animatables.push(animatable);
  87379. }
  87380. };
  87381. /**
  87382. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87383. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87384. * frustum width.
  87385. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87386. * to fully enclose the mesh in the viewing frustum.
  87387. */
  87388. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87389. var size = maximumWorld.subtract(minimumWorld);
  87390. var boxVectorGlobalDiagonal = size.length();
  87391. var frustumSlope = this._getFrustumSlope();
  87392. // Formula for setting distance
  87393. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87394. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87395. // Horizon distance
  87396. var radius = radiusWithoutFraming * this._radiusScale;
  87397. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87398. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87399. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87400. var camera = this._attachedCamera;
  87401. if (!camera) {
  87402. return 0;
  87403. }
  87404. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87405. // Don't exceed the requested limit
  87406. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87407. }
  87408. // Don't exceed the upper radius limit
  87409. if (camera.upperRadiusLimit) {
  87410. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87411. }
  87412. return distance;
  87413. };
  87414. /**
  87415. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87416. * is automatically returned to its default position (expected to be above ground plane).
  87417. */
  87418. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87419. var _this = this;
  87420. if (this._elevationReturnTime < 0) {
  87421. return;
  87422. }
  87423. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87424. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87425. var limitBeta = Math.PI * 0.5;
  87426. // Bring the camera back up if below the ground plane
  87427. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87428. this._betaIsAnimating = true;
  87429. //Transition to new position
  87430. this.stopAllAnimations();
  87431. if (!this._betaTransition) {
  87432. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87433. }
  87434. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87435. _this._clearAnimationLocks();
  87436. _this.stopAllAnimations();
  87437. });
  87438. if (animatabe) {
  87439. this._animatables.push(animatabe);
  87440. }
  87441. }
  87442. };
  87443. /**
  87444. * Returns the frustum slope based on the canvas ratio and camera FOV
  87445. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87446. */
  87447. FramingBehavior.prototype._getFrustumSlope = function () {
  87448. // Calculate the viewport ratio
  87449. // Aspect Ratio is Height/Width.
  87450. var camera = this._attachedCamera;
  87451. if (!camera) {
  87452. return BABYLON.Vector2.Zero();
  87453. }
  87454. var engine = camera.getScene().getEngine();
  87455. var aspectRatio = engine.getAspectRatio(camera);
  87456. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87457. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87458. var frustumSlopeY = Math.tan(camera.fov / 2);
  87459. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87460. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87461. // along the forward vector.
  87462. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87463. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87464. };
  87465. /**
  87466. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87467. */
  87468. FramingBehavior.prototype._clearAnimationLocks = function () {
  87469. this._betaIsAnimating = false;
  87470. };
  87471. /**
  87472. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87473. */
  87474. FramingBehavior.prototype._applyUserInteraction = function () {
  87475. if (this.isUserIsMoving) {
  87476. this._lastInteractionTime = BABYLON.Tools.Now;
  87477. this.stopAllAnimations();
  87478. this._clearAnimationLocks();
  87479. }
  87480. };
  87481. /**
  87482. * Stops and removes all animations that have been applied to the camera
  87483. */
  87484. FramingBehavior.prototype.stopAllAnimations = function () {
  87485. if (this._attachedCamera) {
  87486. this._attachedCamera.animations = [];
  87487. }
  87488. while (this._animatables.length) {
  87489. if (this._animatables[0]) {
  87490. this._animatables[0].onAnimationEnd = null;
  87491. this._animatables[0].stop();
  87492. }
  87493. this._animatables.shift();
  87494. }
  87495. };
  87496. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87497. /**
  87498. * Gets a value indicating if the user is moving the camera
  87499. */
  87500. get: function () {
  87501. if (!this._attachedCamera) {
  87502. return false;
  87503. }
  87504. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87505. this._attachedCamera.inertialBetaOffset !== 0 ||
  87506. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87507. this._attachedCamera.inertialPanningX !== 0 ||
  87508. this._attachedCamera.inertialPanningY !== 0 ||
  87509. this._isPointerDown;
  87510. },
  87511. enumerable: true,
  87512. configurable: true
  87513. });
  87514. /**
  87515. * The easing function used by animations
  87516. */
  87517. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87518. /**
  87519. * The easing mode used by animations
  87520. */
  87521. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87522. // Statics
  87523. /**
  87524. * The camera can move all the way towards the mesh.
  87525. */
  87526. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87527. /**
  87528. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87529. */
  87530. FramingBehavior.FitFrustumSidesMode = 1;
  87531. return FramingBehavior;
  87532. }());
  87533. BABYLON.FramingBehavior = FramingBehavior;
  87534. })(BABYLON || (BABYLON = {}));
  87535. //# sourceMappingURL=babylon.framingBehavior.js.map
  87536. var BABYLON;
  87537. (function (BABYLON) {
  87538. /**
  87539. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87540. */
  87541. var BouncingBehavior = /** @class */ (function () {
  87542. function BouncingBehavior() {
  87543. /**
  87544. * The duration of the animation, in milliseconds
  87545. */
  87546. this.transitionDuration = 450;
  87547. /**
  87548. * Length of the distance animated by the transition when lower radius is reached
  87549. */
  87550. this.lowerRadiusTransitionRange = 2;
  87551. /**
  87552. * Length of the distance animated by the transition when upper radius is reached
  87553. */
  87554. this.upperRadiusTransitionRange = -2;
  87555. this._autoTransitionRange = false;
  87556. // Animations
  87557. this._radiusIsAnimating = false;
  87558. this._radiusBounceTransition = null;
  87559. this._animatables = new Array();
  87560. }
  87561. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87562. get: function () {
  87563. return "Bouncing";
  87564. },
  87565. enumerable: true,
  87566. configurable: true
  87567. });
  87568. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87569. /**
  87570. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87571. */
  87572. get: function () {
  87573. return this._autoTransitionRange;
  87574. },
  87575. /**
  87576. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87577. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87578. */
  87579. set: function (value) {
  87580. var _this = this;
  87581. if (this._autoTransitionRange === value) {
  87582. return;
  87583. }
  87584. this._autoTransitionRange = value;
  87585. var camera = this._attachedCamera;
  87586. if (!camera) {
  87587. return;
  87588. }
  87589. if (value) {
  87590. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87591. if (!mesh) {
  87592. return;
  87593. }
  87594. mesh.computeWorldMatrix(true);
  87595. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87596. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87597. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87598. });
  87599. }
  87600. else if (this._onMeshTargetChangedObserver) {
  87601. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87602. }
  87603. },
  87604. enumerable: true,
  87605. configurable: true
  87606. });
  87607. BouncingBehavior.prototype.init = function () {
  87608. // Do notihng
  87609. };
  87610. BouncingBehavior.prototype.attach = function (camera) {
  87611. var _this = this;
  87612. this._attachedCamera = camera;
  87613. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87614. if (!_this._attachedCamera) {
  87615. return;
  87616. }
  87617. // Add the bounce animation to the lower radius limit
  87618. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87619. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87620. }
  87621. // Add the bounce animation to the upper radius limit
  87622. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87623. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87624. }
  87625. });
  87626. };
  87627. BouncingBehavior.prototype.detach = function () {
  87628. if (!this._attachedCamera) {
  87629. return;
  87630. }
  87631. if (this._onAfterCheckInputsObserver) {
  87632. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87633. }
  87634. if (this._onMeshTargetChangedObserver) {
  87635. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87636. }
  87637. this._attachedCamera = null;
  87638. };
  87639. /**
  87640. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87641. * @param radiusLimit The limit to check against.
  87642. * @return Bool to indicate if at limit.
  87643. */
  87644. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87645. if (!this._attachedCamera) {
  87646. return false;
  87647. }
  87648. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87649. return true;
  87650. }
  87651. return false;
  87652. };
  87653. /**
  87654. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87655. * @param radiusDelta The delta by which to animate to. Can be negative.
  87656. */
  87657. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87658. var _this = this;
  87659. if (!this._attachedCamera) {
  87660. return;
  87661. }
  87662. if (!this._radiusBounceTransition) {
  87663. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87664. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87665. }
  87666. // Prevent zoom until bounce has completed
  87667. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87668. this._attachedCamera.wheelPrecision = Infinity;
  87669. this._attachedCamera.inertialRadiusOffset = 0;
  87670. // Animate to the radius limit
  87671. this.stopAllAnimations();
  87672. this._radiusIsAnimating = true;
  87673. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87674. if (animatable) {
  87675. this._animatables.push(animatable);
  87676. }
  87677. };
  87678. /**
  87679. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87680. */
  87681. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87682. this._radiusIsAnimating = false;
  87683. if (this._attachedCamera) {
  87684. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87685. }
  87686. };
  87687. /**
  87688. * Stops and removes all animations that have been applied to the camera
  87689. */
  87690. BouncingBehavior.prototype.stopAllAnimations = function () {
  87691. if (this._attachedCamera) {
  87692. this._attachedCamera.animations = [];
  87693. }
  87694. while (this._animatables.length) {
  87695. this._animatables[0].onAnimationEnd = null;
  87696. this._animatables[0].stop();
  87697. this._animatables.shift();
  87698. }
  87699. };
  87700. /**
  87701. * The easing function used by animations
  87702. */
  87703. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87704. /**
  87705. * The easing mode used by animations
  87706. */
  87707. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87708. return BouncingBehavior;
  87709. }());
  87710. BABYLON.BouncingBehavior = BouncingBehavior;
  87711. })(BABYLON || (BABYLON = {}));
  87712. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87713. var BABYLON;
  87714. (function (BABYLON) {
  87715. var AutoRotationBehavior = /** @class */ (function () {
  87716. function AutoRotationBehavior() {
  87717. this._zoomStopsAnimation = false;
  87718. this._idleRotationSpeed = 0.05;
  87719. this._idleRotationWaitTime = 2000;
  87720. this._idleRotationSpinupTime = 2000;
  87721. this._isPointerDown = false;
  87722. this._lastFrameTime = null;
  87723. this._lastInteractionTime = -Infinity;
  87724. this._cameraRotationSpeed = 0;
  87725. this._lastFrameRadius = 0;
  87726. }
  87727. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87728. get: function () {
  87729. return "AutoRotation";
  87730. },
  87731. enumerable: true,
  87732. configurable: true
  87733. });
  87734. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87735. /**
  87736. * Gets the flag that indicates if user zooming should stop animation.
  87737. */
  87738. get: function () {
  87739. return this._zoomStopsAnimation;
  87740. },
  87741. /**
  87742. * Sets the flag that indicates if user zooming should stop animation.
  87743. */
  87744. set: function (flag) {
  87745. this._zoomStopsAnimation = flag;
  87746. },
  87747. enumerable: true,
  87748. configurable: true
  87749. });
  87750. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87751. /**
  87752. * Gets the default speed at which the camera rotates around the model.
  87753. */
  87754. get: function () {
  87755. return this._idleRotationSpeed;
  87756. },
  87757. /**
  87758. * Sets the default speed at which the camera rotates around the model.
  87759. */
  87760. set: function (speed) {
  87761. this._idleRotationSpeed = speed;
  87762. },
  87763. enumerable: true,
  87764. configurable: true
  87765. });
  87766. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87767. /**
  87768. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87769. */
  87770. get: function () {
  87771. return this._idleRotationWaitTime;
  87772. },
  87773. /**
  87774. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87775. */
  87776. set: function (time) {
  87777. this._idleRotationWaitTime = time;
  87778. },
  87779. enumerable: true,
  87780. configurable: true
  87781. });
  87782. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87783. /**
  87784. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87785. */
  87786. get: function () {
  87787. return this._idleRotationSpinupTime;
  87788. },
  87789. /**
  87790. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87791. */
  87792. set: function (time) {
  87793. this._idleRotationSpinupTime = time;
  87794. },
  87795. enumerable: true,
  87796. configurable: true
  87797. });
  87798. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87799. /**
  87800. * Gets a value indicating if the camera is currently rotating because of this behavior
  87801. */
  87802. get: function () {
  87803. return Math.abs(this._cameraRotationSpeed) > 0;
  87804. },
  87805. enumerable: true,
  87806. configurable: true
  87807. });
  87808. AutoRotationBehavior.prototype.init = function () {
  87809. // Do notihng
  87810. };
  87811. AutoRotationBehavior.prototype.attach = function (camera) {
  87812. var _this = this;
  87813. this._attachedCamera = camera;
  87814. var scene = this._attachedCamera.getScene();
  87815. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87816. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87817. _this._isPointerDown = true;
  87818. return;
  87819. }
  87820. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87821. _this._isPointerDown = false;
  87822. }
  87823. });
  87824. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87825. var now = BABYLON.Tools.Now;
  87826. var dt = 0;
  87827. if (_this._lastFrameTime != null) {
  87828. dt = now - _this._lastFrameTime;
  87829. }
  87830. _this._lastFrameTime = now;
  87831. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87832. _this._applyUserInteraction();
  87833. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87834. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87835. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87836. // Step camera rotation by rotation speed
  87837. if (_this._attachedCamera) {
  87838. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87839. }
  87840. });
  87841. };
  87842. AutoRotationBehavior.prototype.detach = function () {
  87843. if (!this._attachedCamera) {
  87844. return;
  87845. }
  87846. var scene = this._attachedCamera.getScene();
  87847. if (this._onPrePointerObservableObserver) {
  87848. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87849. }
  87850. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87851. this._attachedCamera = null;
  87852. };
  87853. /**
  87854. * Returns true if user is scrolling.
  87855. * @return true if user is scrolling.
  87856. */
  87857. AutoRotationBehavior.prototype._userIsZooming = function () {
  87858. if (!this._attachedCamera) {
  87859. return false;
  87860. }
  87861. return this._attachedCamera.inertialRadiusOffset !== 0;
  87862. };
  87863. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87864. if (!this._attachedCamera) {
  87865. return false;
  87866. }
  87867. var zoomHasHitLimit = false;
  87868. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87869. zoomHasHitLimit = true;
  87870. }
  87871. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87872. this._lastFrameRadius = this._attachedCamera.radius;
  87873. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87874. };
  87875. /**
  87876. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87877. */
  87878. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87879. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87880. this._lastInteractionTime = BABYLON.Tools.Now;
  87881. }
  87882. };
  87883. // Tools
  87884. AutoRotationBehavior.prototype._userIsMoving = function () {
  87885. if (!this._attachedCamera) {
  87886. return false;
  87887. }
  87888. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87889. this._attachedCamera.inertialBetaOffset !== 0 ||
  87890. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87891. this._attachedCamera.inertialPanningX !== 0 ||
  87892. this._attachedCamera.inertialPanningY !== 0 ||
  87893. this._isPointerDown;
  87894. };
  87895. return AutoRotationBehavior;
  87896. }());
  87897. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87898. })(BABYLON || (BABYLON = {}));
  87899. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87900. var BABYLON;
  87901. (function (BABYLON) {
  87902. /**
  87903. * This class can be used to get instrumentation data from a Babylon engine
  87904. */
  87905. var EngineInstrumentation = /** @class */ (function () {
  87906. function EngineInstrumentation(engine) {
  87907. this.engine = engine;
  87908. this._captureGPUFrameTime = false;
  87909. this._gpuFrameTime = new BABYLON.PerfCounter();
  87910. this._captureShaderCompilationTime = false;
  87911. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87912. // Observers
  87913. this._onBeginFrameObserver = null;
  87914. this._onEndFrameObserver = null;
  87915. this._onBeforeShaderCompilationObserver = null;
  87916. this._onAfterShaderCompilationObserver = null;
  87917. }
  87918. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87919. // Properties
  87920. /**
  87921. * Gets the perf counter used for GPU frame time
  87922. */
  87923. get: function () {
  87924. return this._gpuFrameTime;
  87925. },
  87926. enumerable: true,
  87927. configurable: true
  87928. });
  87929. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87930. /**
  87931. * Gets the GPU frame time capture status
  87932. */
  87933. get: function () {
  87934. return this._captureGPUFrameTime;
  87935. },
  87936. /**
  87937. * Enable or disable the GPU frame time capture
  87938. */
  87939. set: function (value) {
  87940. var _this = this;
  87941. if (value === this._captureGPUFrameTime) {
  87942. return;
  87943. }
  87944. this._captureGPUFrameTime = value;
  87945. if (value) {
  87946. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87947. if (!_this._gpuFrameTimeToken) {
  87948. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87949. }
  87950. });
  87951. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87952. if (!_this._gpuFrameTimeToken) {
  87953. return;
  87954. }
  87955. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87956. if (time > -1) {
  87957. _this._gpuFrameTimeToken = null;
  87958. _this._gpuFrameTime.fetchNewFrame();
  87959. _this._gpuFrameTime.addCount(time, true);
  87960. }
  87961. });
  87962. }
  87963. else {
  87964. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87965. this._onBeginFrameObserver = null;
  87966. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87967. this._onEndFrameObserver = null;
  87968. }
  87969. },
  87970. enumerable: true,
  87971. configurable: true
  87972. });
  87973. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87974. /**
  87975. * Gets the perf counter used for shader compilation time
  87976. */
  87977. get: function () {
  87978. return this._shaderCompilationTime;
  87979. },
  87980. enumerable: true,
  87981. configurable: true
  87982. });
  87983. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87984. /**
  87985. * Gets the shader compilation time capture status
  87986. */
  87987. get: function () {
  87988. return this._captureShaderCompilationTime;
  87989. },
  87990. /**
  87991. * Enable or disable the shader compilation time capture
  87992. */
  87993. set: function (value) {
  87994. var _this = this;
  87995. if (value === this._captureShaderCompilationTime) {
  87996. return;
  87997. }
  87998. this._captureShaderCompilationTime = value;
  87999. if (value) {
  88000. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88001. _this._shaderCompilationTime.fetchNewFrame();
  88002. _this._shaderCompilationTime.beginMonitoring();
  88003. });
  88004. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88005. _this._shaderCompilationTime.endMonitoring();
  88006. });
  88007. }
  88008. else {
  88009. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88010. this._onBeforeShaderCompilationObserver = null;
  88011. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88012. this._onAfterShaderCompilationObserver = null;
  88013. }
  88014. },
  88015. enumerable: true,
  88016. configurable: true
  88017. });
  88018. EngineInstrumentation.prototype.dispose = function () {
  88019. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88020. this._onBeginFrameObserver = null;
  88021. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88022. this._onEndFrameObserver = null;
  88023. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88024. this._onBeforeShaderCompilationObserver = null;
  88025. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88026. this._onAfterShaderCompilationObserver = null;
  88027. this.engine = null;
  88028. };
  88029. return EngineInstrumentation;
  88030. }());
  88031. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88032. })(BABYLON || (BABYLON = {}));
  88033. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88034. var BABYLON;
  88035. (function (BABYLON) {
  88036. /**
  88037. * This class can be used to get instrumentation data from a Babylon engine
  88038. */
  88039. var SceneInstrumentation = /** @class */ (function () {
  88040. function SceneInstrumentation(scene) {
  88041. var _this = this;
  88042. this.scene = scene;
  88043. this._captureActiveMeshesEvaluationTime = false;
  88044. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88045. this._captureRenderTargetsRenderTime = false;
  88046. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88047. this._captureFrameTime = false;
  88048. this._frameTime = new BABYLON.PerfCounter();
  88049. this._captureRenderTime = false;
  88050. this._renderTime = new BABYLON.PerfCounter();
  88051. this._captureInterFrameTime = false;
  88052. this._interFrameTime = new BABYLON.PerfCounter();
  88053. this._captureParticlesRenderTime = false;
  88054. this._particlesRenderTime = new BABYLON.PerfCounter();
  88055. this._captureSpritesRenderTime = false;
  88056. this._spritesRenderTime = new BABYLON.PerfCounter();
  88057. this._capturePhysicsTime = false;
  88058. this._physicsTime = new BABYLON.PerfCounter();
  88059. this._captureAnimationsTime = false;
  88060. this._animationsTime = new BABYLON.PerfCounter();
  88061. // Observers
  88062. this._onBeforeActiveMeshesEvaluationObserver = null;
  88063. this._onAfterActiveMeshesEvaluationObserver = null;
  88064. this._onBeforeRenderTargetsRenderObserver = null;
  88065. this._onAfterRenderTargetsRenderObserver = null;
  88066. this._onAfterRenderObserver = null;
  88067. this._onBeforeDrawPhaseObserver = null;
  88068. this._onAfterDrawPhaseObserver = null;
  88069. this._onBeforeAnimationsObserver = null;
  88070. this._onBeforeParticlesRenderingObserver = null;
  88071. this._onAfterParticlesRenderingObserver = null;
  88072. this._onBeforeSpritesRenderingObserver = null;
  88073. this._onAfterSpritesRenderingObserver = null;
  88074. this._onBeforePhysicsObserver = null;
  88075. this._onAfterPhysicsObserver = null;
  88076. this._onAfterAnimationsObserver = null;
  88077. // Before render
  88078. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88079. if (_this._captureActiveMeshesEvaluationTime) {
  88080. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88081. }
  88082. if (_this._captureRenderTargetsRenderTime) {
  88083. _this._renderTargetsRenderTime.fetchNewFrame();
  88084. }
  88085. if (_this._captureFrameTime) {
  88086. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88087. _this._frameTime.beginMonitoring();
  88088. }
  88089. if (_this._captureInterFrameTime) {
  88090. _this._interFrameTime.endMonitoring();
  88091. }
  88092. if (_this._captureParticlesRenderTime) {
  88093. _this._particlesRenderTime.fetchNewFrame();
  88094. }
  88095. if (_this._captureSpritesRenderTime) {
  88096. _this._spritesRenderTime.fetchNewFrame();
  88097. }
  88098. if (_this._captureAnimationsTime) {
  88099. _this._animationsTime.beginMonitoring();
  88100. }
  88101. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88102. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88103. });
  88104. // After render
  88105. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88106. if (_this._captureFrameTime) {
  88107. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88108. _this._frameTime.endMonitoring();
  88109. }
  88110. if (_this._captureRenderTime) {
  88111. _this._renderTime.endMonitoring(false);
  88112. }
  88113. if (_this._captureInterFrameTime) {
  88114. _this._interFrameTime.beginMonitoring();
  88115. }
  88116. });
  88117. }
  88118. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88119. // Properties
  88120. /**
  88121. * Gets the perf counter used for active meshes evaluation time
  88122. */
  88123. get: function () {
  88124. return this._activeMeshesEvaluationTime;
  88125. },
  88126. enumerable: true,
  88127. configurable: true
  88128. });
  88129. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88130. /**
  88131. * Gets the active meshes evaluation time capture status
  88132. */
  88133. get: function () {
  88134. return this._captureActiveMeshesEvaluationTime;
  88135. },
  88136. /**
  88137. * Enable or disable the active meshes evaluation time capture
  88138. */
  88139. set: function (value) {
  88140. var _this = this;
  88141. if (value === this._captureActiveMeshesEvaluationTime) {
  88142. return;
  88143. }
  88144. this._captureActiveMeshesEvaluationTime = value;
  88145. if (value) {
  88146. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88147. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88148. _this._activeMeshesEvaluationTime.beginMonitoring();
  88149. });
  88150. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88151. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88152. _this._activeMeshesEvaluationTime.endMonitoring();
  88153. });
  88154. }
  88155. else {
  88156. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88157. this._onBeforeActiveMeshesEvaluationObserver = null;
  88158. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88159. this._onAfterActiveMeshesEvaluationObserver = null;
  88160. }
  88161. },
  88162. enumerable: true,
  88163. configurable: true
  88164. });
  88165. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88166. /**
  88167. * Gets the perf counter used for render targets render time
  88168. */
  88169. get: function () {
  88170. return this._renderTargetsRenderTime;
  88171. },
  88172. enumerable: true,
  88173. configurable: true
  88174. });
  88175. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88176. /**
  88177. * Gets the render targets render time capture status
  88178. */
  88179. get: function () {
  88180. return this._captureRenderTargetsRenderTime;
  88181. },
  88182. /**
  88183. * Enable or disable the render targets render time capture
  88184. */
  88185. set: function (value) {
  88186. var _this = this;
  88187. if (value === this._captureRenderTargetsRenderTime) {
  88188. return;
  88189. }
  88190. this._captureRenderTargetsRenderTime = value;
  88191. if (value) {
  88192. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88193. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88194. _this._renderTargetsRenderTime.beginMonitoring();
  88195. });
  88196. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88197. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88198. _this._renderTargetsRenderTime.endMonitoring(false);
  88199. });
  88200. }
  88201. else {
  88202. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88203. this._onBeforeRenderTargetsRenderObserver = null;
  88204. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88205. this._onAfterRenderTargetsRenderObserver = null;
  88206. }
  88207. },
  88208. enumerable: true,
  88209. configurable: true
  88210. });
  88211. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88212. /**
  88213. * Gets the perf counter used for particles render time
  88214. */
  88215. get: function () {
  88216. return this._particlesRenderTime;
  88217. },
  88218. enumerable: true,
  88219. configurable: true
  88220. });
  88221. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88222. /**
  88223. * Gets the particles render time capture status
  88224. */
  88225. get: function () {
  88226. return this._captureParticlesRenderTime;
  88227. },
  88228. /**
  88229. * Enable or disable the particles render time capture
  88230. */
  88231. set: function (value) {
  88232. var _this = this;
  88233. if (value === this._captureParticlesRenderTime) {
  88234. return;
  88235. }
  88236. this._captureParticlesRenderTime = value;
  88237. if (value) {
  88238. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88239. BABYLON.Tools.StartPerformanceCounter("Particles");
  88240. _this._particlesRenderTime.beginMonitoring();
  88241. });
  88242. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88243. BABYLON.Tools.EndPerformanceCounter("Particles");
  88244. _this._particlesRenderTime.endMonitoring(false);
  88245. });
  88246. }
  88247. else {
  88248. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88249. this._onBeforeParticlesRenderingObserver = null;
  88250. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88251. this._onAfterParticlesRenderingObserver = null;
  88252. }
  88253. },
  88254. enumerable: true,
  88255. configurable: true
  88256. });
  88257. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88258. /**
  88259. * Gets the perf counter used for sprites render time
  88260. */
  88261. get: function () {
  88262. return this._spritesRenderTime;
  88263. },
  88264. enumerable: true,
  88265. configurable: true
  88266. });
  88267. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88268. /**
  88269. * Gets the sprites render time capture status
  88270. */
  88271. get: function () {
  88272. return this._captureSpritesRenderTime;
  88273. },
  88274. /**
  88275. * Enable or disable the sprites render time capture
  88276. */
  88277. set: function (value) {
  88278. var _this = this;
  88279. if (value === this._captureSpritesRenderTime) {
  88280. return;
  88281. }
  88282. this._captureSpritesRenderTime = value;
  88283. if (value) {
  88284. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88285. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88286. _this._spritesRenderTime.beginMonitoring();
  88287. });
  88288. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88289. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88290. _this._spritesRenderTime.endMonitoring(false);
  88291. });
  88292. }
  88293. else {
  88294. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88295. this._onBeforeSpritesRenderingObserver = null;
  88296. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88297. this._onAfterSpritesRenderingObserver = null;
  88298. }
  88299. },
  88300. enumerable: true,
  88301. configurable: true
  88302. });
  88303. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88304. /**
  88305. * Gets the perf counter used for physics time
  88306. */
  88307. get: function () {
  88308. return this._physicsTime;
  88309. },
  88310. enumerable: true,
  88311. configurable: true
  88312. });
  88313. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88314. /**
  88315. * Gets the physics time capture status
  88316. */
  88317. get: function () {
  88318. return this._capturePhysicsTime;
  88319. },
  88320. /**
  88321. * Enable or disable the physics time capture
  88322. */
  88323. set: function (value) {
  88324. var _this = this;
  88325. if (value === this._capturePhysicsTime) {
  88326. return;
  88327. }
  88328. this._capturePhysicsTime = value;
  88329. if (value) {
  88330. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88331. BABYLON.Tools.StartPerformanceCounter("Physics");
  88332. _this._physicsTime.beginMonitoring();
  88333. });
  88334. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88335. BABYLON.Tools.EndPerformanceCounter("Physics");
  88336. _this._physicsTime.endMonitoring();
  88337. });
  88338. }
  88339. else {
  88340. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88341. this._onBeforePhysicsObserver = null;
  88342. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88343. this._onAfterPhysicsObserver = null;
  88344. }
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88350. /**
  88351. * Gets the perf counter used for animations time
  88352. */
  88353. get: function () {
  88354. return this._animationsTime;
  88355. },
  88356. enumerable: true,
  88357. configurable: true
  88358. });
  88359. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88360. /**
  88361. * Gets the animations time capture status
  88362. */
  88363. get: function () {
  88364. return this._captureAnimationsTime;
  88365. },
  88366. /**
  88367. * Enable or disable the animations time capture
  88368. */
  88369. set: function (value) {
  88370. var _this = this;
  88371. if (value === this._captureAnimationsTime) {
  88372. return;
  88373. }
  88374. this._captureAnimationsTime = value;
  88375. if (value) {
  88376. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88377. _this._animationsTime.endMonitoring();
  88378. });
  88379. }
  88380. else {
  88381. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88382. this._onAfterAnimationsObserver = null;
  88383. }
  88384. },
  88385. enumerable: true,
  88386. configurable: true
  88387. });
  88388. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88389. /**
  88390. * Gets the perf counter used for frame time capture
  88391. */
  88392. get: function () {
  88393. return this._frameTime;
  88394. },
  88395. enumerable: true,
  88396. configurable: true
  88397. });
  88398. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88399. /**
  88400. * Gets the frame time capture status
  88401. */
  88402. get: function () {
  88403. return this._captureFrameTime;
  88404. },
  88405. /**
  88406. * Enable or disable the frame time capture
  88407. */
  88408. set: function (value) {
  88409. this._captureFrameTime = value;
  88410. },
  88411. enumerable: true,
  88412. configurable: true
  88413. });
  88414. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88415. /**
  88416. * Gets the perf counter used for inter-frames time capture
  88417. */
  88418. get: function () {
  88419. return this._interFrameTime;
  88420. },
  88421. enumerable: true,
  88422. configurable: true
  88423. });
  88424. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88425. /**
  88426. * Gets the inter-frames time capture status
  88427. */
  88428. get: function () {
  88429. return this._captureInterFrameTime;
  88430. },
  88431. /**
  88432. * Enable or disable the inter-frames time capture
  88433. */
  88434. set: function (value) {
  88435. this._captureInterFrameTime = value;
  88436. },
  88437. enumerable: true,
  88438. configurable: true
  88439. });
  88440. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88441. /**
  88442. * Gets the perf counter used for render time capture
  88443. */
  88444. get: function () {
  88445. return this._renderTime;
  88446. },
  88447. enumerable: true,
  88448. configurable: true
  88449. });
  88450. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88451. /**
  88452. * Gets the render time capture status
  88453. */
  88454. get: function () {
  88455. return this._captureRenderTime;
  88456. },
  88457. /**
  88458. * Enable or disable the render time capture
  88459. */
  88460. set: function (value) {
  88461. var _this = this;
  88462. if (value === this._captureRenderTime) {
  88463. return;
  88464. }
  88465. this._captureRenderTime = value;
  88466. if (value) {
  88467. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88468. _this._renderTime.beginMonitoring();
  88469. BABYLON.Tools.StartPerformanceCounter("Main render");
  88470. });
  88471. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88472. _this._renderTime.endMonitoring(false);
  88473. BABYLON.Tools.EndPerformanceCounter("Main render");
  88474. });
  88475. }
  88476. else {
  88477. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88478. this._onBeforeDrawPhaseObserver = null;
  88479. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88480. this._onAfterDrawPhaseObserver = null;
  88481. }
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88487. /**
  88488. * Gets the perf counter used for draw calls
  88489. */
  88490. get: function () {
  88491. return this.scene.getEngine()._drawCalls;
  88492. },
  88493. enumerable: true,
  88494. configurable: true
  88495. });
  88496. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88497. /**
  88498. * Gets the perf counter used for texture collisions
  88499. */
  88500. get: function () {
  88501. return this.scene.getEngine()._textureCollisions;
  88502. },
  88503. enumerable: true,
  88504. configurable: true
  88505. });
  88506. SceneInstrumentation.prototype.dispose = function () {
  88507. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88508. this._onAfterRenderObserver = null;
  88509. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88510. this._onBeforeActiveMeshesEvaluationObserver = null;
  88511. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88512. this._onAfterActiveMeshesEvaluationObserver = null;
  88513. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88514. this._onBeforeRenderTargetsRenderObserver = null;
  88515. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88516. this._onAfterRenderTargetsRenderObserver = null;
  88517. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88518. this._onBeforeAnimationsObserver = null;
  88519. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88520. this._onBeforeParticlesRenderingObserver = null;
  88521. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88522. this._onAfterParticlesRenderingObserver = null;
  88523. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88524. this._onBeforeSpritesRenderingObserver = null;
  88525. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88526. this._onAfterSpritesRenderingObserver = null;
  88527. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88528. this._onBeforeDrawPhaseObserver = null;
  88529. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88530. this._onAfterDrawPhaseObserver = null;
  88531. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88532. this._onBeforePhysicsObserver = null;
  88533. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88534. this._onAfterPhysicsObserver = null;
  88535. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88536. this._onAfterAnimationsObserver = null;
  88537. this.scene = null;
  88538. };
  88539. return SceneInstrumentation;
  88540. }());
  88541. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88542. })(BABYLON || (BABYLON = {}));
  88543. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88544. var BABYLON;
  88545. (function (BABYLON) {
  88546. var _TimeToken = /** @class */ (function () {
  88547. function _TimeToken() {
  88548. this._timeElapsedQueryEnded = false;
  88549. }
  88550. return _TimeToken;
  88551. }());
  88552. BABYLON._TimeToken = _TimeToken;
  88553. })(BABYLON || (BABYLON = {}));
  88554. //# sourceMappingURL=babylon.timeToken.js.map
  88555. var BABYLON;
  88556. (function (BABYLON) {
  88557. /**
  88558. * Background material defines definition.
  88559. * @ignore Mainly internal Use
  88560. */
  88561. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88562. __extends(BackgroundMaterialDefines, _super);
  88563. /**
  88564. * Constructor of the defines.
  88565. */
  88566. function BackgroundMaterialDefines() {
  88567. var _this = _super.call(this) || this;
  88568. /**
  88569. * True if the diffuse texture is in use.
  88570. */
  88571. _this.DIFFUSE = false;
  88572. /**
  88573. * The direct UV channel to use.
  88574. */
  88575. _this.DIFFUSEDIRECTUV = 0;
  88576. /**
  88577. * True if the diffuse texture is in gamma space.
  88578. */
  88579. _this.GAMMADIFFUSE = false;
  88580. /**
  88581. * True if the diffuse texture has opacity in the alpha channel.
  88582. */
  88583. _this.DIFFUSEHASALPHA = false;
  88584. /**
  88585. * True if you want the material to fade to transparent at grazing angle.
  88586. */
  88587. _this.OPACITYFRESNEL = false;
  88588. /**
  88589. * True if an extra blur needs to be added in the reflection.
  88590. */
  88591. _this.REFLECTIONBLUR = false;
  88592. /**
  88593. * True if you want the material to fade to reflection at grazing angle.
  88594. */
  88595. _this.REFLECTIONFRESNEL = false;
  88596. /**
  88597. * True if you want the material to falloff as far as you move away from the scene center.
  88598. */
  88599. _this.REFLECTIONFALLOFF = false;
  88600. /**
  88601. * False if the current Webgl implementation does not support the texture lod extension.
  88602. */
  88603. _this.TEXTURELODSUPPORT = false;
  88604. /**
  88605. * True to ensure the data are premultiplied.
  88606. */
  88607. _this.PREMULTIPLYALPHA = false;
  88608. /**
  88609. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88610. */
  88611. _this.USERGBCOLOR = false;
  88612. /**
  88613. * True to add noise in order to reduce the banding effect.
  88614. */
  88615. _this.NOISE = false;
  88616. /**
  88617. * is the reflection texture in BGR color scheme?
  88618. * Mainly used to solve a bug in ios10 video tag
  88619. */
  88620. _this.REFLECTIONBGR = false;
  88621. _this.IMAGEPROCESSING = false;
  88622. _this.VIGNETTE = false;
  88623. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88624. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88625. _this.TONEMAPPING = false;
  88626. _this.CONTRAST = false;
  88627. _this.COLORCURVES = false;
  88628. _this.COLORGRADING = false;
  88629. _this.COLORGRADING3D = false;
  88630. _this.SAMPLER3DGREENDEPTH = false;
  88631. _this.SAMPLER3DBGRMAP = false;
  88632. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88633. _this.EXPOSURE = false;
  88634. _this.GRAIN = false;
  88635. // Reflection.
  88636. _this.REFLECTION = false;
  88637. _this.REFLECTIONMAP_3D = false;
  88638. _this.REFLECTIONMAP_SPHERICAL = false;
  88639. _this.REFLECTIONMAP_PLANAR = false;
  88640. _this.REFLECTIONMAP_CUBIC = false;
  88641. _this.REFLECTIONMAP_PROJECTION = false;
  88642. _this.REFLECTIONMAP_SKYBOX = false;
  88643. _this.REFLECTIONMAP_EXPLICIT = false;
  88644. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88645. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88646. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88647. _this.INVERTCUBICMAP = false;
  88648. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88649. _this.LODINREFLECTIONALPHA = false;
  88650. _this.GAMMAREFLECTION = false;
  88651. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88652. // Default BJS.
  88653. _this.MAINUV1 = false;
  88654. _this.MAINUV2 = false;
  88655. _this.UV1 = false;
  88656. _this.UV2 = false;
  88657. _this.CLIPPLANE = false;
  88658. _this.POINTSIZE = false;
  88659. _this.FOG = false;
  88660. _this.NORMAL = false;
  88661. _this.NUM_BONE_INFLUENCERS = 0;
  88662. _this.BonesPerMesh = 0;
  88663. _this.INSTANCES = false;
  88664. _this.SHADOWFLOAT = false;
  88665. _this.rebuild();
  88666. return _this;
  88667. }
  88668. return BackgroundMaterialDefines;
  88669. }(BABYLON.MaterialDefines));
  88670. /**
  88671. * Background material used to create an efficient environement around your scene.
  88672. */
  88673. var BackgroundMaterial = /** @class */ (function (_super) {
  88674. __extends(BackgroundMaterial, _super);
  88675. /**
  88676. * Instantiates a Background Material in the given scene
  88677. * @param name The friendly name of the material
  88678. * @param scene The scene to add the material to
  88679. */
  88680. function BackgroundMaterial(name, scene) {
  88681. var _this = _super.call(this, name, scene) || this;
  88682. /**
  88683. * Key light Color (multiply against the R channel of the environement texture)
  88684. */
  88685. _this.primaryColor = BABYLON.Color3.White();
  88686. /**
  88687. * Key light Level (allowing HDR output of the background)
  88688. */
  88689. _this.primaryLevel = 1;
  88690. /**
  88691. * Secondary light Color (multiply against the G channel of the environement texture)
  88692. */
  88693. _this.secondaryColor = BABYLON.Color3.Gray();
  88694. /**
  88695. * Secondary light Level (allowing HDR output of the background)
  88696. */
  88697. _this.secondaryLevel = 1;
  88698. /**
  88699. * Tertiary light Color (multiply against the B channel of the environement texture)
  88700. */
  88701. _this.tertiaryColor = BABYLON.Color3.Black();
  88702. /**
  88703. * Tertiary light Level (allowing HDR output of the background)
  88704. */
  88705. _this.tertiaryLevel = 1;
  88706. /**
  88707. * Reflection Texture used in the material.
  88708. * Should be author in a specific way for the best result (refer to the documentation).
  88709. */
  88710. _this.reflectionTexture = null;
  88711. /**
  88712. * Reflection Texture level of blur.
  88713. *
  88714. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88715. * texture twice.
  88716. */
  88717. _this.reflectionBlur = 0;
  88718. /**
  88719. * Diffuse Texture used in the material.
  88720. * Should be author in a specific way for the best result (refer to the documentation).
  88721. */
  88722. _this.diffuseTexture = null;
  88723. _this._shadowLights = null;
  88724. /**
  88725. * Specify the list of lights casting shadow on the material.
  88726. * All scene shadow lights will be included if null.
  88727. */
  88728. _this.shadowLights = null;
  88729. /**
  88730. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88731. * soft lighting on the background.
  88732. */
  88733. _this.shadowBlurScale = 1;
  88734. /**
  88735. * Helps adjusting the shadow to a softer level if required.
  88736. * 0 means black shadows and 1 means no shadows.
  88737. */
  88738. _this.shadowLevel = 0;
  88739. /**
  88740. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88741. * It is usually zero but might be interesting to modify according to your setup.
  88742. */
  88743. _this.sceneCenter = BABYLON.Vector3.Zero();
  88744. /**
  88745. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88746. * This helps ensuring a nice transition when the camera goes under the ground.
  88747. */
  88748. _this.opacityFresnel = true;
  88749. /**
  88750. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88751. * This helps adding a mirror texture on the ground.
  88752. */
  88753. _this.reflectionFresnel = false;
  88754. /**
  88755. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88756. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88757. */
  88758. _this.reflectionFalloffDistance = 0.0;
  88759. /**
  88760. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88761. */
  88762. _this.reflectionAmount = 1.0;
  88763. /**
  88764. * This specifies the weight of the reflection at grazing angle.
  88765. */
  88766. _this.reflectionReflectance0 = 0.05;
  88767. /**
  88768. * This specifies the weight of the reflection at a perpendicular point of view.
  88769. */
  88770. _this.reflectionReflectance90 = 0.5;
  88771. /**
  88772. * Helps to directly use the maps channels instead of their level.
  88773. */
  88774. _this.useRGBColor = true;
  88775. /**
  88776. * This helps reducing the banding effect that could occur on the background.
  88777. */
  88778. _this.enableNoise = false;
  88779. _this._fovMultiplier = 1.0;
  88780. /**
  88781. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88782. * @type {boolean}
  88783. */
  88784. _this.useEquirectangularFOV = false;
  88785. _this._maxSimultaneousLights = 4;
  88786. /**
  88787. * Number of Simultaneous lights allowed on the material.
  88788. */
  88789. _this.maxSimultaneousLights = 4;
  88790. /**
  88791. * Keep track of the image processing observer to allow dispose and replace.
  88792. */
  88793. _this._imageProcessingObserver = null;
  88794. /**
  88795. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88796. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88797. */
  88798. _this.switchToBGR = false;
  88799. // Temp values kept as cache in the material.
  88800. _this._renderTargets = new BABYLON.SmartArray(16);
  88801. _this._reflectionControls = BABYLON.Vector4.Zero();
  88802. // Setup the default processing configuration to the scene.
  88803. _this._attachImageProcessingConfiguration(null);
  88804. _this.getRenderTargetTextures = function () {
  88805. _this._renderTargets.reset();
  88806. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88807. _this._renderTargets.push(_this._diffuseTexture);
  88808. }
  88809. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88810. _this._renderTargets.push(_this._reflectionTexture);
  88811. }
  88812. return _this._renderTargets;
  88813. };
  88814. return _this;
  88815. }
  88816. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88817. /**
  88818. * Sets the reflection reflectance fresnel values according to the default standard
  88819. * empirically know to work well :-)
  88820. */
  88821. set: function (value) {
  88822. var reflectionWeight = value;
  88823. if (reflectionWeight < 0.5) {
  88824. reflectionWeight = reflectionWeight * 2.0;
  88825. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88826. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88827. }
  88828. else {
  88829. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88830. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88831. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88832. }
  88833. },
  88834. enumerable: true,
  88835. configurable: true
  88836. });
  88837. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88838. /**
  88839. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88840. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88841. * Recommended to be keep at 1.0 except for special cases.
  88842. */
  88843. get: function () {
  88844. return this._fovMultiplier;
  88845. },
  88846. set: function (value) {
  88847. if (isNaN(value)) {
  88848. value = 1.0;
  88849. }
  88850. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88851. },
  88852. enumerable: true,
  88853. configurable: true
  88854. });
  88855. /**
  88856. * Attaches a new image processing configuration to the PBR Material.
  88857. * @param configuration (if null the scene configuration will be use)
  88858. */
  88859. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88860. var _this = this;
  88861. if (configuration === this._imageProcessingConfiguration) {
  88862. return;
  88863. }
  88864. // Detaches observer.
  88865. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88866. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88867. }
  88868. // Pick the scene configuration if needed.
  88869. if (!configuration) {
  88870. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88871. }
  88872. else {
  88873. this._imageProcessingConfiguration = configuration;
  88874. }
  88875. // Attaches observer.
  88876. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88877. _this._markAllSubMeshesAsImageProcessingDirty();
  88878. });
  88879. };
  88880. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88881. /**
  88882. * Gets the image processing configuration used either in this material.
  88883. */
  88884. get: function () {
  88885. return this._imageProcessingConfiguration;
  88886. },
  88887. /**
  88888. * Sets the Default image processing configuration used either in the this material.
  88889. *
  88890. * If sets to null, the scene one is in use.
  88891. */
  88892. set: function (value) {
  88893. this._attachImageProcessingConfiguration(value);
  88894. // Ensure the effect will be rebuilt.
  88895. this._markAllSubMeshesAsTexturesDirty();
  88896. },
  88897. enumerable: true,
  88898. configurable: true
  88899. });
  88900. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88901. /**
  88902. * Gets wether the color curves effect is enabled.
  88903. */
  88904. get: function () {
  88905. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88906. },
  88907. /**
  88908. * Sets wether the color curves effect is enabled.
  88909. */
  88910. set: function (value) {
  88911. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88912. },
  88913. enumerable: true,
  88914. configurable: true
  88915. });
  88916. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88917. /**
  88918. * Gets wether the color grading effect is enabled.
  88919. */
  88920. get: function () {
  88921. return this.imageProcessingConfiguration.colorGradingEnabled;
  88922. },
  88923. /**
  88924. * Gets wether the color grading effect is enabled.
  88925. */
  88926. set: function (value) {
  88927. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88928. },
  88929. enumerable: true,
  88930. configurable: true
  88931. });
  88932. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88933. /**
  88934. * Gets wether tonemapping is enabled or not.
  88935. */
  88936. get: function () {
  88937. return this._imageProcessingConfiguration.toneMappingEnabled;
  88938. },
  88939. /**
  88940. * Sets wether tonemapping is enabled or not
  88941. */
  88942. set: function (value) {
  88943. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88944. },
  88945. enumerable: true,
  88946. configurable: true
  88947. });
  88948. ;
  88949. ;
  88950. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88951. /**
  88952. * The camera exposure used on this material.
  88953. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88954. * This corresponds to a photographic exposure.
  88955. */
  88956. get: function () {
  88957. return this._imageProcessingConfiguration.exposure;
  88958. },
  88959. /**
  88960. * The camera exposure used on this material.
  88961. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88962. * This corresponds to a photographic exposure.
  88963. */
  88964. set: function (value) {
  88965. this._imageProcessingConfiguration.exposure = value;
  88966. },
  88967. enumerable: true,
  88968. configurable: true
  88969. });
  88970. ;
  88971. ;
  88972. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88973. /**
  88974. * Gets The camera contrast used on this material.
  88975. */
  88976. get: function () {
  88977. return this._imageProcessingConfiguration.contrast;
  88978. },
  88979. /**
  88980. * Sets The camera contrast used on this material.
  88981. */
  88982. set: function (value) {
  88983. this._imageProcessingConfiguration.contrast = value;
  88984. },
  88985. enumerable: true,
  88986. configurable: true
  88987. });
  88988. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88989. /**
  88990. * Gets the Color Grading 2D Lookup Texture.
  88991. */
  88992. get: function () {
  88993. return this._imageProcessingConfiguration.colorGradingTexture;
  88994. },
  88995. /**
  88996. * Sets the Color Grading 2D Lookup Texture.
  88997. */
  88998. set: function (value) {
  88999. this.imageProcessingConfiguration.colorGradingTexture = value;
  89000. },
  89001. enumerable: true,
  89002. configurable: true
  89003. });
  89004. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89005. /**
  89006. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89007. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89008. * 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;
  89009. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89010. */
  89011. get: function () {
  89012. return this.imageProcessingConfiguration.colorCurves;
  89013. },
  89014. /**
  89015. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89016. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89017. * 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;
  89018. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89019. */
  89020. set: function (value) {
  89021. this.imageProcessingConfiguration.colorCurves = value;
  89022. },
  89023. enumerable: true,
  89024. configurable: true
  89025. });
  89026. /**
  89027. * The entire material has been created in order to prevent overdraw.
  89028. * @returns false
  89029. */
  89030. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89031. return true;
  89032. };
  89033. /**
  89034. * The entire material has been created in order to prevent overdraw.
  89035. * @returns true if blending is enable
  89036. */
  89037. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89038. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89039. };
  89040. /**
  89041. * Checks wether the material is ready to be rendered for a given mesh.
  89042. * @param mesh The mesh to render
  89043. * @param subMesh The submesh to check against
  89044. * @param useInstances Specify wether or not the material is used with instances
  89045. * @returns true if all the dependencies are ready (Textures, Effects...)
  89046. */
  89047. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89048. var _this = this;
  89049. if (useInstances === void 0) { useInstances = false; }
  89050. if (subMesh.effect && this.isFrozen) {
  89051. if (this._wasPreviouslyReady) {
  89052. return true;
  89053. }
  89054. }
  89055. if (!subMesh._materialDefines) {
  89056. subMesh._materialDefines = new BackgroundMaterialDefines();
  89057. }
  89058. var scene = this.getScene();
  89059. var defines = subMesh._materialDefines;
  89060. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89061. if (defines._renderId === scene.getRenderId()) {
  89062. return true;
  89063. }
  89064. }
  89065. var engine = scene.getEngine();
  89066. // Lights
  89067. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89068. defines._needNormals = true;
  89069. // Textures
  89070. if (defines._areTexturesDirty) {
  89071. defines._needUVs = false;
  89072. if (scene.texturesEnabled) {
  89073. if (scene.getEngine().getCaps().textureLOD) {
  89074. defines.TEXTURELODSUPPORT = true;
  89075. }
  89076. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89077. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89078. return false;
  89079. }
  89080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89081. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89082. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89083. defines.OPACITYFRESNEL = this._opacityFresnel;
  89084. }
  89085. else {
  89086. defines.DIFFUSE = false;
  89087. defines.DIFFUSEHASALPHA = false;
  89088. defines.GAMMADIFFUSE = false;
  89089. defines.OPACITYFRESNEL = false;
  89090. }
  89091. var reflectionTexture = this._reflectionTexture;
  89092. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89093. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89094. return false;
  89095. }
  89096. defines.REFLECTION = true;
  89097. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89098. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89099. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89100. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89101. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89102. defines.REFLECTIONBGR = this.switchToBGR;
  89103. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89104. defines.INVERTCUBICMAP = true;
  89105. }
  89106. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89107. switch (reflectionTexture.coordinatesMode) {
  89108. case BABYLON.Texture.CUBIC_MODE:
  89109. case BABYLON.Texture.INVCUBIC_MODE:
  89110. defines.REFLECTIONMAP_CUBIC = true;
  89111. break;
  89112. case BABYLON.Texture.EXPLICIT_MODE:
  89113. defines.REFLECTIONMAP_EXPLICIT = true;
  89114. break;
  89115. case BABYLON.Texture.PLANAR_MODE:
  89116. defines.REFLECTIONMAP_PLANAR = true;
  89117. break;
  89118. case BABYLON.Texture.PROJECTION_MODE:
  89119. defines.REFLECTIONMAP_PROJECTION = true;
  89120. break;
  89121. case BABYLON.Texture.SKYBOX_MODE:
  89122. defines.REFLECTIONMAP_SKYBOX = true;
  89123. break;
  89124. case BABYLON.Texture.SPHERICAL_MODE:
  89125. defines.REFLECTIONMAP_SPHERICAL = true;
  89126. break;
  89127. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89128. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89129. break;
  89130. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89131. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89132. break;
  89133. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89134. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89135. break;
  89136. }
  89137. if (this.reflectionFresnel) {
  89138. defines.REFLECTIONFRESNEL = true;
  89139. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89140. this._reflectionControls.x = this.reflectionAmount;
  89141. this._reflectionControls.y = this.reflectionReflectance0;
  89142. this._reflectionControls.z = this.reflectionReflectance90;
  89143. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89144. }
  89145. else {
  89146. defines.REFLECTIONFRESNEL = false;
  89147. defines.REFLECTIONFALLOFF = false;
  89148. }
  89149. }
  89150. else {
  89151. defines.REFLECTION = false;
  89152. defines.REFLECTIONFALLOFF = false;
  89153. defines.REFLECTIONBLUR = false;
  89154. defines.REFLECTIONMAP_3D = false;
  89155. defines.REFLECTIONMAP_SPHERICAL = false;
  89156. defines.REFLECTIONMAP_PLANAR = false;
  89157. defines.REFLECTIONMAP_CUBIC = false;
  89158. defines.REFLECTIONMAP_PROJECTION = false;
  89159. defines.REFLECTIONMAP_SKYBOX = false;
  89160. defines.REFLECTIONMAP_EXPLICIT = false;
  89161. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89162. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89163. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89164. defines.INVERTCUBICMAP = false;
  89165. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89166. defines.LODINREFLECTIONALPHA = false;
  89167. defines.GAMMAREFLECTION = false;
  89168. }
  89169. }
  89170. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89171. defines.USERGBCOLOR = this._useRGBColor;
  89172. defines.NOISE = this._enableNoise;
  89173. }
  89174. if (defines._areImageProcessingDirty) {
  89175. if (!this._imageProcessingConfiguration.isReady()) {
  89176. return false;
  89177. }
  89178. this._imageProcessingConfiguration.prepareDefines(defines);
  89179. }
  89180. // Misc.
  89181. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89182. // Values that need to be evaluated on every frame
  89183. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89184. // Attribs
  89185. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89186. if (mesh) {
  89187. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89188. mesh.createNormals(true);
  89189. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89190. }
  89191. }
  89192. }
  89193. // Get correct effect
  89194. if (defines.isDirty) {
  89195. defines.markAsProcessed();
  89196. scene.resetCachedMaterial();
  89197. // Fallbacks
  89198. var fallbacks = new BABYLON.EffectFallbacks();
  89199. if (defines.FOG) {
  89200. fallbacks.addFallback(0, "FOG");
  89201. }
  89202. if (defines.POINTSIZE) {
  89203. fallbacks.addFallback(1, "POINTSIZE");
  89204. }
  89205. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89206. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89207. fallbacks.addCPUSkinningFallback(0, mesh);
  89208. }
  89209. //Attributes
  89210. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89211. if (defines.NORMAL) {
  89212. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89213. }
  89214. if (defines.UV1) {
  89215. attribs.push(BABYLON.VertexBuffer.UVKind);
  89216. }
  89217. if (defines.UV2) {
  89218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89219. }
  89220. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89221. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89222. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89223. "vFogInfos", "vFogColor", "pointSize",
  89224. "vClipPlane", "mBones",
  89225. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89226. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89227. "shadowLevel", "alpha",
  89228. "vBackgroundCenter", "vReflectionControl",
  89229. "vDiffuseInfos", "diffuseMatrix",
  89230. ];
  89231. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89232. var uniformBuffers = ["Material", "Scene"];
  89233. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89234. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89235. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89236. uniformsNames: uniforms,
  89237. uniformBuffersNames: uniformBuffers,
  89238. samplers: samplers,
  89239. defines: defines,
  89240. maxSimultaneousLights: this._maxSimultaneousLights
  89241. });
  89242. var onCompiled = function (effect) {
  89243. if (_this.onCompiled) {
  89244. _this.onCompiled(effect);
  89245. }
  89246. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89247. };
  89248. var join = defines.toString();
  89249. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89250. attributes: attribs,
  89251. uniformsNames: uniforms,
  89252. uniformBuffersNames: uniformBuffers,
  89253. samplers: samplers,
  89254. defines: join,
  89255. fallbacks: fallbacks,
  89256. onCompiled: onCompiled,
  89257. onError: this.onError,
  89258. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89259. }, engine), defines);
  89260. this.buildUniformLayout();
  89261. }
  89262. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89263. return false;
  89264. }
  89265. defines._renderId = scene.getRenderId();
  89266. this._wasPreviouslyReady = true;
  89267. return true;
  89268. };
  89269. /**
  89270. * Build the uniform buffer used in the material.
  89271. */
  89272. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89273. // Order is important !
  89274. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89275. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89276. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89277. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89278. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89279. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89280. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89281. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89282. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89283. this._uniformBuffer.addUniform("pointSize", 1);
  89284. this._uniformBuffer.addUniform("shadowLevel", 1);
  89285. this._uniformBuffer.addUniform("alpha", 1);
  89286. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89287. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89288. this._uniformBuffer.create();
  89289. };
  89290. /**
  89291. * Unbind the material.
  89292. */
  89293. BackgroundMaterial.prototype.unbind = function () {
  89294. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89295. this._uniformBuffer.setTexture("diffuseSampler", null);
  89296. }
  89297. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89298. this._uniformBuffer.setTexture("reflectionSampler", null);
  89299. }
  89300. _super.prototype.unbind.call(this);
  89301. };
  89302. /**
  89303. * Bind only the world matrix to the material.
  89304. * @param world The world matrix to bind.
  89305. */
  89306. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89307. this._activeEffect.setMatrix("world", world);
  89308. };
  89309. /**
  89310. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89311. * @param world The world matrix to bind.
  89312. * @param subMesh The submesh to bind for.
  89313. */
  89314. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89315. var scene = this.getScene();
  89316. var defines = subMesh._materialDefines;
  89317. if (!defines) {
  89318. return;
  89319. }
  89320. var effect = subMesh.effect;
  89321. if (!effect) {
  89322. return;
  89323. }
  89324. this._activeEffect = effect;
  89325. // Matrices
  89326. this.bindOnlyWorldMatrix(world);
  89327. // Bones
  89328. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89329. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89330. if (mustRebind) {
  89331. this._uniformBuffer.bindToEffect(effect, "Material");
  89332. this.bindViewProjection(effect);
  89333. var reflectionTexture = this._reflectionTexture;
  89334. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89335. // Texture uniforms
  89336. if (scene.texturesEnabled) {
  89337. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89338. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89339. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89340. }
  89341. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89342. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89343. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89344. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89345. }
  89346. }
  89347. if (this.shadowLevel > 0) {
  89348. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89349. }
  89350. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89351. // Point size
  89352. if (this.pointsCloud) {
  89353. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89354. }
  89355. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89356. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89357. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89358. }
  89359. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89360. // Textures
  89361. if (scene.texturesEnabled) {
  89362. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89363. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89364. }
  89365. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89366. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89367. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89368. }
  89369. else if (!defines.REFLECTIONBLUR) {
  89370. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89371. }
  89372. else {
  89373. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89374. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89375. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89376. }
  89377. if (defines.REFLECTIONFRESNEL) {
  89378. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89379. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89380. }
  89381. }
  89382. }
  89383. // Clip plane
  89384. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89385. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89386. }
  89387. if (mustRebind || !this.isFrozen) {
  89388. if (scene.lightsEnabled) {
  89389. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89390. }
  89391. // View
  89392. this.bindView(effect);
  89393. // Fog
  89394. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89395. // image processing
  89396. this._imageProcessingConfiguration.bind(this._activeEffect);
  89397. }
  89398. this._uniformBuffer.update();
  89399. this._afterBind(mesh);
  89400. };
  89401. /**
  89402. * Dispose the material.
  89403. * @param forceDisposeEffect Force disposal of the associated effect.
  89404. * @param forceDisposeTextures Force disposal of the associated textures.
  89405. */
  89406. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89407. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89408. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89409. if (forceDisposeTextures) {
  89410. if (this.diffuseTexture) {
  89411. this.diffuseTexture.dispose();
  89412. }
  89413. if (this.reflectionTexture) {
  89414. this.reflectionTexture.dispose();
  89415. }
  89416. }
  89417. this._renderTargets.dispose();
  89418. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89419. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89420. }
  89421. _super.prototype.dispose.call(this, forceDisposeEffect);
  89422. };
  89423. /**
  89424. * Clones the material.
  89425. * @param name The cloned name.
  89426. * @returns The cloned material.
  89427. */
  89428. BackgroundMaterial.prototype.clone = function (name) {
  89429. var _this = this;
  89430. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89431. };
  89432. /**
  89433. * Serializes the current material to its JSON representation.
  89434. * @returns The JSON representation.
  89435. */
  89436. BackgroundMaterial.prototype.serialize = function () {
  89437. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89438. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89439. return serializationObject;
  89440. };
  89441. /**
  89442. * Gets the class name of the material
  89443. * @returns "BackgroundMaterial"
  89444. */
  89445. BackgroundMaterial.prototype.getClassName = function () {
  89446. return "BackgroundMaterial";
  89447. };
  89448. /**
  89449. * Parse a JSON input to create back a background material.
  89450. * @param source The JSON data to parse
  89451. * @param scene The scene to create the parsed material in
  89452. * @param rootUrl The root url of the assets the material depends upon
  89453. * @returns the instantiated BackgroundMaterial.
  89454. */
  89455. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89456. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89457. };
  89458. /**
  89459. * Standard reflectance value at parallel view angle.
  89460. */
  89461. BackgroundMaterial.StandardReflectance0 = 0.05;
  89462. /**
  89463. * Standard reflectance value at grazing angle.
  89464. */
  89465. BackgroundMaterial.StandardReflectance90 = 0.5;
  89466. __decorate([
  89467. BABYLON.serializeAsColor3()
  89468. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89469. __decorate([
  89470. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89471. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89472. __decorate([
  89473. BABYLON.serialize()
  89474. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89475. __decorate([
  89476. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89477. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89478. __decorate([
  89479. BABYLON.serializeAsColor3()
  89480. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89481. __decorate([
  89482. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89483. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89484. __decorate([
  89485. BABYLON.serialize()
  89486. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89487. __decorate([
  89488. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89489. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89490. __decorate([
  89491. BABYLON.serializeAsColor3()
  89492. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89493. __decorate([
  89494. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89495. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89496. __decorate([
  89497. BABYLON.serialize()
  89498. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89499. __decorate([
  89500. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89501. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89502. __decorate([
  89503. BABYLON.serializeAsTexture()
  89504. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89505. __decorate([
  89506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89507. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89508. __decorate([
  89509. BABYLON.serialize()
  89510. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89511. __decorate([
  89512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89513. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89514. __decorate([
  89515. BABYLON.serializeAsTexture()
  89516. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89517. __decorate([
  89518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89519. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89520. __decorate([
  89521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89522. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89523. __decorate([
  89524. BABYLON.serialize()
  89525. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89526. __decorate([
  89527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89528. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89529. __decorate([
  89530. BABYLON.serialize()
  89531. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89532. __decorate([
  89533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89534. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89535. __decorate([
  89536. BABYLON.serializeAsVector3()
  89537. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89538. __decorate([
  89539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89540. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89541. __decorate([
  89542. BABYLON.serialize()
  89543. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89544. __decorate([
  89545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89546. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89547. __decorate([
  89548. BABYLON.serialize()
  89549. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89550. __decorate([
  89551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89552. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89553. __decorate([
  89554. BABYLON.serialize()
  89555. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89556. __decorate([
  89557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89558. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89559. __decorate([
  89560. BABYLON.serialize()
  89561. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89562. __decorate([
  89563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89564. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89565. __decorate([
  89566. BABYLON.serialize()
  89567. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89568. __decorate([
  89569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89570. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89571. __decorate([
  89572. BABYLON.serialize()
  89573. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89574. __decorate([
  89575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89576. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89577. __decorate([
  89578. BABYLON.serialize()
  89579. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89580. __decorate([
  89581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89582. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89583. __decorate([
  89584. BABYLON.serialize()
  89585. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89586. __decorate([
  89587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89588. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89589. __decorate([
  89590. BABYLON.serialize()
  89591. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89592. __decorate([
  89593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89594. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89595. __decorate([
  89596. BABYLON.serializeAsImageProcessingConfiguration()
  89597. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89598. return BackgroundMaterial;
  89599. }(BABYLON.PushMaterial));
  89600. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89601. })(BABYLON || (BABYLON = {}));
  89602. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89603. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89604. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89605. s = arguments[i];
  89606. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89607. t[p] = s[p];
  89608. }
  89609. return t;
  89610. };
  89611. var BABYLON;
  89612. (function (BABYLON) {
  89613. /**
  89614. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89615. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89616. * It also helps with the default setup of your imageProcessing configuration.
  89617. */
  89618. var EnvironmentHelper = /** @class */ (function () {
  89619. /**
  89620. * constructor
  89621. * @param options
  89622. * @param scene The scene to add the material to
  89623. */
  89624. function EnvironmentHelper(options, scene) {
  89625. var _this = this;
  89626. this._errorHandler = function (message, exception) {
  89627. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89628. };
  89629. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89630. this._scene = scene;
  89631. this.onErrorObservable = new BABYLON.Observable();
  89632. this._setupBackground();
  89633. this._setupImageProcessing();
  89634. }
  89635. /**
  89636. * Creates the default options for the helper.
  89637. */
  89638. EnvironmentHelper._getDefaultOptions = function () {
  89639. return {
  89640. createGround: true,
  89641. groundSize: 15,
  89642. groundTexture: this._groundTextureCDNUrl,
  89643. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89644. groundOpacity: 0.9,
  89645. enableGroundShadow: true,
  89646. groundShadowLevel: 0.5,
  89647. enableGroundMirror: false,
  89648. groundMirrorSizeRatio: 0.3,
  89649. groundMirrorBlurKernel: 64,
  89650. groundMirrorAmount: 1,
  89651. groundMirrorFresnelWeight: 1,
  89652. groundMirrorFallOffDistance: 0,
  89653. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89654. groundYBias: 0.00001,
  89655. createSkybox: true,
  89656. skyboxSize: 20,
  89657. skyboxTexture: this._skyboxTextureCDNUrl,
  89658. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89659. backgroundYRotation: 0,
  89660. sizeAuto: true,
  89661. rootPosition: BABYLON.Vector3.Zero(),
  89662. setupImageProcessing: true,
  89663. environmentTexture: this._environmentTextureCDNUrl,
  89664. cameraExposure: 0.8,
  89665. cameraContrast: 1.2,
  89666. toneMappingEnabled: true,
  89667. };
  89668. };
  89669. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89670. /**
  89671. * Gets the root mesh created by the helper.
  89672. */
  89673. get: function () {
  89674. return this._rootMesh;
  89675. },
  89676. enumerable: true,
  89677. configurable: true
  89678. });
  89679. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89680. /**
  89681. * Gets the skybox created by the helper.
  89682. */
  89683. get: function () {
  89684. return this._skybox;
  89685. },
  89686. enumerable: true,
  89687. configurable: true
  89688. });
  89689. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89690. /**
  89691. * Gets the skybox texture created by the helper.
  89692. */
  89693. get: function () {
  89694. return this._skyboxTexture;
  89695. },
  89696. enumerable: true,
  89697. configurable: true
  89698. });
  89699. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89700. /**
  89701. * Gets the skybox material created by the helper.
  89702. */
  89703. get: function () {
  89704. return this._skyboxMaterial;
  89705. },
  89706. enumerable: true,
  89707. configurable: true
  89708. });
  89709. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89710. /**
  89711. * Gets the ground mesh created by the helper.
  89712. */
  89713. get: function () {
  89714. return this._ground;
  89715. },
  89716. enumerable: true,
  89717. configurable: true
  89718. });
  89719. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89720. /**
  89721. * Gets the ground texture created by the helper.
  89722. */
  89723. get: function () {
  89724. return this._groundTexture;
  89725. },
  89726. enumerable: true,
  89727. configurable: true
  89728. });
  89729. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89730. /**
  89731. * Gets the ground mirror created by the helper.
  89732. */
  89733. get: function () {
  89734. return this._groundMirror;
  89735. },
  89736. enumerable: true,
  89737. configurable: true
  89738. });
  89739. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89740. /**
  89741. * Gets the ground mirror render list to helps pushing the meshes
  89742. * you wish in the ground reflection.
  89743. */
  89744. get: function () {
  89745. if (this._groundMirror) {
  89746. return this._groundMirror.renderList;
  89747. }
  89748. return null;
  89749. },
  89750. enumerable: true,
  89751. configurable: true
  89752. });
  89753. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89754. /**
  89755. * Gets the ground material created by the helper.
  89756. */
  89757. get: function () {
  89758. return this._groundMaterial;
  89759. },
  89760. enumerable: true,
  89761. configurable: true
  89762. });
  89763. /**
  89764. * Updates the background according to the new options
  89765. * @param options
  89766. */
  89767. EnvironmentHelper.prototype.updateOptions = function (options) {
  89768. var newOptions = __assign({}, this._options, options);
  89769. if (this._ground && !newOptions.createGround) {
  89770. this._ground.dispose();
  89771. this._ground = null;
  89772. }
  89773. if (this._groundMaterial && !newOptions.createGround) {
  89774. this._groundMaterial.dispose();
  89775. this._groundMaterial = null;
  89776. }
  89777. if (this._groundTexture) {
  89778. if (this._options.groundTexture != newOptions.groundTexture) {
  89779. this._groundTexture.dispose();
  89780. this._groundTexture = null;
  89781. }
  89782. }
  89783. if (this._skybox && !newOptions.createSkybox) {
  89784. this._skybox.dispose();
  89785. this._skybox = null;
  89786. }
  89787. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89788. this._skyboxMaterial.dispose();
  89789. this._skyboxMaterial = null;
  89790. }
  89791. if (this._skyboxTexture) {
  89792. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89793. this._skyboxTexture.dispose();
  89794. this._skyboxTexture = null;
  89795. }
  89796. }
  89797. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89798. this._groundMirror.dispose();
  89799. this._groundMirror = null;
  89800. }
  89801. if (this._scene.environmentTexture) {
  89802. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89803. this._scene.environmentTexture.dispose();
  89804. }
  89805. }
  89806. this._options = newOptions;
  89807. this._setupBackground();
  89808. this._setupImageProcessing();
  89809. };
  89810. /**
  89811. * Sets the primary color of all the available elements.
  89812. * @param color
  89813. */
  89814. EnvironmentHelper.prototype.setMainColor = function (color) {
  89815. if (this.groundMaterial) {
  89816. this.groundMaterial.primaryColor = color;
  89817. }
  89818. if (this.skyboxMaterial) {
  89819. this.skyboxMaterial.primaryColor = color;
  89820. }
  89821. if (this.groundMirror) {
  89822. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89823. }
  89824. };
  89825. /**
  89826. * Setup the image processing according to the specified options.
  89827. */
  89828. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89829. if (this._options.setupImageProcessing) {
  89830. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89831. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89832. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89833. this._setupEnvironmentTexture();
  89834. }
  89835. };
  89836. /**
  89837. * Setup the environment texture according to the specified options.
  89838. */
  89839. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89840. if (this._scene.environmentTexture) {
  89841. return;
  89842. }
  89843. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89844. this._scene.environmentTexture = this._options.environmentTexture;
  89845. return;
  89846. }
  89847. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89848. this._scene.environmentTexture = environmentTexture;
  89849. };
  89850. /**
  89851. * Setup the background according to the specified options.
  89852. */
  89853. EnvironmentHelper.prototype._setupBackground = function () {
  89854. if (!this._rootMesh) {
  89855. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89856. }
  89857. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89858. var sceneSize = this._getSceneSize();
  89859. if (this._options.createGround) {
  89860. this._setupGround(sceneSize);
  89861. this._setupGroundMaterial();
  89862. this._setupGroundDiffuseTexture();
  89863. if (this._options.enableGroundMirror) {
  89864. this._setupGroundMirrorTexture(sceneSize);
  89865. }
  89866. this._setupMirrorInGroundMaterial();
  89867. }
  89868. if (this._options.createSkybox) {
  89869. this._setupSkybox(sceneSize);
  89870. this._setupSkyboxMaterial();
  89871. this._setupSkyboxReflectionTexture();
  89872. }
  89873. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89874. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89875. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89876. };
  89877. /**
  89878. * Get the scene sizes according to the setup.
  89879. */
  89880. EnvironmentHelper.prototype._getSceneSize = function () {
  89881. var _this = this;
  89882. var groundSize = this._options.groundSize;
  89883. var skyboxSize = this._options.skyboxSize;
  89884. var rootPosition = this._options.rootPosition;
  89885. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89886. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89887. }
  89888. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89889. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89890. });
  89891. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89892. if (this._options.sizeAuto) {
  89893. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89894. this._scene.activeCamera.upperRadiusLimit) {
  89895. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89896. skyboxSize = groundSize;
  89897. }
  89898. var sceneDiagonalLenght = sceneDiagonal.length();
  89899. if (sceneDiagonalLenght > groundSize) {
  89900. groundSize = sceneDiagonalLenght * 2;
  89901. skyboxSize = groundSize;
  89902. }
  89903. // 10 % bigger.
  89904. groundSize *= 1.1;
  89905. skyboxSize *= 1.5;
  89906. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89907. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89908. }
  89909. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89910. };
  89911. /**
  89912. * Setup the ground according to the specified options.
  89913. */
  89914. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89915. var _this = this;
  89916. if (!this._ground) {
  89917. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89918. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89919. this._ground.parent = this._rootMesh;
  89920. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89921. }
  89922. this._ground.receiveShadows = this._options.enableGroundShadow;
  89923. };
  89924. /**
  89925. * Setup the ground material according to the specified options.
  89926. */
  89927. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89928. if (!this._groundMaterial) {
  89929. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89930. }
  89931. this._groundMaterial.alpha = this._options.groundOpacity;
  89932. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89933. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89934. this._groundMaterial.primaryLevel = 1;
  89935. this._groundMaterial.primaryColor = this._options.groundColor;
  89936. this._groundMaterial.secondaryLevel = 0;
  89937. this._groundMaterial.tertiaryLevel = 0;
  89938. this._groundMaterial.useRGBColor = false;
  89939. this._groundMaterial.enableNoise = true;
  89940. if (this._ground) {
  89941. this._ground.material = this._groundMaterial;
  89942. }
  89943. };
  89944. /**
  89945. * Setup the ground diffuse texture according to the specified options.
  89946. */
  89947. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89948. if (!this._groundMaterial) {
  89949. return;
  89950. }
  89951. if (this._groundTexture) {
  89952. return;
  89953. }
  89954. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89955. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89956. return;
  89957. }
  89958. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89959. diffuseTexture.gammaSpace = false;
  89960. diffuseTexture.hasAlpha = true;
  89961. this._groundMaterial.diffuseTexture = diffuseTexture;
  89962. };
  89963. /**
  89964. * Setup the ground mirror texture according to the specified options.
  89965. */
  89966. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89967. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89968. if (!this._groundMirror) {
  89969. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89970. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89971. this._groundMirror.anisotropicFilteringLevel = 1;
  89972. this._groundMirror.wrapU = wrapping;
  89973. this._groundMirror.wrapV = wrapping;
  89974. this._groundMirror.gammaSpace = false;
  89975. if (this._groundMirror.renderList) {
  89976. for (var i = 0; i < this._scene.meshes.length; i++) {
  89977. var mesh = this._scene.meshes[i];
  89978. if (mesh !== this._ground &&
  89979. mesh !== this._skybox &&
  89980. mesh !== this._rootMesh) {
  89981. this._groundMirror.renderList.push(mesh);
  89982. }
  89983. }
  89984. }
  89985. }
  89986. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89987. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89988. };
  89989. /**
  89990. * Setup the ground to receive the mirror texture.
  89991. */
  89992. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89993. if (this._groundMaterial) {
  89994. this._groundMaterial.reflectionTexture = this._groundMirror;
  89995. this._groundMaterial.reflectionFresnel = true;
  89996. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89997. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89998. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89999. }
  90000. };
  90001. /**
  90002. * Setup the skybox according to the specified options.
  90003. */
  90004. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90005. var _this = this;
  90006. if (!this._skybox) {
  90007. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90008. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90009. }
  90010. this._skybox.parent = this._rootMesh;
  90011. };
  90012. /**
  90013. * Setup the skybox material according to the specified options.
  90014. */
  90015. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90016. if (!this._skybox) {
  90017. return;
  90018. }
  90019. if (!this._skyboxMaterial) {
  90020. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90021. }
  90022. this._skyboxMaterial.useRGBColor = false;
  90023. this._skyboxMaterial.primaryLevel = 1;
  90024. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90025. this._skyboxMaterial.secondaryLevel = 0;
  90026. this._skyboxMaterial.tertiaryLevel = 0;
  90027. this._skyboxMaterial.enableNoise = true;
  90028. this._skybox.material = this._skyboxMaterial;
  90029. };
  90030. /**
  90031. * Setup the skybox reflection texture according to the specified options.
  90032. */
  90033. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90034. if (!this._skyboxMaterial) {
  90035. return;
  90036. }
  90037. if (this._skyboxTexture) {
  90038. return;
  90039. }
  90040. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90041. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90042. return;
  90043. }
  90044. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90045. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90046. this._skyboxTexture.gammaSpace = false;
  90047. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90048. };
  90049. /**
  90050. * Dispose all the elements created by the Helper.
  90051. */
  90052. EnvironmentHelper.prototype.dispose = function () {
  90053. if (this._groundMaterial) {
  90054. this._groundMaterial.dispose(true, true);
  90055. }
  90056. if (this._skyboxMaterial) {
  90057. this._skyboxMaterial.dispose(true, true);
  90058. }
  90059. this._rootMesh.dispose(false);
  90060. };
  90061. /**
  90062. * Default ground texture URL.
  90063. */
  90064. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90065. /**
  90066. * Default skybox texture URL.
  90067. */
  90068. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90069. /**
  90070. * Default environment texture URL.
  90071. */
  90072. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90073. return EnvironmentHelper;
  90074. }());
  90075. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90076. })(BABYLON || (BABYLON = {}));
  90077. //# sourceMappingURL=babylon.environmentHelper.js.map
  90078. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  90079. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  90080. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90081. var BABYLON;
  90082. (function (BABYLON) {
  90083. var GridMaterialDefines = /** @class */ (function (_super) {
  90084. __extends(GridMaterialDefines, _super);
  90085. function GridMaterialDefines() {
  90086. var _this = _super.call(this) || this;
  90087. _this.TRANSPARENT = false;
  90088. _this.FOG = false;
  90089. _this.PREMULTIPLYALPHA = false;
  90090. _this.rebuild();
  90091. return _this;
  90092. }
  90093. return GridMaterialDefines;
  90094. }(BABYLON.MaterialDefines));
  90095. /**
  90096. * The grid materials allows you to wrap any shape with a grid.
  90097. * Colors are customizable.
  90098. */
  90099. var GridMaterial = /** @class */ (function (_super) {
  90100. __extends(GridMaterial, _super);
  90101. /**
  90102. * constructor
  90103. * @param name The name given to the material in order to identify it afterwards.
  90104. * @param scene The scene the material is used in.
  90105. */
  90106. function GridMaterial(name, scene) {
  90107. var _this = _super.call(this, name, scene) || this;
  90108. /**
  90109. * Main color of the grid (e.g. between lines)
  90110. */
  90111. _this.mainColor = BABYLON.Color3.Black();
  90112. /**
  90113. * Color of the grid lines.
  90114. */
  90115. _this.lineColor = BABYLON.Color3.Teal();
  90116. /**
  90117. * The scale of the grid compared to unit.
  90118. */
  90119. _this.gridRatio = 1.0;
  90120. /**
  90121. * Allows setting an offset for the grid lines.
  90122. */
  90123. _this.gridOffset = BABYLON.Vector3.Zero();
  90124. /**
  90125. * The frequency of thicker lines.
  90126. */
  90127. _this.majorUnitFrequency = 10;
  90128. /**
  90129. * The visibility of minor units in the grid.
  90130. */
  90131. _this.minorUnitVisibility = 0.33;
  90132. /**
  90133. * The grid opacity outside of the lines.
  90134. */
  90135. _this.opacity = 1.0;
  90136. /**
  90137. * Determine RBG output is premultiplied by alpha value.
  90138. */
  90139. _this.preMultiplyAlpha = false;
  90140. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  90141. return _this;
  90142. }
  90143. /**
  90144. * Returns wehter or not the grid requires alpha blending.
  90145. */
  90146. GridMaterial.prototype.needAlphaBlending = function () {
  90147. return this.opacity < 1.0;
  90148. };
  90149. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  90150. return this.needAlphaBlending();
  90151. };
  90152. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90153. if (this.isFrozen) {
  90154. if (this._wasPreviouslyReady && subMesh.effect) {
  90155. return true;
  90156. }
  90157. }
  90158. if (!subMesh._materialDefines) {
  90159. subMesh._materialDefines = new GridMaterialDefines();
  90160. }
  90161. var defines = subMesh._materialDefines;
  90162. var scene = this.getScene();
  90163. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90164. if (this._renderId === scene.getRenderId()) {
  90165. return true;
  90166. }
  90167. }
  90168. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  90169. defines.TRANSPARENT = !defines.TRANSPARENT;
  90170. defines.markAsUnprocessed();
  90171. }
  90172. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  90173. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  90174. defines.markAsUnprocessed();
  90175. }
  90176. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  90177. // Get correct effect
  90178. if (defines.isDirty) {
  90179. defines.markAsProcessed();
  90180. scene.resetCachedMaterial();
  90181. // Attributes
  90182. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90183. // Defines
  90184. var join = defines.toString();
  90185. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  90186. }
  90187. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90188. return false;
  90189. }
  90190. this._renderId = scene.getRenderId();
  90191. this._wasPreviouslyReady = true;
  90192. return true;
  90193. };
  90194. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90195. var scene = this.getScene();
  90196. var defines = subMesh._materialDefines;
  90197. if (!defines) {
  90198. return;
  90199. }
  90200. var effect = subMesh.effect;
  90201. if (!effect) {
  90202. return;
  90203. }
  90204. this._activeEffect = effect;
  90205. // Matrices
  90206. this.bindOnlyWorldMatrix(world);
  90207. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  90208. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  90209. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  90210. // Uniforms
  90211. if (this._mustRebind(scene, effect)) {
  90212. this._activeEffect.setColor3("mainColor", this.mainColor);
  90213. this._activeEffect.setColor3("lineColor", this.lineColor);
  90214. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  90215. this._gridControl.x = this.gridRatio;
  90216. this._gridControl.y = Math.round(this.majorUnitFrequency);
  90217. this._gridControl.z = this.minorUnitVisibility;
  90218. this._gridControl.w = this.opacity;
  90219. this._activeEffect.setVector4("gridControl", this._gridControl);
  90220. }
  90221. // Fog
  90222. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90223. this._afterBind(mesh, this._activeEffect);
  90224. };
  90225. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  90226. _super.prototype.dispose.call(this, forceDisposeEffect);
  90227. };
  90228. GridMaterial.prototype.clone = function (name) {
  90229. var _this = this;
  90230. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  90231. };
  90232. GridMaterial.prototype.serialize = function () {
  90233. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90234. serializationObject.customType = "BABYLON.GridMaterial";
  90235. return serializationObject;
  90236. };
  90237. GridMaterial.prototype.getClassName = function () {
  90238. return "GridMaterial";
  90239. };
  90240. GridMaterial.Parse = function (source, scene, rootUrl) {
  90241. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  90242. };
  90243. __decorate([
  90244. BABYLON.serializeAsColor3()
  90245. ], GridMaterial.prototype, "mainColor", void 0);
  90246. __decorate([
  90247. BABYLON.serializeAsColor3()
  90248. ], GridMaterial.prototype, "lineColor", void 0);
  90249. __decorate([
  90250. BABYLON.serialize()
  90251. ], GridMaterial.prototype, "gridRatio", void 0);
  90252. __decorate([
  90253. BABYLON.serializeAsColor3()
  90254. ], GridMaterial.prototype, "gridOffset", void 0);
  90255. __decorate([
  90256. BABYLON.serialize()
  90257. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  90258. __decorate([
  90259. BABYLON.serialize()
  90260. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  90261. __decorate([
  90262. BABYLON.serialize()
  90263. ], GridMaterial.prototype, "opacity", void 0);
  90264. __decorate([
  90265. BABYLON.serialize()
  90266. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  90267. return GridMaterial;
  90268. }(BABYLON.PushMaterial));
  90269. BABYLON.GridMaterial = GridMaterial;
  90270. })(BABYLON || (BABYLON = {}));
  90271. //# sourceMappingURL=babylon.gridmaterial.js.map
  90272. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  90273. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  90274. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90275. var BABYLON;
  90276. (function (BABYLON) {
  90277. var GLTFLoaderCoordinateSystemMode;
  90278. (function (GLTFLoaderCoordinateSystemMode) {
  90279. /**
  90280. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  90281. */
  90282. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  90283. /**
  90284. * Sets the useRightHandedSystem flag on the scene.
  90285. */
  90286. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  90287. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  90288. var GLTFLoaderAnimationStartMode;
  90289. (function (GLTFLoaderAnimationStartMode) {
  90290. /**
  90291. * No animation will start.
  90292. */
  90293. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  90294. /**
  90295. * The first animation will start.
  90296. */
  90297. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  90298. /**
  90299. * All animations will start.
  90300. */
  90301. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  90302. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  90303. var GLTFLoaderState;
  90304. (function (GLTFLoaderState) {
  90305. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  90306. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  90307. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  90308. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  90309. var GLTFFileLoader = /** @class */ (function () {
  90310. function GLTFFileLoader() {
  90311. // #region Common options
  90312. /**
  90313. * Raised when the asset has been parsed.
  90314. * The data.json property stores the glTF JSON.
  90315. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  90316. */
  90317. this.onParsedObservable = new BABYLON.Observable();
  90318. // #endregion
  90319. // #region V2 options
  90320. /**
  90321. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  90322. */
  90323. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  90324. /**
  90325. * The animation start mode (NONE, FIRST, ALL).
  90326. */
  90327. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90328. /**
  90329. * Set to true to compile materials before raising the success callback.
  90330. */
  90331. this.compileMaterials = false;
  90332. /**
  90333. * Set to true to also compile materials with clip planes.
  90334. */
  90335. this.useClipPlane = false;
  90336. /**
  90337. * Set to true to compile shadow generators before raising the success callback.
  90338. */
  90339. this.compileShadowGenerators = false;
  90340. /**
  90341. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90342. */
  90343. this.onMeshLoadedObservable = new BABYLON.Observable();
  90344. /**
  90345. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90346. */
  90347. this.onTextureLoadedObservable = new BABYLON.Observable();
  90348. /**
  90349. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90350. */
  90351. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90352. /**
  90353. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90354. */
  90355. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90356. /**
  90357. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90358. * For assets with LODs, raised when all of the LODs are complete.
  90359. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90360. */
  90361. this.onCompleteObservable = new BABYLON.Observable();
  90362. /**
  90363. * Raised when the loader is disposed.
  90364. */
  90365. this.onDisposeObservable = new BABYLON.Observable();
  90366. /**
  90367. * Raised after a loader extension is created.
  90368. * Set additional options for a loader extension in this event.
  90369. */
  90370. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90371. // #endregion
  90372. this._loader = null;
  90373. this.name = "gltf";
  90374. this.extensions = {
  90375. ".gltf": { isBinary: false },
  90376. ".glb": { isBinary: true }
  90377. };
  90378. }
  90379. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90380. set: function (callback) {
  90381. if (this._onParsedObserver) {
  90382. this.onParsedObservable.remove(this._onParsedObserver);
  90383. }
  90384. this._onParsedObserver = this.onParsedObservable.add(callback);
  90385. },
  90386. enumerable: true,
  90387. configurable: true
  90388. });
  90389. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90390. set: function (callback) {
  90391. if (this._onMeshLoadedObserver) {
  90392. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90393. }
  90394. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90395. },
  90396. enumerable: true,
  90397. configurable: true
  90398. });
  90399. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90400. set: function (callback) {
  90401. if (this._onTextureLoadedObserver) {
  90402. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90403. }
  90404. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90405. },
  90406. enumerable: true,
  90407. configurable: true
  90408. });
  90409. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90410. set: function (callback) {
  90411. if (this._onMaterialLoadedObserver) {
  90412. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90413. }
  90414. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90415. },
  90416. enumerable: true,
  90417. configurable: true
  90418. });
  90419. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90420. set: function (callback) {
  90421. if (this._onAnimationGroupLoadedObserver) {
  90422. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90423. }
  90424. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90425. },
  90426. enumerable: true,
  90427. configurable: true
  90428. });
  90429. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90430. set: function (callback) {
  90431. if (this._onCompleteObserver) {
  90432. this.onCompleteObservable.remove(this._onCompleteObserver);
  90433. }
  90434. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90435. },
  90436. enumerable: true,
  90437. configurable: true
  90438. });
  90439. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90440. set: function (callback) {
  90441. if (this._onDisposeObserver) {
  90442. this.onDisposeObservable.remove(this._onDisposeObserver);
  90443. }
  90444. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90445. },
  90446. enumerable: true,
  90447. configurable: true
  90448. });
  90449. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90450. set: function (callback) {
  90451. if (this._onExtensionLoadedObserver) {
  90452. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90453. }
  90454. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90455. },
  90456. enumerable: true,
  90457. configurable: true
  90458. });
  90459. /**
  90460. * Gets a promise that resolves when the asset is completely loaded.
  90461. * @returns A promise that resolves when the asset is completely loaded.
  90462. */
  90463. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90464. var _this = this;
  90465. return new Promise(function (resolve) {
  90466. _this.onCompleteObservable.add(function () {
  90467. resolve();
  90468. }, undefined, undefined, undefined, true);
  90469. });
  90470. };
  90471. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90472. /**
  90473. * The loader state or null if not active.
  90474. */
  90475. get: function () {
  90476. return this._loader ? this._loader.state : null;
  90477. },
  90478. enumerable: true,
  90479. configurable: true
  90480. });
  90481. /**
  90482. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90483. */
  90484. GLTFFileLoader.prototype.dispose = function () {
  90485. if (this._loader) {
  90486. this._loader.dispose();
  90487. this._loader = null;
  90488. }
  90489. this.onMeshLoadedObservable.clear();
  90490. this.onTextureLoadedObservable.clear();
  90491. this.onMaterialLoadedObservable.clear();
  90492. this.onDisposeObservable.notifyObservers(this);
  90493. this.onDisposeObservable.clear();
  90494. };
  90495. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90496. var _this = this;
  90497. return Promise.resolve().then(function () {
  90498. var loaderData = _this._parse(data);
  90499. _this._loader = _this._getLoader(loaderData);
  90500. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90501. });
  90502. };
  90503. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90504. var _this = this;
  90505. return Promise.resolve().then(function () {
  90506. var loaderData = _this._parse(data);
  90507. _this._loader = _this._getLoader(loaderData);
  90508. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90509. });
  90510. };
  90511. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90512. var _this = this;
  90513. return Promise.resolve().then(function () {
  90514. var loaderData = _this._parse(data);
  90515. _this._loader = _this._getLoader(loaderData);
  90516. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90517. var container = new BABYLON.AssetContainer(scene);
  90518. Array.prototype.push.apply(container.meshes, result.meshes);
  90519. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90520. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90521. container.removeAllFromScene();
  90522. return container;
  90523. });
  90524. });
  90525. };
  90526. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90527. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90528. };
  90529. GLTFFileLoader.prototype.createPlugin = function () {
  90530. return new GLTFFileLoader();
  90531. };
  90532. GLTFFileLoader.prototype._parse = function (data) {
  90533. var parsedData;
  90534. if (data instanceof ArrayBuffer) {
  90535. parsedData = GLTFFileLoader._parseBinary(data);
  90536. }
  90537. else {
  90538. parsedData = {
  90539. json: JSON.parse(data),
  90540. bin: null
  90541. };
  90542. }
  90543. this.onParsedObservable.notifyObservers(parsedData);
  90544. this.onParsedObservable.clear();
  90545. return parsedData;
  90546. };
  90547. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90548. var _this = this;
  90549. var loaderVersion = { major: 2, minor: 0 };
  90550. var asset = loaderData.json.asset || {};
  90551. var version = GLTFFileLoader._parseVersion(asset.version);
  90552. if (!version) {
  90553. throw new Error("Invalid version: " + asset.version);
  90554. }
  90555. if (asset.minVersion !== undefined) {
  90556. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90557. if (!minVersion) {
  90558. throw new Error("Invalid minimum version: " + asset.minVersion);
  90559. }
  90560. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90561. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90562. }
  90563. }
  90564. var createLoaders = {
  90565. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90566. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90567. };
  90568. var createLoader = createLoaders[version.major];
  90569. if (!createLoader) {
  90570. throw new Error("Unsupported version: " + asset.version);
  90571. }
  90572. var loader = createLoader();
  90573. loader.coordinateSystemMode = this.coordinateSystemMode;
  90574. loader.animationStartMode = this.animationStartMode;
  90575. loader.compileMaterials = this.compileMaterials;
  90576. loader.useClipPlane = this.useClipPlane;
  90577. loader.compileShadowGenerators = this.compileShadowGenerators;
  90578. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90579. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90580. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90581. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90582. loader.onCompleteObservable.add(function () {
  90583. _this.onMeshLoadedObservable.clear();
  90584. _this.onTextureLoadedObservable.clear();
  90585. _this.onMaterialLoadedObservable.clear();
  90586. _this.onCompleteObservable.notifyObservers(_this);
  90587. _this.onCompleteObservable.clear();
  90588. });
  90589. return loader;
  90590. };
  90591. GLTFFileLoader._parseBinary = function (data) {
  90592. var Binary = {
  90593. Magic: 0x46546C67
  90594. };
  90595. var binaryReader = new BinaryReader(data);
  90596. var magic = binaryReader.readUint32();
  90597. if (magic !== Binary.Magic) {
  90598. throw new Error("Unexpected magic: " + magic);
  90599. }
  90600. var version = binaryReader.readUint32();
  90601. switch (version) {
  90602. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90603. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90604. }
  90605. throw new Error("Unsupported version: " + version);
  90606. };
  90607. GLTFFileLoader._parseV1 = function (binaryReader) {
  90608. var ContentFormat = {
  90609. JSON: 0
  90610. };
  90611. var length = binaryReader.readUint32();
  90612. if (length != binaryReader.getLength()) {
  90613. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90614. }
  90615. var contentLength = binaryReader.readUint32();
  90616. var contentFormat = binaryReader.readUint32();
  90617. var content;
  90618. switch (contentFormat) {
  90619. case ContentFormat.JSON: {
  90620. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90621. break;
  90622. }
  90623. default: {
  90624. throw new Error("Unexpected content format: " + contentFormat);
  90625. }
  90626. }
  90627. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90628. var body = binaryReader.readUint8Array(bytesRemaining);
  90629. return {
  90630. json: content,
  90631. bin: body
  90632. };
  90633. };
  90634. GLTFFileLoader._parseV2 = function (binaryReader) {
  90635. var ChunkFormat = {
  90636. JSON: 0x4E4F534A,
  90637. BIN: 0x004E4942
  90638. };
  90639. var length = binaryReader.readUint32();
  90640. if (length !== binaryReader.getLength()) {
  90641. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90642. }
  90643. // JSON chunk
  90644. var chunkLength = binaryReader.readUint32();
  90645. var chunkFormat = binaryReader.readUint32();
  90646. if (chunkFormat !== ChunkFormat.JSON) {
  90647. throw new Error("First chunk format is not JSON");
  90648. }
  90649. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90650. // Look for BIN chunk
  90651. var bin = null;
  90652. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90653. var chunkLength_1 = binaryReader.readUint32();
  90654. var chunkFormat_1 = binaryReader.readUint32();
  90655. switch (chunkFormat_1) {
  90656. case ChunkFormat.JSON: {
  90657. throw new Error("Unexpected JSON chunk");
  90658. }
  90659. case ChunkFormat.BIN: {
  90660. bin = binaryReader.readUint8Array(chunkLength_1);
  90661. break;
  90662. }
  90663. default: {
  90664. // ignore unrecognized chunkFormat
  90665. binaryReader.skipBytes(chunkLength_1);
  90666. break;
  90667. }
  90668. }
  90669. }
  90670. return {
  90671. json: json,
  90672. bin: bin
  90673. };
  90674. };
  90675. GLTFFileLoader._parseVersion = function (version) {
  90676. if (version === "1.0" || version === "1.0.1") {
  90677. return {
  90678. major: 1,
  90679. minor: 0
  90680. };
  90681. }
  90682. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90683. if (!match) {
  90684. return null;
  90685. }
  90686. return {
  90687. major: parseInt(match[1]),
  90688. minor: parseInt(match[2])
  90689. };
  90690. };
  90691. GLTFFileLoader._compareVersion = function (a, b) {
  90692. if (a.major > b.major)
  90693. return 1;
  90694. if (a.major < b.major)
  90695. return -1;
  90696. if (a.minor > b.minor)
  90697. return 1;
  90698. if (a.minor < b.minor)
  90699. return -1;
  90700. return 0;
  90701. };
  90702. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90703. var result = "";
  90704. var length = buffer.byteLength;
  90705. for (var i = 0; i < length; i++) {
  90706. result += String.fromCharCode(buffer[i]);
  90707. }
  90708. return result;
  90709. };
  90710. // #endregion
  90711. // #region V1 options
  90712. GLTFFileLoader.IncrementalLoading = true;
  90713. GLTFFileLoader.HomogeneousCoordinates = false;
  90714. return GLTFFileLoader;
  90715. }());
  90716. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90717. var BinaryReader = /** @class */ (function () {
  90718. function BinaryReader(arrayBuffer) {
  90719. this._arrayBuffer = arrayBuffer;
  90720. this._dataView = new DataView(arrayBuffer);
  90721. this._byteOffset = 0;
  90722. }
  90723. BinaryReader.prototype.getPosition = function () {
  90724. return this._byteOffset;
  90725. };
  90726. BinaryReader.prototype.getLength = function () {
  90727. return this._arrayBuffer.byteLength;
  90728. };
  90729. BinaryReader.prototype.readUint32 = function () {
  90730. var value = this._dataView.getUint32(this._byteOffset, true);
  90731. this._byteOffset += 4;
  90732. return value;
  90733. };
  90734. BinaryReader.prototype.readUint8Array = function (length) {
  90735. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90736. this._byteOffset += length;
  90737. return value;
  90738. };
  90739. BinaryReader.prototype.skipBytes = function (length) {
  90740. this._byteOffset += length;
  90741. };
  90742. return BinaryReader;
  90743. }());
  90744. if (BABYLON.SceneLoader) {
  90745. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90746. }
  90747. })(BABYLON || (BABYLON = {}));
  90748. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90749. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90750. var BABYLON;
  90751. (function (BABYLON) {
  90752. var GLTF1;
  90753. (function (GLTF1) {
  90754. /**
  90755. * Enums
  90756. */
  90757. var EComponentType;
  90758. (function (EComponentType) {
  90759. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90760. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90761. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90762. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90763. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90764. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90765. var EShaderType;
  90766. (function (EShaderType) {
  90767. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90768. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90769. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90770. var EParameterType;
  90771. (function (EParameterType) {
  90772. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90773. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90774. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90775. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90776. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90777. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90778. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90779. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90780. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90781. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90782. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90783. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90784. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90785. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90786. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90787. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90788. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90789. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90790. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90791. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90792. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90793. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90794. var ETextureWrapMode;
  90795. (function (ETextureWrapMode) {
  90796. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90797. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90798. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90799. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90800. var ETextureFilterType;
  90801. (function (ETextureFilterType) {
  90802. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90803. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90804. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90805. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90806. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90807. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90808. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90809. var ETextureFormat;
  90810. (function (ETextureFormat) {
  90811. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90812. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90813. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90814. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90815. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90816. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90817. var ECullingType;
  90818. (function (ECullingType) {
  90819. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90820. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90821. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90822. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90823. var EBlendingFunction;
  90824. (function (EBlendingFunction) {
  90825. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90826. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90827. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90828. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90829. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90830. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90831. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90832. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90833. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90834. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90835. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90836. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90837. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90838. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90839. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90840. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90841. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90842. })(BABYLON || (BABYLON = {}));
  90843. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90844. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90845. var BABYLON;
  90846. (function (BABYLON) {
  90847. var GLTF1;
  90848. (function (GLTF1) {
  90849. /**
  90850. * Tokenizer. Used for shaders compatibility
  90851. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90852. */
  90853. var ETokenType;
  90854. (function (ETokenType) {
  90855. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90856. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90857. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90858. })(ETokenType || (ETokenType = {}));
  90859. var Tokenizer = /** @class */ (function () {
  90860. function Tokenizer(toParse) {
  90861. this._pos = 0;
  90862. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90863. this._toParse = toParse;
  90864. this._maxPos = toParse.length;
  90865. }
  90866. Tokenizer.prototype.getNextToken = function () {
  90867. if (this.isEnd())
  90868. return ETokenType.END_OF_INPUT;
  90869. this.currentString = this.read();
  90870. this.currentToken = ETokenType.UNKNOWN;
  90871. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90872. this.currentToken = ETokenType.IDENTIFIER;
  90873. this.currentIdentifier = this.currentString;
  90874. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90875. this.currentIdentifier += this.currentString;
  90876. this.forward();
  90877. }
  90878. }
  90879. return this.currentToken;
  90880. };
  90881. Tokenizer.prototype.peek = function () {
  90882. return this._toParse[this._pos];
  90883. };
  90884. Tokenizer.prototype.read = function () {
  90885. return this._toParse[this._pos++];
  90886. };
  90887. Tokenizer.prototype.forward = function () {
  90888. this._pos++;
  90889. };
  90890. Tokenizer.prototype.isEnd = function () {
  90891. return this._pos >= this._maxPos;
  90892. };
  90893. return Tokenizer;
  90894. }());
  90895. /**
  90896. * Values
  90897. */
  90898. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90899. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90900. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90901. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90902. /**
  90903. * Parse
  90904. */
  90905. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90906. for (var buf in parsedBuffers) {
  90907. var parsedBuffer = parsedBuffers[buf];
  90908. gltfRuntime.buffers[buf] = parsedBuffer;
  90909. gltfRuntime.buffersCount++;
  90910. }
  90911. };
  90912. var parseShaders = function (parsedShaders, gltfRuntime) {
  90913. for (var sha in parsedShaders) {
  90914. var parsedShader = parsedShaders[sha];
  90915. gltfRuntime.shaders[sha] = parsedShader;
  90916. gltfRuntime.shaderscount++;
  90917. }
  90918. };
  90919. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90920. for (var object in parsedObjects) {
  90921. var parsedObject = parsedObjects[object];
  90922. gltfRuntime[runtimeProperty][object] = parsedObject;
  90923. }
  90924. };
  90925. /**
  90926. * Utils
  90927. */
  90928. var normalizeUVs = function (buffer) {
  90929. if (!buffer) {
  90930. return;
  90931. }
  90932. for (var i = 0; i < buffer.length / 2; i++) {
  90933. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90934. }
  90935. };
  90936. var getAttribute = function (attributeParameter) {
  90937. if (attributeParameter.semantic === "NORMAL") {
  90938. return "normal";
  90939. }
  90940. else if (attributeParameter.semantic === "POSITION") {
  90941. return "position";
  90942. }
  90943. else if (attributeParameter.semantic === "JOINT") {
  90944. return "matricesIndices";
  90945. }
  90946. else if (attributeParameter.semantic === "WEIGHT") {
  90947. return "matricesWeights";
  90948. }
  90949. else if (attributeParameter.semantic === "COLOR") {
  90950. return "color";
  90951. }
  90952. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90953. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90954. return "uv" + (channel === 0 ? "" : channel + 1);
  90955. }
  90956. return null;
  90957. };
  90958. /**
  90959. * Loads and creates animations
  90960. */
  90961. var loadAnimations = function (gltfRuntime) {
  90962. for (var anim in gltfRuntime.animations) {
  90963. var animation = gltfRuntime.animations[anim];
  90964. if (!animation.channels || !animation.samplers) {
  90965. continue;
  90966. }
  90967. var lastAnimation = null;
  90968. for (var i = 0; i < animation.channels.length; i++) {
  90969. // Get parameters and load buffers
  90970. var channel = animation.channels[i];
  90971. var sampler = animation.samplers[channel.sampler];
  90972. if (!sampler) {
  90973. continue;
  90974. }
  90975. var inputData = null;
  90976. var outputData = null;
  90977. if (animation.parameters) {
  90978. inputData = animation.parameters[sampler.input];
  90979. outputData = animation.parameters[sampler.output];
  90980. }
  90981. else {
  90982. inputData = sampler.input;
  90983. outputData = sampler.output;
  90984. }
  90985. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90986. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90987. var targetID = channel.target.id;
  90988. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90989. if (targetNode === null) {
  90990. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90991. }
  90992. if (targetNode === null) {
  90993. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90994. continue;
  90995. }
  90996. var isBone = targetNode instanceof BABYLON.Bone;
  90997. // Get target path (position, rotation or scaling)
  90998. var targetPath = channel.target.path;
  90999. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  91000. if (targetPathIndex !== -1) {
  91001. targetPath = babylonAnimationPaths[targetPathIndex];
  91002. }
  91003. // Determine animation type
  91004. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  91005. if (!isBone) {
  91006. if (targetPath === "rotationQuaternion") {
  91007. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91008. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  91009. }
  91010. else {
  91011. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91012. }
  91013. }
  91014. // Create animation and key frames
  91015. var babylonAnimation = null;
  91016. var keys = [];
  91017. var arrayOffset = 0;
  91018. var modifyKey = false;
  91019. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  91020. babylonAnimation = lastAnimation;
  91021. modifyKey = true;
  91022. }
  91023. if (!modifyKey) {
  91024. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91025. }
  91026. // For each frame
  91027. for (var j = 0; j < bufferInput.length; j++) {
  91028. var value = null;
  91029. if (targetPath === "rotationQuaternion") {
  91030. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  91031. arrayOffset += 4;
  91032. }
  91033. else {
  91034. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  91035. arrayOffset += 3;
  91036. }
  91037. if (isBone) {
  91038. var bone = targetNode;
  91039. var translation = BABYLON.Vector3.Zero();
  91040. var rotationQuaternion = new BABYLON.Quaternion();
  91041. var scaling = BABYLON.Vector3.Zero();
  91042. // Warning on decompose
  91043. var mat = bone.getBaseMatrix();
  91044. if (modifyKey && lastAnimation) {
  91045. mat = lastAnimation.getKeys()[j].value;
  91046. }
  91047. mat.decompose(scaling, rotationQuaternion, translation);
  91048. if (targetPath === "position") {
  91049. translation = value;
  91050. }
  91051. else if (targetPath === "rotationQuaternion") {
  91052. rotationQuaternion = value;
  91053. }
  91054. else {
  91055. scaling = value;
  91056. }
  91057. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  91058. }
  91059. if (!modifyKey) {
  91060. keys.push({
  91061. frame: bufferInput[j],
  91062. value: value
  91063. });
  91064. }
  91065. else if (lastAnimation) {
  91066. lastAnimation.getKeys()[j].value = value;
  91067. }
  91068. }
  91069. // Finish
  91070. if (!modifyKey && babylonAnimation) {
  91071. babylonAnimation.setKeys(keys);
  91072. targetNode.animations.push(babylonAnimation);
  91073. }
  91074. lastAnimation = babylonAnimation;
  91075. gltfRuntime.scene.stopAnimation(targetNode);
  91076. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  91077. }
  91078. }
  91079. };
  91080. /**
  91081. * Returns the bones transformation matrix
  91082. */
  91083. var configureBoneTransformation = function (node) {
  91084. var mat = null;
  91085. if (node.translation || node.rotation || node.scale) {
  91086. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  91087. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  91088. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  91089. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  91090. }
  91091. else {
  91092. mat = BABYLON.Matrix.FromArray(node.matrix);
  91093. }
  91094. return mat;
  91095. };
  91096. /**
  91097. * Returns the parent bone
  91098. */
  91099. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  91100. // Try to find
  91101. for (var i = 0; i < newSkeleton.bones.length; i++) {
  91102. if (newSkeleton.bones[i].name === jointName) {
  91103. return newSkeleton.bones[i];
  91104. }
  91105. }
  91106. // Not found, search in gltf nodes
  91107. var nodes = gltfRuntime.nodes;
  91108. for (var nde in nodes) {
  91109. var node = nodes[nde];
  91110. if (!node.jointName) {
  91111. continue;
  91112. }
  91113. var children = node.children;
  91114. for (var i = 0; i < children.length; i++) {
  91115. var child = gltfRuntime.nodes[children[i]];
  91116. if (!child.jointName) {
  91117. continue;
  91118. }
  91119. if (child.jointName === jointName) {
  91120. var mat = configureBoneTransformation(node);
  91121. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  91122. bone.id = nde;
  91123. return bone;
  91124. }
  91125. }
  91126. }
  91127. return null;
  91128. };
  91129. /**
  91130. * Returns the appropriate root node
  91131. */
  91132. var getNodeToRoot = function (nodesToRoot, id) {
  91133. for (var i = 0; i < nodesToRoot.length; i++) {
  91134. var nodeToRoot = nodesToRoot[i];
  91135. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  91136. var child = nodeToRoot.node.children[j];
  91137. if (child === id) {
  91138. return nodeToRoot.bone;
  91139. }
  91140. }
  91141. }
  91142. return null;
  91143. };
  91144. /**
  91145. * Returns the node with the joint name
  91146. */
  91147. var getJointNode = function (gltfRuntime, jointName) {
  91148. var nodes = gltfRuntime.nodes;
  91149. var node = nodes[jointName];
  91150. if (node) {
  91151. return {
  91152. node: node,
  91153. id: jointName
  91154. };
  91155. }
  91156. for (var nde in nodes) {
  91157. node = nodes[nde];
  91158. if (node.jointName === jointName) {
  91159. return {
  91160. node: node,
  91161. id: nde
  91162. };
  91163. }
  91164. }
  91165. return null;
  91166. };
  91167. /**
  91168. * Checks if a nodes is in joints
  91169. */
  91170. var nodeIsInJoints = function (skins, id) {
  91171. for (var i = 0; i < skins.jointNames.length; i++) {
  91172. if (skins.jointNames[i] === id) {
  91173. return true;
  91174. }
  91175. }
  91176. return false;
  91177. };
  91178. /**
  91179. * Fills the nodes to root for bones and builds hierarchy
  91180. */
  91181. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  91182. // Creates nodes for root
  91183. for (var nde in gltfRuntime.nodes) {
  91184. var node = gltfRuntime.nodes[nde];
  91185. var id = nde;
  91186. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  91187. continue;
  91188. }
  91189. // Create node to root bone
  91190. var mat = configureBoneTransformation(node);
  91191. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  91192. bone.id = id;
  91193. nodesToRoot.push({ bone: bone, node: node, id: id });
  91194. }
  91195. // Parenting
  91196. for (var i = 0; i < nodesToRoot.length; i++) {
  91197. var nodeToRoot = nodesToRoot[i];
  91198. var children = nodeToRoot.node.children;
  91199. for (var j = 0; j < children.length; j++) {
  91200. var child = null;
  91201. for (var k = 0; k < nodesToRoot.length; k++) {
  91202. if (nodesToRoot[k].id === children[j]) {
  91203. child = nodesToRoot[k];
  91204. break;
  91205. }
  91206. }
  91207. if (child) {
  91208. child.bone._parent = nodeToRoot.bone;
  91209. nodeToRoot.bone.children.push(child.bone);
  91210. }
  91211. }
  91212. }
  91213. };
  91214. /**
  91215. * Imports a skeleton
  91216. */
  91217. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  91218. if (!newSkeleton) {
  91219. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  91220. }
  91221. if (!skins.babylonSkeleton) {
  91222. return newSkeleton;
  91223. }
  91224. // Find the root bones
  91225. var nodesToRoot = [];
  91226. var nodesToRootToAdd = [];
  91227. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  91228. newSkeleton.bones = [];
  91229. // Joints
  91230. for (var i = 0; i < skins.jointNames.length; i++) {
  91231. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91232. if (!jointNode) {
  91233. continue;
  91234. }
  91235. var node = jointNode.node;
  91236. if (!node) {
  91237. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  91238. continue;
  91239. }
  91240. var id = jointNode.id;
  91241. // Optimize, if the bone already exists...
  91242. var existingBone = gltfRuntime.scene.getBoneByID(id);
  91243. if (existingBone) {
  91244. newSkeleton.bones.push(existingBone);
  91245. continue;
  91246. }
  91247. // Search for parent bone
  91248. var foundBone = false;
  91249. var parentBone = null;
  91250. for (var j = 0; j < i; j++) {
  91251. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  91252. if (!jointNode_1) {
  91253. continue;
  91254. }
  91255. var joint = jointNode_1.node;
  91256. if (!joint) {
  91257. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  91258. continue;
  91259. }
  91260. var children = joint.children;
  91261. if (!children) {
  91262. continue;
  91263. }
  91264. foundBone = false;
  91265. for (var k = 0; k < children.length; k++) {
  91266. if (children[k] === id) {
  91267. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  91268. foundBone = true;
  91269. break;
  91270. }
  91271. }
  91272. if (foundBone) {
  91273. break;
  91274. }
  91275. }
  91276. // Create bone
  91277. var mat = configureBoneTransformation(node);
  91278. if (!parentBone && nodesToRoot.length > 0) {
  91279. parentBone = getNodeToRoot(nodesToRoot, id);
  91280. if (parentBone) {
  91281. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  91282. nodesToRootToAdd.push(parentBone);
  91283. }
  91284. }
  91285. }
  91286. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  91287. bone.id = id;
  91288. }
  91289. // Polish
  91290. var bones = newSkeleton.bones;
  91291. newSkeleton.bones = [];
  91292. for (var i = 0; i < skins.jointNames.length; i++) {
  91293. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91294. if (!jointNode) {
  91295. continue;
  91296. }
  91297. for (var j = 0; j < bones.length; j++) {
  91298. if (bones[j].id === jointNode.id) {
  91299. newSkeleton.bones.push(bones[j]);
  91300. break;
  91301. }
  91302. }
  91303. }
  91304. newSkeleton.prepare();
  91305. // Finish
  91306. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  91307. newSkeleton.bones.push(nodesToRootToAdd[i]);
  91308. }
  91309. return newSkeleton;
  91310. };
  91311. /**
  91312. * Imports a mesh and its geometries
  91313. */
  91314. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  91315. if (!newMesh) {
  91316. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91317. newMesh.id = id;
  91318. }
  91319. if (!node.babylonNode) {
  91320. return newMesh;
  91321. }
  91322. var subMaterials = [];
  91323. var vertexData = null;
  91324. var verticesStarts = new Array();
  91325. var verticesCounts = new Array();
  91326. var indexStarts = new Array();
  91327. var indexCounts = new Array();
  91328. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91329. var meshID = meshes[meshIndex];
  91330. var mesh = gltfRuntime.meshes[meshID];
  91331. if (!mesh) {
  91332. continue;
  91333. }
  91334. // Positions, normals and UVs
  91335. for (var i = 0; i < mesh.primitives.length; i++) {
  91336. // Temporary vertex data
  91337. var tempVertexData = new BABYLON.VertexData();
  91338. var primitive = mesh.primitives[i];
  91339. if (primitive.mode !== 4) {
  91340. // continue;
  91341. }
  91342. var attributes = primitive.attributes;
  91343. var accessor = null;
  91344. var buffer = null;
  91345. // Set positions, normal and uvs
  91346. for (var semantic in attributes) {
  91347. // Link accessor and buffer view
  91348. accessor = gltfRuntime.accessors[attributes[semantic]];
  91349. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91350. if (semantic === "NORMAL") {
  91351. tempVertexData.normals = new Float32Array(buffer.length);
  91352. tempVertexData.normals.set(buffer);
  91353. }
  91354. else if (semantic === "POSITION") {
  91355. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91356. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91357. for (var j = 0; j < buffer.length; j += 4) {
  91358. tempVertexData.positions[j] = buffer[j];
  91359. tempVertexData.positions[j + 1] = buffer[j + 1];
  91360. tempVertexData.positions[j + 2] = buffer[j + 2];
  91361. }
  91362. }
  91363. else {
  91364. tempVertexData.positions = new Float32Array(buffer.length);
  91365. tempVertexData.positions.set(buffer);
  91366. }
  91367. verticesCounts.push(tempVertexData.positions.length);
  91368. }
  91369. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91370. var channel = Number(semantic.split("_")[1]);
  91371. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91372. var uvs = new Float32Array(buffer.length);
  91373. uvs.set(buffer);
  91374. normalizeUVs(uvs);
  91375. tempVertexData.set(uvs, uvKind);
  91376. }
  91377. else if (semantic === "JOINT") {
  91378. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91379. tempVertexData.matricesIndices.set(buffer);
  91380. }
  91381. else if (semantic === "WEIGHT") {
  91382. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91383. tempVertexData.matricesWeights.set(buffer);
  91384. }
  91385. else if (semantic === "COLOR") {
  91386. tempVertexData.colors = new Float32Array(buffer.length);
  91387. tempVertexData.colors.set(buffer);
  91388. }
  91389. }
  91390. // Indices
  91391. accessor = gltfRuntime.accessors[primitive.indices];
  91392. if (accessor) {
  91393. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91394. tempVertexData.indices = new Int32Array(buffer.length);
  91395. tempVertexData.indices.set(buffer);
  91396. indexCounts.push(tempVertexData.indices.length);
  91397. }
  91398. else {
  91399. // Set indices on the fly
  91400. var indices = [];
  91401. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91402. indices.push(j);
  91403. }
  91404. tempVertexData.indices = new Int32Array(indices);
  91405. indexCounts.push(tempVertexData.indices.length);
  91406. }
  91407. if (!vertexData) {
  91408. vertexData = tempVertexData;
  91409. }
  91410. else {
  91411. vertexData.merge(tempVertexData);
  91412. }
  91413. // Sub material
  91414. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91415. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91416. // Update vertices start and index start
  91417. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91418. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91419. }
  91420. }
  91421. var material;
  91422. if (subMaterials.length > 1) {
  91423. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91424. material.subMaterials = subMaterials;
  91425. }
  91426. else {
  91427. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91428. }
  91429. if (subMaterials.length === 1) {
  91430. material = subMaterials[0];
  91431. }
  91432. if (!newMesh.material) {
  91433. newMesh.material = material;
  91434. }
  91435. // Apply geometry
  91436. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91437. newMesh.computeWorldMatrix(true);
  91438. // Apply submeshes
  91439. newMesh.subMeshes = [];
  91440. var index = 0;
  91441. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91442. var meshID = meshes[meshIndex];
  91443. var mesh = gltfRuntime.meshes[meshID];
  91444. if (!mesh) {
  91445. continue;
  91446. }
  91447. for (var i = 0; i < mesh.primitives.length; i++) {
  91448. if (mesh.primitives[i].mode !== 4) {
  91449. //continue;
  91450. }
  91451. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91452. index++;
  91453. }
  91454. }
  91455. // Finish
  91456. return newMesh;
  91457. };
  91458. /**
  91459. * Configure node transformation from position, rotation and scaling
  91460. */
  91461. var configureNode = function (newNode, position, rotation, scaling) {
  91462. if (newNode.position) {
  91463. newNode.position = position;
  91464. }
  91465. if (newNode.rotationQuaternion || newNode.rotation) {
  91466. newNode.rotationQuaternion = rotation;
  91467. }
  91468. if (newNode.scaling) {
  91469. newNode.scaling = scaling;
  91470. }
  91471. };
  91472. /**
  91473. * Configures node from transformation matrix
  91474. */
  91475. var configureNodeFromMatrix = function (newNode, node, parent) {
  91476. if (node.matrix) {
  91477. var position = new BABYLON.Vector3(0, 0, 0);
  91478. var rotation = new BABYLON.Quaternion();
  91479. var scaling = new BABYLON.Vector3(0, 0, 0);
  91480. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91481. mat.decompose(scaling, rotation, position);
  91482. configureNode(newNode, position, rotation, scaling);
  91483. }
  91484. else if (node.translation && node.rotation && node.scale) {
  91485. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91486. }
  91487. newNode.computeWorldMatrix(true);
  91488. };
  91489. /**
  91490. * Imports a node
  91491. */
  91492. var importNode = function (gltfRuntime, node, id, parent) {
  91493. var lastNode = null;
  91494. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91495. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91496. return null;
  91497. }
  91498. }
  91499. // Meshes
  91500. if (node.skin) {
  91501. if (node.meshes) {
  91502. var skin = gltfRuntime.skins[node.skin];
  91503. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91504. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91505. if (newMesh.skeleton === null) {
  91506. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91507. if (!skin.babylonSkeleton) {
  91508. skin.babylonSkeleton = newMesh.skeleton;
  91509. }
  91510. }
  91511. lastNode = newMesh;
  91512. }
  91513. }
  91514. else if (node.meshes) {
  91515. /**
  91516. * Improve meshes property
  91517. */
  91518. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91519. lastNode = newMesh;
  91520. }
  91521. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91522. var light = gltfRuntime.lights[node.light];
  91523. if (light) {
  91524. if (light.type === "ambient") {
  91525. var ambienLight = light[light.type];
  91526. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91527. hemiLight.name = node.name || "";
  91528. if (ambienLight.color) {
  91529. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91530. }
  91531. lastNode = hemiLight;
  91532. }
  91533. else if (light.type === "directional") {
  91534. var directionalLight = light[light.type];
  91535. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91536. dirLight.name = node.name || "";
  91537. if (directionalLight.color) {
  91538. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91539. }
  91540. lastNode = dirLight;
  91541. }
  91542. else if (light.type === "point") {
  91543. var pointLight = light[light.type];
  91544. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91545. ptLight.name = node.name || "";
  91546. if (pointLight.color) {
  91547. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91548. }
  91549. lastNode = ptLight;
  91550. }
  91551. else if (light.type === "spot") {
  91552. var spotLight = light[light.type];
  91553. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91554. spLight.name = node.name || "";
  91555. if (spotLight.color) {
  91556. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91557. }
  91558. if (spotLight.fallOfAngle) {
  91559. spLight.angle = spotLight.fallOfAngle;
  91560. }
  91561. if (spotLight.fallOffExponent) {
  91562. spLight.exponent = spotLight.fallOffExponent;
  91563. }
  91564. lastNode = spLight;
  91565. }
  91566. }
  91567. }
  91568. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91569. var camera = gltfRuntime.cameras[node.camera];
  91570. if (camera) {
  91571. if (camera.type === "orthographic") {
  91572. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91573. orthoCamera.name = node.name || "";
  91574. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91575. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91576. lastNode = orthoCamera;
  91577. }
  91578. else if (camera.type === "perspective") {
  91579. var perspectiveCamera = camera[camera.type];
  91580. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91581. persCamera.name = node.name || "";
  91582. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91583. if (!perspectiveCamera.aspectRatio) {
  91584. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91585. }
  91586. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91587. persCamera.maxZ = perspectiveCamera.zfar;
  91588. persCamera.minZ = perspectiveCamera.znear;
  91589. }
  91590. lastNode = persCamera;
  91591. }
  91592. }
  91593. }
  91594. // Empty node
  91595. if (!node.jointName) {
  91596. if (node.babylonNode) {
  91597. return node.babylonNode;
  91598. }
  91599. else if (lastNode === null) {
  91600. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91601. node.babylonNode = dummy;
  91602. lastNode = dummy;
  91603. }
  91604. }
  91605. if (lastNode !== null) {
  91606. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91607. configureNodeFromMatrix(lastNode, node, parent);
  91608. }
  91609. else {
  91610. var translation = node.translation || [0, 0, 0];
  91611. var rotation = node.rotation || [0, 0, 0, 1];
  91612. var scale = node.scale || [1, 1, 1];
  91613. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91614. }
  91615. lastNode.updateCache(true);
  91616. node.babylonNode = lastNode;
  91617. }
  91618. return lastNode;
  91619. };
  91620. /**
  91621. * Traverses nodes and creates them
  91622. */
  91623. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91624. if (meshIncluded === void 0) { meshIncluded = false; }
  91625. var node = gltfRuntime.nodes[id];
  91626. var newNode = null;
  91627. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91628. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91629. meshIncluded = true;
  91630. }
  91631. else {
  91632. meshIncluded = false;
  91633. }
  91634. }
  91635. else {
  91636. meshIncluded = true;
  91637. }
  91638. if (!node.jointName && meshIncluded) {
  91639. newNode = importNode(gltfRuntime, node, id, parent);
  91640. if (newNode !== null) {
  91641. newNode.id = id;
  91642. newNode.parent = parent;
  91643. }
  91644. }
  91645. if (node.children) {
  91646. for (var i = 0; i < node.children.length; i++) {
  91647. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91648. }
  91649. }
  91650. };
  91651. /**
  91652. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91653. */
  91654. var postLoad = function (gltfRuntime) {
  91655. // Nodes
  91656. var currentScene = gltfRuntime.currentScene;
  91657. if (currentScene) {
  91658. for (var i = 0; i < currentScene.nodes.length; i++) {
  91659. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91660. }
  91661. }
  91662. else {
  91663. for (var thing in gltfRuntime.scenes) {
  91664. currentScene = gltfRuntime.scenes[thing];
  91665. for (var i = 0; i < currentScene.nodes.length; i++) {
  91666. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91667. }
  91668. }
  91669. }
  91670. // Set animations
  91671. loadAnimations(gltfRuntime);
  91672. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91673. var skeleton = gltfRuntime.scene.skeletons[i];
  91674. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91675. }
  91676. };
  91677. /**
  91678. * onBind shaderrs callback to set uniforms and matrices
  91679. */
  91680. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91681. var materialValues = material.values || technique.parameters;
  91682. for (var unif in unTreatedUniforms) {
  91683. var uniform = unTreatedUniforms[unif];
  91684. var type = uniform.type;
  91685. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91686. if (uniform.semantic && !uniform.source && !uniform.node) {
  91687. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91688. }
  91689. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91690. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91691. if (source === null) {
  91692. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91693. }
  91694. if (source === null) {
  91695. continue;
  91696. }
  91697. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91698. }
  91699. }
  91700. else {
  91701. var value = materialValues[technique.uniforms[unif]];
  91702. if (!value) {
  91703. continue;
  91704. }
  91705. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91706. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91707. if (texture === null || texture === undefined) {
  91708. continue;
  91709. }
  91710. shaderMaterial.getEffect().setTexture(unif, texture);
  91711. }
  91712. else {
  91713. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91714. }
  91715. }
  91716. }
  91717. onSuccess(shaderMaterial);
  91718. };
  91719. /**
  91720. * Prepare uniforms to send the only one time
  91721. * Loads the appropriate textures
  91722. */
  91723. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91724. var materialValues = material.values || technique.parameters;
  91725. var techniqueUniforms = technique.uniforms;
  91726. /**
  91727. * Prepare values here (not matrices)
  91728. */
  91729. for (var unif in unTreatedUniforms) {
  91730. var uniform = unTreatedUniforms[unif];
  91731. var type = uniform.type;
  91732. var value = materialValues[techniqueUniforms[unif]];
  91733. if (value === undefined) {
  91734. // In case the value is the same for all materials
  91735. value = uniform.value;
  91736. }
  91737. if (!value) {
  91738. continue;
  91739. }
  91740. var onLoadTexture = function (uniformName) {
  91741. return function (texture) {
  91742. if (uniform.value && uniformName) {
  91743. // Static uniform
  91744. shaderMaterial.setTexture(uniformName, texture);
  91745. delete unTreatedUniforms[uniformName];
  91746. }
  91747. };
  91748. };
  91749. // Texture (sampler2D)
  91750. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91751. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91752. }
  91753. else {
  91754. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91755. // Static uniform
  91756. delete unTreatedUniforms[unif];
  91757. }
  91758. }
  91759. }
  91760. };
  91761. /**
  91762. * Shader compilation failed
  91763. */
  91764. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91765. return function (effect, error) {
  91766. shaderMaterial.dispose(true);
  91767. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91768. };
  91769. };
  91770. /**
  91771. * Shader compilation success
  91772. */
  91773. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91774. return function (_) {
  91775. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91776. shaderMaterial.onBind = function (mesh) {
  91777. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91778. };
  91779. };
  91780. };
  91781. /**
  91782. * Returns the appropriate uniform if already handled by babylon
  91783. */
  91784. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91785. for (var unif in technique.uniforms) {
  91786. var uniform = technique.uniforms[unif];
  91787. var uniformParameter = technique.parameters[uniform];
  91788. if (tokenizer.currentIdentifier === unif) {
  91789. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91790. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91791. if (transformIndex !== -1) {
  91792. delete unTreatedUniforms[unif];
  91793. return babylonTransforms[transformIndex];
  91794. }
  91795. }
  91796. }
  91797. }
  91798. return tokenizer.currentIdentifier;
  91799. };
  91800. /**
  91801. * All shaders loaded. Create materials one by one
  91802. */
  91803. var importMaterials = function (gltfRuntime) {
  91804. // Create materials
  91805. for (var mat in gltfRuntime.materials) {
  91806. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91807. }
  91808. };
  91809. /**
  91810. * Implementation of the base glTF spec
  91811. */
  91812. var GLTFLoaderBase = /** @class */ (function () {
  91813. function GLTFLoaderBase() {
  91814. }
  91815. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91816. var gltfRuntime = {
  91817. extensions: {},
  91818. accessors: {},
  91819. buffers: {},
  91820. bufferViews: {},
  91821. meshes: {},
  91822. lights: {},
  91823. cameras: {},
  91824. nodes: {},
  91825. images: {},
  91826. textures: {},
  91827. shaders: {},
  91828. programs: {},
  91829. samplers: {},
  91830. techniques: {},
  91831. materials: {},
  91832. animations: {},
  91833. skins: {},
  91834. extensionsUsed: [],
  91835. scenes: {},
  91836. buffersCount: 0,
  91837. shaderscount: 0,
  91838. scene: scene,
  91839. rootUrl: rootUrl,
  91840. loadedBufferCount: 0,
  91841. loadedBufferViews: {},
  91842. loadedShaderCount: 0,
  91843. importOnlyMeshes: false,
  91844. dummyNodes: []
  91845. };
  91846. // Parse
  91847. if (parsedData.extensions) {
  91848. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91849. }
  91850. if (parsedData.extensionsUsed) {
  91851. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91852. }
  91853. if (parsedData.buffers) {
  91854. parseBuffers(parsedData.buffers, gltfRuntime);
  91855. }
  91856. if (parsedData.bufferViews) {
  91857. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91858. }
  91859. if (parsedData.accessors) {
  91860. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91861. }
  91862. if (parsedData.meshes) {
  91863. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91864. }
  91865. if (parsedData.lights) {
  91866. parseObject(parsedData.lights, "lights", gltfRuntime);
  91867. }
  91868. if (parsedData.cameras) {
  91869. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91870. }
  91871. if (parsedData.nodes) {
  91872. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91873. }
  91874. if (parsedData.images) {
  91875. parseObject(parsedData.images, "images", gltfRuntime);
  91876. }
  91877. if (parsedData.textures) {
  91878. parseObject(parsedData.textures, "textures", gltfRuntime);
  91879. }
  91880. if (parsedData.shaders) {
  91881. parseShaders(parsedData.shaders, gltfRuntime);
  91882. }
  91883. if (parsedData.programs) {
  91884. parseObject(parsedData.programs, "programs", gltfRuntime);
  91885. }
  91886. if (parsedData.samplers) {
  91887. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91888. }
  91889. if (parsedData.techniques) {
  91890. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91891. }
  91892. if (parsedData.materials) {
  91893. parseObject(parsedData.materials, "materials", gltfRuntime);
  91894. }
  91895. if (parsedData.animations) {
  91896. parseObject(parsedData.animations, "animations", gltfRuntime);
  91897. }
  91898. if (parsedData.skins) {
  91899. parseObject(parsedData.skins, "skins", gltfRuntime);
  91900. }
  91901. if (parsedData.scenes) {
  91902. gltfRuntime.scenes = parsedData.scenes;
  91903. }
  91904. if (parsedData.scene && parsedData.scenes) {
  91905. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91906. }
  91907. return gltfRuntime;
  91908. };
  91909. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91910. var buffer = gltfRuntime.buffers[id];
  91911. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91912. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91913. }
  91914. else {
  91915. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91916. if (request) {
  91917. onError(request.status + " " + request.statusText);
  91918. }
  91919. });
  91920. }
  91921. };
  91922. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91923. var texture = gltfRuntime.textures[id];
  91924. if (!texture || !texture.source) {
  91925. onError("");
  91926. return;
  91927. }
  91928. if (texture.babylonTexture) {
  91929. onSuccess(null);
  91930. return;
  91931. }
  91932. var source = gltfRuntime.images[texture.source];
  91933. if (BABYLON.Tools.IsBase64(source.uri)) {
  91934. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91935. }
  91936. else {
  91937. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91938. if (request) {
  91939. onError(request.status + " " + request.statusText);
  91940. }
  91941. });
  91942. }
  91943. };
  91944. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91945. var texture = gltfRuntime.textures[id];
  91946. if (texture.babylonTexture) {
  91947. onSuccess(texture.babylonTexture);
  91948. return;
  91949. }
  91950. var sampler = gltfRuntime.samplers[texture.sampler];
  91951. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91952. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91953. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91954. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91955. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91956. var blob = new Blob([buffer]);
  91957. var blobURL = URL.createObjectURL(blob);
  91958. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91959. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91960. if (sampler.wrapS !== undefined) {
  91961. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91962. }
  91963. if (sampler.wrapT !== undefined) {
  91964. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91965. }
  91966. newTexture.name = id;
  91967. texture.babylonTexture = newTexture;
  91968. onSuccess(newTexture);
  91969. };
  91970. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91971. var shader = gltfRuntime.shaders[id];
  91972. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91973. var shaderString = atob(shader.uri.split(",")[1]);
  91974. onSuccess(shaderString);
  91975. }
  91976. else {
  91977. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91978. if (request) {
  91979. onError(request.status + " " + request.statusText);
  91980. }
  91981. });
  91982. }
  91983. };
  91984. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91985. var material = gltfRuntime.materials[id];
  91986. if (!material.technique) {
  91987. if (onError) {
  91988. onError("No technique found.");
  91989. }
  91990. return;
  91991. }
  91992. var technique = gltfRuntime.techniques[material.technique];
  91993. if (!technique) {
  91994. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91995. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91996. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91997. onSuccess(defaultMaterial);
  91998. return;
  91999. }
  92000. var program = gltfRuntime.programs[technique.program];
  92001. var states = technique.states;
  92002. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  92003. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  92004. var newVertexShader = "";
  92005. var newPixelShader = "";
  92006. var vertexTokenizer = new Tokenizer(vertexShader);
  92007. var pixelTokenizer = new Tokenizer(pixelShader);
  92008. var unTreatedUniforms = {};
  92009. var uniforms = [];
  92010. var attributes = [];
  92011. var samplers = [];
  92012. // Fill uniform, sampler2D and attributes
  92013. for (var unif in technique.uniforms) {
  92014. var uniform = technique.uniforms[unif];
  92015. var uniformParameter = technique.parameters[uniform];
  92016. unTreatedUniforms[unif] = uniformParameter;
  92017. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  92018. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92019. if (transformIndex !== -1) {
  92020. uniforms.push(babylonTransforms[transformIndex]);
  92021. delete unTreatedUniforms[unif];
  92022. }
  92023. else {
  92024. uniforms.push(unif);
  92025. }
  92026. }
  92027. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  92028. samplers.push(unif);
  92029. }
  92030. else {
  92031. uniforms.push(unif);
  92032. }
  92033. }
  92034. for (var attr in technique.attributes) {
  92035. var attribute = technique.attributes[attr];
  92036. var attributeParameter = technique.parameters[attribute];
  92037. if (attributeParameter.semantic) {
  92038. attributes.push(getAttribute(attributeParameter));
  92039. }
  92040. }
  92041. // Configure vertex shader
  92042. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  92043. var tokenType = vertexTokenizer.currentToken;
  92044. if (tokenType !== ETokenType.IDENTIFIER) {
  92045. newVertexShader += vertexTokenizer.currentString;
  92046. continue;
  92047. }
  92048. var foundAttribute = false;
  92049. for (var attr in technique.attributes) {
  92050. var attribute = technique.attributes[attr];
  92051. var attributeParameter = technique.parameters[attribute];
  92052. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  92053. newVertexShader += getAttribute(attributeParameter);
  92054. foundAttribute = true;
  92055. break;
  92056. }
  92057. }
  92058. if (foundAttribute) {
  92059. continue;
  92060. }
  92061. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  92062. }
  92063. // Configure pixel shader
  92064. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  92065. var tokenType = pixelTokenizer.currentToken;
  92066. if (tokenType !== ETokenType.IDENTIFIER) {
  92067. newPixelShader += pixelTokenizer.currentString;
  92068. continue;
  92069. }
  92070. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  92071. }
  92072. // Create shader material
  92073. var shaderPath = {
  92074. vertex: program.vertexShader + id,
  92075. fragment: program.fragmentShader + id
  92076. };
  92077. var options = {
  92078. attributes: attributes,
  92079. uniforms: uniforms,
  92080. samplers: samplers,
  92081. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  92082. };
  92083. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  92084. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  92085. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  92086. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  92087. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  92088. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92089. if (states && states.functions) {
  92090. var functions = states.functions;
  92091. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  92092. shaderMaterial.backFaceCulling = false;
  92093. }
  92094. var blendFunc = functions.blendFuncSeparate;
  92095. if (blendFunc) {
  92096. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92097. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  92098. }
  92099. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92100. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92101. }
  92102. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92103. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  92104. }
  92105. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92106. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  92107. }
  92108. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92109. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  92110. }
  92111. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92112. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  92113. }
  92114. }
  92115. }
  92116. };
  92117. return GLTFLoaderBase;
  92118. }());
  92119. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  92120. /**
  92121. * glTF V1 Loader
  92122. */
  92123. var GLTFLoader = /** @class */ (function () {
  92124. function GLTFLoader() {
  92125. // #region Stubs for IGLTFLoader interface
  92126. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92127. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92128. this.compileMaterials = false;
  92129. this.useClipPlane = false;
  92130. this.compileShadowGenerators = false;
  92131. this.onDisposeObservable = new BABYLON.Observable();
  92132. this.onMeshLoadedObservable = new BABYLON.Observable();
  92133. this.onTextureLoadedObservable = new BABYLON.Observable();
  92134. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92135. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92136. this.onCompleteObservable = new BABYLON.Observable();
  92137. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92138. this.state = null;
  92139. }
  92140. GLTFLoader.RegisterExtension = function (extension) {
  92141. if (GLTFLoader.Extensions[extension.name]) {
  92142. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  92143. return;
  92144. }
  92145. GLTFLoader.Extensions[extension.name] = extension;
  92146. };
  92147. GLTFLoader.prototype.dispose = function () { };
  92148. // #endregion
  92149. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  92150. var _this = this;
  92151. scene.useRightHandedSystem = true;
  92152. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92153. gltfRuntime.importOnlyMeshes = true;
  92154. if (meshesNames === "") {
  92155. gltfRuntime.importMeshesNames = [];
  92156. }
  92157. else if (typeof meshesNames === "string") {
  92158. gltfRuntime.importMeshesNames = [meshesNames];
  92159. }
  92160. else if (meshesNames && !(meshesNames instanceof Array)) {
  92161. gltfRuntime.importMeshesNames = [meshesNames];
  92162. }
  92163. else {
  92164. gltfRuntime.importMeshesNames = [];
  92165. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  92166. }
  92167. // Create nodes
  92168. _this._createNodes(gltfRuntime);
  92169. var meshes = new Array();
  92170. var skeletons = new Array();
  92171. // Fill arrays of meshes and skeletons
  92172. for (var nde in gltfRuntime.nodes) {
  92173. var node = gltfRuntime.nodes[nde];
  92174. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  92175. meshes.push(node.babylonNode);
  92176. }
  92177. }
  92178. for (var skl in gltfRuntime.skins) {
  92179. var skin = gltfRuntime.skins[skl];
  92180. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  92181. skeletons.push(skin.babylonSkeleton);
  92182. }
  92183. }
  92184. // Load buffers, shaders, materials, etc.
  92185. _this._loadBuffersAsync(gltfRuntime, function () {
  92186. _this._loadShadersAsync(gltfRuntime, function () {
  92187. importMaterials(gltfRuntime);
  92188. postLoad(gltfRuntime);
  92189. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92190. onSuccess(meshes, [], skeletons);
  92191. }
  92192. });
  92193. }, onProgress);
  92194. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92195. onSuccess(meshes, [], skeletons);
  92196. }
  92197. }, onError);
  92198. return true;
  92199. };
  92200. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92201. var _this = this;
  92202. return new Promise(function (resolve, reject) {
  92203. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  92204. resolve({
  92205. meshes: meshes,
  92206. particleSystems: particleSystems,
  92207. skeletons: skeletons
  92208. });
  92209. }, onProgress, function (message) {
  92210. reject(new Error(message));
  92211. });
  92212. });
  92213. };
  92214. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  92215. var _this = this;
  92216. scene.useRightHandedSystem = true;
  92217. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92218. // Load runtime extensios
  92219. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  92220. // Create nodes
  92221. _this._createNodes(gltfRuntime);
  92222. // Load buffers, shaders, materials, etc.
  92223. _this._loadBuffersAsync(gltfRuntime, function () {
  92224. _this._loadShadersAsync(gltfRuntime, function () {
  92225. importMaterials(gltfRuntime);
  92226. postLoad(gltfRuntime);
  92227. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  92228. onSuccess();
  92229. }
  92230. });
  92231. });
  92232. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  92233. onSuccess();
  92234. }
  92235. }, onError);
  92236. }, onError);
  92237. };
  92238. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92239. var _this = this;
  92240. return new Promise(function (resolve, reject) {
  92241. _this._loadAsync(scene, data, rootUrl, function () {
  92242. resolve();
  92243. }, onProgress, function (message) {
  92244. reject(new Error(message));
  92245. });
  92246. });
  92247. };
  92248. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  92249. var hasShaders = false;
  92250. var processShader = function (sha, shader) {
  92251. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  92252. gltfRuntime.loadedShaderCount++;
  92253. if (shaderString) {
  92254. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  92255. }
  92256. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  92257. onload();
  92258. }
  92259. }, function () {
  92260. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  92261. });
  92262. };
  92263. for (var sha in gltfRuntime.shaders) {
  92264. hasShaders = true;
  92265. var shader = gltfRuntime.shaders[sha];
  92266. if (shader) {
  92267. processShader.bind(this, sha, shader)();
  92268. }
  92269. else {
  92270. BABYLON.Tools.Error("No shader named: " + sha);
  92271. }
  92272. }
  92273. if (!hasShaders) {
  92274. onload();
  92275. }
  92276. };
  92277. ;
  92278. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  92279. var hasBuffers = false;
  92280. var processBuffer = function (buf, buffer) {
  92281. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  92282. gltfRuntime.loadedBufferCount++;
  92283. if (bufferView) {
  92284. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  92285. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  92286. }
  92287. gltfRuntime.loadedBufferViews[buf] = bufferView;
  92288. }
  92289. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  92290. onLoad();
  92291. }
  92292. }, function () {
  92293. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  92294. });
  92295. };
  92296. for (var buf in gltfRuntime.buffers) {
  92297. hasBuffers = true;
  92298. var buffer = gltfRuntime.buffers[buf];
  92299. if (buffer) {
  92300. processBuffer.bind(this, buf, buffer)();
  92301. }
  92302. else {
  92303. BABYLON.Tools.Error("No buffer named: " + buf);
  92304. }
  92305. }
  92306. if (!hasBuffers) {
  92307. onLoad();
  92308. }
  92309. };
  92310. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  92311. var currentScene = gltfRuntime.currentScene;
  92312. if (currentScene) {
  92313. // Only one scene even if multiple scenes are defined
  92314. for (var i = 0; i < currentScene.nodes.length; i++) {
  92315. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92316. }
  92317. }
  92318. else {
  92319. // Load all scenes
  92320. for (var thing in gltfRuntime.scenes) {
  92321. currentScene = gltfRuntime.scenes[thing];
  92322. for (var i = 0; i < currentScene.nodes.length; i++) {
  92323. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92324. }
  92325. }
  92326. }
  92327. };
  92328. GLTFLoader.Extensions = {};
  92329. return GLTFLoader;
  92330. }());
  92331. GLTF1.GLTFLoader = GLTFLoader;
  92332. ;
  92333. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92334. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92335. })(BABYLON || (BABYLON = {}));
  92336. //# sourceMappingURL=babylon.glTFLoader.js.map
  92337. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92338. var BABYLON;
  92339. (function (BABYLON) {
  92340. var GLTF1;
  92341. (function (GLTF1) {
  92342. /**
  92343. * Utils functions for GLTF
  92344. */
  92345. var GLTFUtils = /** @class */ (function () {
  92346. function GLTFUtils() {
  92347. }
  92348. /**
  92349. * Sets the given "parameter" matrix
  92350. * @param scene: the {BABYLON.Scene} object
  92351. * @param source: the source node where to pick the matrix
  92352. * @param parameter: the GLTF technique parameter
  92353. * @param uniformName: the name of the shader's uniform
  92354. * @param shaderMaterial: the shader material
  92355. */
  92356. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92357. var mat = null;
  92358. if (parameter.semantic === "MODEL") {
  92359. mat = source.getWorldMatrix();
  92360. }
  92361. else if (parameter.semantic === "PROJECTION") {
  92362. mat = scene.getProjectionMatrix();
  92363. }
  92364. else if (parameter.semantic === "VIEW") {
  92365. mat = scene.getViewMatrix();
  92366. }
  92367. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92368. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92369. }
  92370. else if (parameter.semantic === "MODELVIEW") {
  92371. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92372. }
  92373. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92374. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92375. }
  92376. else if (parameter.semantic === "MODELINVERSE") {
  92377. mat = source.getWorldMatrix().invert();
  92378. }
  92379. else if (parameter.semantic === "VIEWINVERSE") {
  92380. mat = scene.getViewMatrix().invert();
  92381. }
  92382. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92383. mat = scene.getProjectionMatrix().invert();
  92384. }
  92385. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92386. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92387. }
  92388. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92389. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92390. }
  92391. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92392. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92393. }
  92394. else {
  92395. debugger;
  92396. }
  92397. if (mat) {
  92398. switch (parameter.type) {
  92399. case GLTF1.EParameterType.FLOAT_MAT2:
  92400. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92401. break;
  92402. case GLTF1.EParameterType.FLOAT_MAT3:
  92403. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92404. break;
  92405. case GLTF1.EParameterType.FLOAT_MAT4:
  92406. shaderMaterial.setMatrix(uniformName, mat);
  92407. break;
  92408. default: break;
  92409. }
  92410. }
  92411. };
  92412. /**
  92413. * Sets the given "parameter" matrix
  92414. * @param shaderMaterial: the shader material
  92415. * @param uniform: the name of the shader's uniform
  92416. * @param value: the value of the uniform
  92417. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92418. */
  92419. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92420. switch (type) {
  92421. case GLTF1.EParameterType.FLOAT:
  92422. shaderMaterial.setFloat(uniform, value);
  92423. return true;
  92424. case GLTF1.EParameterType.FLOAT_VEC2:
  92425. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92426. return true;
  92427. case GLTF1.EParameterType.FLOAT_VEC3:
  92428. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92429. return true;
  92430. case GLTF1.EParameterType.FLOAT_VEC4:
  92431. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92432. return true;
  92433. default: return false;
  92434. }
  92435. };
  92436. /**
  92437. * Returns the wrap mode of the texture
  92438. * @param mode: the mode value
  92439. */
  92440. GLTFUtils.GetWrapMode = function (mode) {
  92441. switch (mode) {
  92442. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92443. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92444. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92445. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92446. }
  92447. };
  92448. /**
  92449. * Returns the byte stride giving an accessor
  92450. * @param accessor: the GLTF accessor objet
  92451. */
  92452. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92453. // Needs this function since "byteStride" isn't requiered in glTF format
  92454. var type = accessor.type;
  92455. switch (type) {
  92456. case "VEC2": return 2;
  92457. case "VEC3": return 3;
  92458. case "VEC4": return 4;
  92459. case "MAT2": return 4;
  92460. case "MAT3": return 9;
  92461. case "MAT4": return 16;
  92462. default: return 1;
  92463. }
  92464. };
  92465. /**
  92466. * Returns the texture filter mode giving a mode value
  92467. * @param mode: the filter mode value
  92468. */
  92469. GLTFUtils.GetTextureFilterMode = function (mode) {
  92470. switch (mode) {
  92471. case GLTF1.ETextureFilterType.LINEAR:
  92472. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92473. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92474. case GLTF1.ETextureFilterType.NEAREST:
  92475. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92476. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92477. }
  92478. };
  92479. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92480. var byteOffset = bufferView.byteOffset + byteOffset;
  92481. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92482. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92483. throw new Error("Buffer access is out of range");
  92484. }
  92485. var buffer = loadedBufferView.buffer;
  92486. byteOffset += loadedBufferView.byteOffset;
  92487. switch (componentType) {
  92488. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92489. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92490. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92491. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92492. default: return new Float32Array(buffer, byteOffset, byteLength);
  92493. }
  92494. };
  92495. /**
  92496. * Returns a buffer from its accessor
  92497. * @param gltfRuntime: the GLTF runtime
  92498. * @param accessor: the GLTF accessor
  92499. */
  92500. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92501. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92502. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92503. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92504. };
  92505. /**
  92506. * Decodes a buffer view into a string
  92507. * @param view: the buffer view
  92508. */
  92509. GLTFUtils.DecodeBufferToText = function (view) {
  92510. var result = "";
  92511. var length = view.byteLength;
  92512. for (var i = 0; i < length; ++i) {
  92513. result += String.fromCharCode(view[i]);
  92514. }
  92515. return result;
  92516. };
  92517. /**
  92518. * Returns the default material of gltf. Related to
  92519. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92520. * @param scene: the Babylon.js scene
  92521. */
  92522. GLTFUtils.GetDefaultMaterial = function (scene) {
  92523. if (!GLTFUtils._DefaultMaterial) {
  92524. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92525. "precision highp float;",
  92526. "",
  92527. "uniform mat4 worldView;",
  92528. "uniform mat4 projection;",
  92529. "",
  92530. "attribute vec3 position;",
  92531. "",
  92532. "void main(void)",
  92533. "{",
  92534. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92535. "}"
  92536. ].join("\n");
  92537. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92538. "precision highp float;",
  92539. "",
  92540. "uniform vec4 u_emission;",
  92541. "",
  92542. "void main(void)",
  92543. "{",
  92544. " gl_FragColor = u_emission;",
  92545. "}"
  92546. ].join("\n");
  92547. var shaderPath = {
  92548. vertex: "GLTFDefaultMaterial",
  92549. fragment: "GLTFDefaultMaterial"
  92550. };
  92551. var options = {
  92552. attributes: ["position"],
  92553. uniforms: ["worldView", "projection", "u_emission"],
  92554. samplers: new Array(),
  92555. needAlphaBlending: false
  92556. };
  92557. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92558. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92559. }
  92560. return GLTFUtils._DefaultMaterial;
  92561. };
  92562. // The GLTF default material
  92563. GLTFUtils._DefaultMaterial = null;
  92564. return GLTFUtils;
  92565. }());
  92566. GLTF1.GLTFUtils = GLTFUtils;
  92567. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92568. })(BABYLON || (BABYLON = {}));
  92569. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92570. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92571. var BABYLON;
  92572. (function (BABYLON) {
  92573. var GLTF1;
  92574. (function (GLTF1) {
  92575. var GLTFLoaderExtension = /** @class */ (function () {
  92576. function GLTFLoaderExtension(name) {
  92577. this._name = name;
  92578. }
  92579. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92580. get: function () {
  92581. return this._name;
  92582. },
  92583. enumerable: true,
  92584. configurable: true
  92585. });
  92586. /**
  92587. * Defines an override for loading the runtime
  92588. * Return true to stop further extensions from loading the runtime
  92589. */
  92590. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92591. return false;
  92592. };
  92593. /**
  92594. * Defines an onverride for creating gltf runtime
  92595. * Return true to stop further extensions from creating the runtime
  92596. */
  92597. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92598. return false;
  92599. };
  92600. /**
  92601. * Defines an override for loading buffers
  92602. * Return true to stop further extensions from loading this buffer
  92603. */
  92604. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92605. return false;
  92606. };
  92607. /**
  92608. * Defines an override for loading texture buffers
  92609. * Return true to stop further extensions from loading this texture data
  92610. */
  92611. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92612. return false;
  92613. };
  92614. /**
  92615. * Defines an override for creating textures
  92616. * Return true to stop further extensions from loading this texture
  92617. */
  92618. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92619. return false;
  92620. };
  92621. /**
  92622. * Defines an override for loading shader strings
  92623. * Return true to stop further extensions from loading this shader data
  92624. */
  92625. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92626. return false;
  92627. };
  92628. /**
  92629. * Defines an override for loading materials
  92630. * Return true to stop further extensions from loading this material
  92631. */
  92632. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92633. return false;
  92634. };
  92635. // ---------
  92636. // Utilities
  92637. // ---------
  92638. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92639. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92640. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92641. }, function () {
  92642. setTimeout(function () {
  92643. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92644. });
  92645. });
  92646. };
  92647. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92648. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92649. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92650. }, function () {
  92651. setTimeout(function () {
  92652. onSuccess();
  92653. });
  92654. });
  92655. };
  92656. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92657. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92658. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92659. }, function () {
  92660. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92661. });
  92662. };
  92663. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92664. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92665. };
  92666. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92667. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92668. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92669. }, function () {
  92670. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92671. });
  92672. };
  92673. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92674. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92675. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92676. }, function () {
  92677. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92678. });
  92679. };
  92680. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92681. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92682. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92683. }, function () {
  92684. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92685. });
  92686. };
  92687. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92688. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92689. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92690. }, function () {
  92691. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92692. });
  92693. };
  92694. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92695. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92696. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92697. if (func(loaderExtension)) {
  92698. return;
  92699. }
  92700. }
  92701. defaultFunc();
  92702. };
  92703. return GLTFLoaderExtension;
  92704. }());
  92705. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92706. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92707. })(BABYLON || (BABYLON = {}));
  92708. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92709. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92710. var BABYLON;
  92711. (function (BABYLON) {
  92712. var GLTF1;
  92713. (function (GLTF1) {
  92714. var BinaryExtensionBufferName = "binary_glTF";
  92715. ;
  92716. ;
  92717. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92718. __extends(GLTFBinaryExtension, _super);
  92719. function GLTFBinaryExtension() {
  92720. return _super.call(this, "KHR_binary_glTF") || this;
  92721. }
  92722. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92723. var extensionsUsed = data.json.extensionsUsed;
  92724. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92725. return false;
  92726. }
  92727. this._bin = data.bin;
  92728. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92729. return true;
  92730. };
  92731. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92732. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92733. return false;
  92734. }
  92735. if (id !== BinaryExtensionBufferName) {
  92736. return false;
  92737. }
  92738. onSuccess(this._bin);
  92739. return true;
  92740. };
  92741. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92742. var texture = gltfRuntime.textures[id];
  92743. var source = gltfRuntime.images[texture.source];
  92744. if (!source.extensions || !(this.name in source.extensions)) {
  92745. return false;
  92746. }
  92747. var sourceExt = source.extensions[this.name];
  92748. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92749. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92750. onSuccess(buffer);
  92751. return true;
  92752. };
  92753. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92754. var shader = gltfRuntime.shaders[id];
  92755. if (!shader.extensions || !(this.name in shader.extensions)) {
  92756. return false;
  92757. }
  92758. var binaryExtensionShader = shader.extensions[this.name];
  92759. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92760. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92761. setTimeout(function () {
  92762. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92763. onSuccess(shaderString);
  92764. });
  92765. return true;
  92766. };
  92767. return GLTFBinaryExtension;
  92768. }(GLTF1.GLTFLoaderExtension));
  92769. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92770. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92771. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92772. })(BABYLON || (BABYLON = {}));
  92773. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92774. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92775. var BABYLON;
  92776. (function (BABYLON) {
  92777. var GLTF1;
  92778. (function (GLTF1) {
  92779. ;
  92780. ;
  92781. ;
  92782. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92783. __extends(GLTFMaterialsCommonExtension, _super);
  92784. function GLTFMaterialsCommonExtension() {
  92785. return _super.call(this, "KHR_materials_common") || this;
  92786. }
  92787. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92788. if (!gltfRuntime.extensions)
  92789. return false;
  92790. var extension = gltfRuntime.extensions[this.name];
  92791. if (!extension)
  92792. return false;
  92793. // Create lights
  92794. var lights = extension.lights;
  92795. if (lights) {
  92796. for (var thing in lights) {
  92797. var light = lights[thing];
  92798. switch (light.type) {
  92799. case "ambient":
  92800. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92801. var ambient = light.ambient;
  92802. if (ambient) {
  92803. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92804. }
  92805. break;
  92806. case "point":
  92807. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92808. var point = light.point;
  92809. if (point) {
  92810. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92811. }
  92812. break;
  92813. case "directional":
  92814. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92815. var directional = light.directional;
  92816. if (directional) {
  92817. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92818. }
  92819. break;
  92820. case "spot":
  92821. var spot = light.spot;
  92822. if (spot) {
  92823. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  92824. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92825. }
  92826. break;
  92827. default:
  92828. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92829. break;
  92830. }
  92831. }
  92832. }
  92833. return false;
  92834. };
  92835. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92836. var material = gltfRuntime.materials[id];
  92837. if (!material || !material.extensions)
  92838. return false;
  92839. var extension = material.extensions[this.name];
  92840. if (!extension)
  92841. return false;
  92842. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92843. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92844. if (extension.technique === "CONSTANT") {
  92845. standardMaterial.disableLighting = true;
  92846. }
  92847. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92848. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92849. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92850. // Ambient
  92851. if (typeof extension.values.ambient === "string") {
  92852. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92853. }
  92854. else {
  92855. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92856. }
  92857. // Diffuse
  92858. if (typeof extension.values.diffuse === "string") {
  92859. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92860. }
  92861. else {
  92862. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92863. }
  92864. // Emission
  92865. if (typeof extension.values.emission === "string") {
  92866. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92867. }
  92868. else {
  92869. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92870. }
  92871. // Specular
  92872. if (typeof extension.values.specular === "string") {
  92873. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92874. }
  92875. else {
  92876. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92877. }
  92878. return true;
  92879. };
  92880. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92881. // Create buffer from texture url
  92882. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92883. // Create texture from buffer
  92884. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92885. }, onError);
  92886. };
  92887. return GLTFMaterialsCommonExtension;
  92888. }(GLTF1.GLTFLoaderExtension));
  92889. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92890. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92891. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92892. })(BABYLON || (BABYLON = {}));
  92893. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92894. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92895. var BABYLON;
  92896. (function (BABYLON) {
  92897. var GLTF2;
  92898. (function (GLTF2) {
  92899. var ArrayItem = /** @class */ (function () {
  92900. function ArrayItem() {
  92901. }
  92902. ArrayItem.Assign = function (values) {
  92903. if (values) {
  92904. for (var index = 0; index < values.length; index++) {
  92905. values[index]._index = index;
  92906. }
  92907. }
  92908. };
  92909. return ArrayItem;
  92910. }());
  92911. GLTF2.ArrayItem = ArrayItem;
  92912. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92913. })(BABYLON || (BABYLON = {}));
  92914. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92915. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92916. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92917. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92918. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92919. var BABYLON;
  92920. (function (BABYLON) {
  92921. var GLTF2;
  92922. (function (GLTF2) {
  92923. var GLTFLoader = /** @class */ (function () {
  92924. function GLTFLoader() {
  92925. this._completePromises = new Array();
  92926. this._disposed = false;
  92927. this._state = null;
  92928. this._extensions = {};
  92929. this._defaultSampler = {};
  92930. this._requests = new Array();
  92931. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92932. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92933. this.compileMaterials = false;
  92934. this.useClipPlane = false;
  92935. this.compileShadowGenerators = false;
  92936. this.onDisposeObservable = new BABYLON.Observable();
  92937. this.onMeshLoadedObservable = new BABYLON.Observable();
  92938. this.onTextureLoadedObservable = new BABYLON.Observable();
  92939. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92940. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92941. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92942. this.onCompleteObservable = new BABYLON.Observable();
  92943. }
  92944. GLTFLoader._Register = function (name, factory) {
  92945. if (GLTFLoader._Factories[name]) {
  92946. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92947. return;
  92948. }
  92949. GLTFLoader._Factories[name] = factory;
  92950. // Keep the order of registration so that extensions registered first are called first.
  92951. GLTFLoader._Names.push(name);
  92952. };
  92953. Object.defineProperty(GLTFLoader.prototype, "state", {
  92954. get: function () {
  92955. return this._state;
  92956. },
  92957. enumerable: true,
  92958. configurable: true
  92959. });
  92960. GLTFLoader.prototype.dispose = function () {
  92961. if (this._disposed) {
  92962. return;
  92963. }
  92964. this._disposed = true;
  92965. this.onDisposeObservable.notifyObservers(this);
  92966. this.onDisposeObservable.clear();
  92967. this._clear();
  92968. };
  92969. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92970. var _this = this;
  92971. return Promise.resolve().then(function () {
  92972. var nodes = null;
  92973. if (meshesNames) {
  92974. var nodeMap_1 = {};
  92975. if (_this._gltf.nodes) {
  92976. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92977. var node = _a[_i];
  92978. if (node.name) {
  92979. nodeMap_1[node.name] = node;
  92980. }
  92981. }
  92982. }
  92983. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92984. nodes = names.map(function (name) {
  92985. var node = nodeMap_1[name];
  92986. if (!node) {
  92987. throw new Error("Failed to find node '" + name + "'");
  92988. }
  92989. return node;
  92990. });
  92991. }
  92992. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92993. return {
  92994. meshes: _this._getMeshes(),
  92995. particleSystems: [],
  92996. skeletons: _this._getSkeletons(),
  92997. };
  92998. });
  92999. });
  93000. };
  93001. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93002. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  93003. };
  93004. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  93005. var _this = this;
  93006. return Promise.resolve().then(function () {
  93007. _this._loadExtensions();
  93008. _this._babylonScene = scene;
  93009. _this._rootUrl = rootUrl;
  93010. _this._progressCallback = onProgress;
  93011. _this._state = BABYLON.GLTFLoaderState.Loading;
  93012. _this._loadData(data);
  93013. _this._checkExtensions();
  93014. var promises = new Array();
  93015. if (nodes) {
  93016. promises.push(_this._loadNodesAsync(nodes));
  93017. }
  93018. else {
  93019. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  93020. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  93021. }
  93022. if (_this.compileMaterials) {
  93023. promises.push(_this._compileMaterialsAsync());
  93024. }
  93025. if (_this.compileShadowGenerators) {
  93026. promises.push(_this._compileShadowGeneratorsAsync());
  93027. }
  93028. var resultPromise = Promise.all(promises).then(function () {
  93029. _this._state = BABYLON.GLTFLoaderState.Ready;
  93030. _this._startAnimations();
  93031. });
  93032. resultPromise.then(function () {
  93033. _this._rootBabylonMesh.setEnabled(true);
  93034. BABYLON.Tools.SetImmediate(function () {
  93035. if (!_this._disposed) {
  93036. Promise.all(_this._completePromises).then(function () {
  93037. _this._state = BABYLON.GLTFLoaderState.Complete;
  93038. _this.onCompleteObservable.notifyObservers(_this);
  93039. _this.onCompleteObservable.clear();
  93040. _this._clear();
  93041. }).catch(function (error) {
  93042. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93043. _this._clear();
  93044. });
  93045. }
  93046. });
  93047. });
  93048. return resultPromise;
  93049. }).catch(function (error) {
  93050. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93051. _this._clear();
  93052. throw error;
  93053. });
  93054. };
  93055. GLTFLoader.prototype._loadExtensions = function () {
  93056. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93057. var name_1 = _a[_i];
  93058. var extension = GLTFLoader._Factories[name_1](this);
  93059. this._extensions[name_1] = extension;
  93060. this.onExtensionLoadedObservable.notifyObservers(extension);
  93061. }
  93062. this.onExtensionLoadedObservable.clear();
  93063. };
  93064. GLTFLoader.prototype._loadData = function (data) {
  93065. this._gltf = data.json;
  93066. this._setupData();
  93067. if (data.bin) {
  93068. var buffers = this._gltf.buffers;
  93069. if (buffers && buffers[0] && !buffers[0].uri) {
  93070. var binaryBuffer = buffers[0];
  93071. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  93072. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  93073. }
  93074. binaryBuffer._data = Promise.resolve(data.bin);
  93075. }
  93076. else {
  93077. BABYLON.Tools.Warn("Unexpected BIN chunk");
  93078. }
  93079. }
  93080. };
  93081. GLTFLoader.prototype._setupData = function () {
  93082. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  93083. GLTF2.ArrayItem.Assign(this._gltf.animations);
  93084. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  93085. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  93086. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  93087. GLTF2.ArrayItem.Assign(this._gltf.images);
  93088. GLTF2.ArrayItem.Assign(this._gltf.materials);
  93089. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  93090. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  93091. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  93092. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  93093. GLTF2.ArrayItem.Assign(this._gltf.skins);
  93094. GLTF2.ArrayItem.Assign(this._gltf.textures);
  93095. if (this._gltf.nodes) {
  93096. var nodeParents = {};
  93097. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  93098. var node = _a[_i];
  93099. if (node.children) {
  93100. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  93101. var index = _c[_b];
  93102. nodeParents[index] = node._index;
  93103. }
  93104. }
  93105. }
  93106. var rootNode = this._createRootNode();
  93107. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  93108. var node = _e[_d];
  93109. var parentIndex = nodeParents[node._index];
  93110. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  93111. }
  93112. }
  93113. };
  93114. GLTFLoader.prototype._checkExtensions = function () {
  93115. if (this._gltf.extensionsRequired) {
  93116. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  93117. var name_2 = _a[_i];
  93118. var extension = this._extensions[name_2];
  93119. if (!extension || !extension.enabled) {
  93120. throw new Error("Require extension " + name_2 + " is not available");
  93121. }
  93122. }
  93123. }
  93124. };
  93125. GLTFLoader.prototype._createRootNode = function () {
  93126. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  93127. this._rootBabylonMesh.setEnabled(false);
  93128. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  93129. switch (this.coordinateSystemMode) {
  93130. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  93131. if (!this._babylonScene.useRightHandedSystem) {
  93132. rootNode.rotation = [0, 1, 0, 0];
  93133. rootNode.scale = [1, 1, -1];
  93134. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  93135. }
  93136. break;
  93137. }
  93138. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  93139. this._babylonScene.useRightHandedSystem = true;
  93140. break;
  93141. }
  93142. default: {
  93143. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  93144. }
  93145. }
  93146. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  93147. return rootNode;
  93148. };
  93149. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  93150. var promises = new Array();
  93151. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  93152. var node = nodes_1[_i];
  93153. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93154. }
  93155. promises.push(this._loadAnimationsAsync());
  93156. return Promise.all(promises).then(function () { });
  93157. };
  93158. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  93159. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  93160. if (promise) {
  93161. return promise;
  93162. }
  93163. var promises = new Array();
  93164. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  93165. var index = _a[_i];
  93166. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  93167. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93168. }
  93169. promises.push(this._loadAnimationsAsync());
  93170. return Promise.all(promises).then(function () { });
  93171. };
  93172. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  93173. if (node._babylonMesh) {
  93174. callback(node._babylonMesh);
  93175. }
  93176. if (node._primitiveBabylonMeshes) {
  93177. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93178. var babylonMesh = _a[_i];
  93179. callback(babylonMesh);
  93180. }
  93181. }
  93182. };
  93183. GLTFLoader.prototype._getMeshes = function () {
  93184. var meshes = new Array();
  93185. // Root mesh is always first.
  93186. meshes.push(this._rootBabylonMesh);
  93187. var nodes = this._gltf.nodes;
  93188. if (nodes) {
  93189. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  93190. var node = nodes_2[_i];
  93191. this._forEachNodeMesh(node, function (mesh) {
  93192. meshes.push(mesh);
  93193. });
  93194. }
  93195. }
  93196. return meshes;
  93197. };
  93198. GLTFLoader.prototype._getSkeletons = function () {
  93199. var skeletons = new Array();
  93200. var skins = this._gltf.skins;
  93201. if (skins) {
  93202. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  93203. var skin = skins_1[_i];
  93204. if (skin._babylonSkeleton) {
  93205. skeletons.push(skin._babylonSkeleton);
  93206. }
  93207. }
  93208. }
  93209. return skeletons;
  93210. };
  93211. GLTFLoader.prototype._startAnimations = function () {
  93212. var animations = this._gltf.animations;
  93213. if (!animations) {
  93214. return;
  93215. }
  93216. switch (this.animationStartMode) {
  93217. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  93218. // do nothing
  93219. break;
  93220. }
  93221. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  93222. var animation = animations[0];
  93223. animation._babylonAnimationGroup.start(true);
  93224. break;
  93225. }
  93226. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  93227. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  93228. var animation = animations_1[_i];
  93229. animation._babylonAnimationGroup.start(true);
  93230. }
  93231. break;
  93232. }
  93233. default: {
  93234. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  93235. return;
  93236. }
  93237. }
  93238. };
  93239. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  93240. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  93241. if (promise) {
  93242. return promise;
  93243. }
  93244. if (node._babylonMesh) {
  93245. throw new Error(context + ": Invalid recursive node hierarchy");
  93246. }
  93247. var promises = new Array();
  93248. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  93249. node._babylonMesh = babylonMesh;
  93250. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93251. node._babylonAnimationTargets.push(babylonMesh);
  93252. GLTFLoader._LoadTransform(node, babylonMesh);
  93253. if (node.mesh != undefined) {
  93254. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  93255. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  93256. }
  93257. if (node.children) {
  93258. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  93259. var index = _a[_i];
  93260. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  93261. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  93262. }
  93263. }
  93264. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93265. return Promise.all(promises).then(function () { });
  93266. };
  93267. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  93268. // TODO: instancing
  93269. var _this = this;
  93270. var promises = new Array();
  93271. var primitives = mesh.primitives;
  93272. if (!primitives || primitives.length === 0) {
  93273. throw new Error(context + ": Primitives are missing");
  93274. }
  93275. GLTF2.ArrayItem.Assign(primitives);
  93276. if (primitives.length === 1) {
  93277. var primitive = primitives[0];
  93278. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  93279. }
  93280. else {
  93281. node._primitiveBabylonMeshes = [];
  93282. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  93283. var primitive = primitives_1[_i];
  93284. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  93285. node._primitiveBabylonMeshes.push(babylonMesh);
  93286. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  93287. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93288. }
  93289. }
  93290. if (node.skin != undefined) {
  93291. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  93292. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  93293. }
  93294. return Promise.all(promises).then(function () {
  93295. _this._forEachNodeMesh(node, function (babylonMesh) {
  93296. babylonMesh._refreshBoundingInfo(true);
  93297. });
  93298. });
  93299. };
  93300. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  93301. var _this = this;
  93302. var promises = new Array();
  93303. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  93304. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  93305. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  93306. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  93307. }));
  93308. if (primitive.material == undefined) {
  93309. babylonMesh.material = this._getDefaultMaterial();
  93310. }
  93311. else {
  93312. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  93313. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  93314. babylonMesh.material = babylonMaterial;
  93315. }));
  93316. }
  93317. return Promise.all(promises).then(function () { });
  93318. };
  93319. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93320. var _this = this;
  93321. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  93322. if (promise) {
  93323. return promise;
  93324. }
  93325. var attributes = primitive.attributes;
  93326. if (!attributes) {
  93327. throw new Error(context + ": Attributes are missing");
  93328. }
  93329. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93330. // TODO: handle other primitive modes
  93331. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93332. }
  93333. var promises = new Array();
  93334. var babylonVertexData = new BABYLON.VertexData();
  93335. if (primitive.indices == undefined) {
  93336. var positionAccessorIndex = attributes["POSITION"];
  93337. if (positionAccessorIndex != undefined) {
  93338. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93339. babylonVertexData.indices = new Uint32Array(accessor.count);
  93340. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93341. babylonVertexData.indices[i] = i;
  93342. }
  93343. }
  93344. }
  93345. else {
  93346. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93347. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93348. babylonVertexData.indices = data;
  93349. }));
  93350. }
  93351. var loadAttribute = function (attribute, kind) {
  93352. if (attributes[attribute] == undefined) {
  93353. return;
  93354. }
  93355. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93356. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93357. babylonMesh._delayInfo.push(kind);
  93358. }
  93359. if (attribute === "COLOR_0") {
  93360. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93361. babylonMesh.hasVertexAlpha = true;
  93362. }
  93363. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93364. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93365. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93366. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  93367. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93368. }
  93369. babylonVertexData.set(attributeData, kind);
  93370. }));
  93371. };
  93372. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93373. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93374. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93375. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93376. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93377. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93378. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93379. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93380. return Promise.all(promises).then(function () {
  93381. return babylonVertexData;
  93382. });
  93383. };
  93384. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93385. if (!primitive.targets) {
  93386. return;
  93387. }
  93388. if (node._numMorphTargets == undefined) {
  93389. node._numMorphTargets = primitive.targets.length;
  93390. }
  93391. else if (primitive.targets.length !== node._numMorphTargets) {
  93392. throw new Error(context + ": Primitives do not have the same number of targets");
  93393. }
  93394. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93395. for (var index = 0; index < primitive.targets.length; index++) {
  93396. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93397. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93398. // TODO: tell the target whether it has positions, normals, tangents
  93399. }
  93400. };
  93401. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93402. if (!primitive.targets) {
  93403. return Promise.resolve();
  93404. }
  93405. var promises = new Array();
  93406. var morphTargetManager = babylonMesh.morphTargetManager;
  93407. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93408. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93409. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93410. }
  93411. return Promise.all(promises).then(function () { });
  93412. };
  93413. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93414. var _this = this;
  93415. var promises = new Array();
  93416. var loadAttribute = function (attribute, setData) {
  93417. if (attributes[attribute] == undefined) {
  93418. return;
  93419. }
  93420. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93421. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93422. setData(data);
  93423. }));
  93424. };
  93425. loadAttribute("POSITION", function (data) {
  93426. if (babylonVertexData.positions) {
  93427. for (var i = 0; i < data.length; i++) {
  93428. data[i] += babylonVertexData.positions[i];
  93429. }
  93430. babylonMorphTarget.setPositions(data);
  93431. }
  93432. });
  93433. loadAttribute("NORMAL", function (data) {
  93434. if (babylonVertexData.normals) {
  93435. for (var i = 0; i < data.length; i++) {
  93436. data[i] += babylonVertexData.normals[i];
  93437. }
  93438. babylonMorphTarget.setNormals(data);
  93439. }
  93440. });
  93441. loadAttribute("TANGENT", function (data) {
  93442. if (babylonVertexData.tangents) {
  93443. // Tangent data for morph targets is stored as xyz delta.
  93444. // The vertexData.tangent is stored as xyzw.
  93445. // So we need to skip every fourth vertexData.tangent.
  93446. for (var i = 0, j = 0; i < data.length; i++) {
  93447. data[i] += babylonVertexData.tangents[j++];
  93448. if ((i + 1) % 3 == 0) {
  93449. j++;
  93450. }
  93451. }
  93452. babylonMorphTarget.setTangents(data);
  93453. }
  93454. });
  93455. return Promise.all(promises).then(function () { });
  93456. };
  93457. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93458. if (accessor.componentType == 5126 /* FLOAT */) {
  93459. return data;
  93460. }
  93461. var factor = 1;
  93462. if (accessor.normalized) {
  93463. switch (accessor.componentType) {
  93464. case 5121 /* UNSIGNED_BYTE */: {
  93465. factor = 1 / 255;
  93466. break;
  93467. }
  93468. case 5123 /* UNSIGNED_SHORT */: {
  93469. factor = 1 / 65535;
  93470. break;
  93471. }
  93472. default: {
  93473. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93474. }
  93475. }
  93476. }
  93477. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93478. for (var i = 0; i < result.length; i++) {
  93479. result[i] = data[i] * factor;
  93480. }
  93481. return result;
  93482. };
  93483. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93484. var result = new Float32Array(data.length / 3 * 4);
  93485. var offset = 0;
  93486. for (var i = 0; i < result.length; i++) {
  93487. if ((i + 1) % 4 === 0) {
  93488. result[i] = 1;
  93489. }
  93490. else {
  93491. result[i] = data[offset++];
  93492. }
  93493. }
  93494. return result;
  93495. };
  93496. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93497. var position = BABYLON.Vector3.Zero();
  93498. var rotation = BABYLON.Quaternion.Identity();
  93499. var scaling = BABYLON.Vector3.One();
  93500. if (node.matrix) {
  93501. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93502. matrix.decompose(scaling, rotation, position);
  93503. }
  93504. else {
  93505. if (node.translation)
  93506. position = BABYLON.Vector3.FromArray(node.translation);
  93507. if (node.rotation)
  93508. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93509. if (node.scale)
  93510. scaling = BABYLON.Vector3.FromArray(node.scale);
  93511. }
  93512. babylonNode.position = position;
  93513. babylonNode.rotationQuaternion = rotation;
  93514. babylonNode.scaling = scaling;
  93515. };
  93516. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93517. var _this = this;
  93518. var assignSkeleton = function () {
  93519. _this._forEachNodeMesh(node, function (babylonMesh) {
  93520. babylonMesh.skeleton = skin._babylonSkeleton;
  93521. });
  93522. node._babylonMesh.parent = _this._rootBabylonMesh;
  93523. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93524. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93525. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93526. };
  93527. if (skin._loaded) {
  93528. return skin._loaded.then(function () {
  93529. assignSkeleton();
  93530. });
  93531. }
  93532. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93533. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93534. var skeletonId = "skeleton" + skin._index;
  93535. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93536. skin._babylonSkeleton = babylonSkeleton;
  93537. _this._loadBones(context, skin, inverseBindMatricesData);
  93538. assignSkeleton();
  93539. }));
  93540. };
  93541. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93542. if (skin.inverseBindMatrices == undefined) {
  93543. return Promise.resolve(null);
  93544. }
  93545. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93546. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93547. return data;
  93548. });
  93549. };
  93550. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93551. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93552. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93553. node._babylonAnimationTargets.push(babylonBone);
  93554. return babylonBone;
  93555. };
  93556. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93557. var babylonBones = {};
  93558. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93559. var index = _a[_i];
  93560. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93561. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93562. }
  93563. };
  93564. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93565. var babylonBone = babylonBones[node._index];
  93566. if (babylonBone) {
  93567. return babylonBone;
  93568. }
  93569. var boneIndex = skin.joints.indexOf(node._index);
  93570. var baseMatrix = BABYLON.Matrix.Identity();
  93571. if (inverseBindMatricesData && boneIndex !== -1) {
  93572. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93573. baseMatrix.invertToRef(baseMatrix);
  93574. }
  93575. var babylonParentBone = null;
  93576. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93577. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93578. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93579. }
  93580. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93581. babylonBones[node._index] = babylonBone;
  93582. return babylonBone;
  93583. };
  93584. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93585. return node.matrix ?
  93586. BABYLON.Matrix.FromArray(node.matrix) :
  93587. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  93588. };
  93589. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93590. var animations = this._gltf.animations;
  93591. if (!animations) {
  93592. return Promise.resolve();
  93593. }
  93594. var promises = new Array();
  93595. for (var index = 0; index < animations.length; index++) {
  93596. var animation = animations[index];
  93597. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93598. }
  93599. return Promise.all(promises).then(function () { });
  93600. };
  93601. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93602. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93603. animation._babylonAnimationGroup = babylonAnimationGroup;
  93604. var promises = new Array();
  93605. GLTF2.ArrayItem.Assign(animation.channels);
  93606. GLTF2.ArrayItem.Assign(animation.samplers);
  93607. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93608. var channel = _a[_i];
  93609. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93610. }
  93611. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93612. return Promise.all(promises).then(function () {
  93613. babylonAnimationGroup.normalize();
  93614. });
  93615. };
  93616. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93617. var _this = this;
  93618. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93619. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93620. return Promise.resolve();
  93621. }
  93622. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93623. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93624. var targetPath;
  93625. var animationType;
  93626. switch (channel.target.path) {
  93627. case "translation" /* TRANSLATION */: {
  93628. targetPath = "position";
  93629. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93630. break;
  93631. }
  93632. case "rotation" /* ROTATION */: {
  93633. targetPath = "rotationQuaternion";
  93634. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93635. break;
  93636. }
  93637. case "scale" /* SCALE */: {
  93638. targetPath = "scaling";
  93639. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93640. break;
  93641. }
  93642. case "weights" /* WEIGHTS */: {
  93643. targetPath = "influence";
  93644. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93645. break;
  93646. }
  93647. default: {
  93648. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93649. }
  93650. }
  93651. var outputBufferOffset = 0;
  93652. var getNextOutputValue;
  93653. switch (targetPath) {
  93654. case "position": {
  93655. getNextOutputValue = function () {
  93656. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93657. outputBufferOffset += 3;
  93658. return value;
  93659. };
  93660. break;
  93661. }
  93662. case "rotationQuaternion": {
  93663. getNextOutputValue = function () {
  93664. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93665. outputBufferOffset += 4;
  93666. return value;
  93667. };
  93668. break;
  93669. }
  93670. case "scaling": {
  93671. getNextOutputValue = function () {
  93672. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93673. outputBufferOffset += 3;
  93674. return value;
  93675. };
  93676. break;
  93677. }
  93678. case "influence": {
  93679. getNextOutputValue = function () {
  93680. var value = new Array(targetNode._numMorphTargets);
  93681. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93682. value[i] = data.output[outputBufferOffset++];
  93683. }
  93684. return value;
  93685. };
  93686. break;
  93687. }
  93688. }
  93689. var getNextKey;
  93690. switch (data.interpolation) {
  93691. case "STEP" /* STEP */: {
  93692. getNextKey = function (frameIndex) { return ({
  93693. frame: data.input[frameIndex],
  93694. value: getNextOutputValue(),
  93695. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93696. }); };
  93697. break;
  93698. }
  93699. case "LINEAR" /* LINEAR */: {
  93700. getNextKey = function (frameIndex) { return ({
  93701. frame: data.input[frameIndex],
  93702. value: getNextOutputValue()
  93703. }); };
  93704. break;
  93705. }
  93706. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93707. getNextKey = function (frameIndex) { return ({
  93708. frame: data.input[frameIndex],
  93709. inTangent: getNextOutputValue(),
  93710. value: getNextOutputValue(),
  93711. outTangent: getNextOutputValue()
  93712. }); };
  93713. break;
  93714. }
  93715. }
  93716. var keys;
  93717. if (data.input.length === 1) {
  93718. var key = getNextKey(0);
  93719. keys = [
  93720. { frame: key.frame, value: key.value },
  93721. { frame: key.frame + 1, value: key.value }
  93722. ];
  93723. }
  93724. else {
  93725. keys = new Array(data.input.length);
  93726. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93727. keys[frameIndex] = getNextKey(frameIndex);
  93728. }
  93729. }
  93730. if (targetPath === "influence") {
  93731. var _loop_1 = function (targetIndex) {
  93732. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93733. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93734. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93735. frame: key.frame,
  93736. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93737. value: key.value[targetIndex],
  93738. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93739. }); }));
  93740. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93741. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93742. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93743. });
  93744. };
  93745. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93746. _loop_1(targetIndex);
  93747. }
  93748. }
  93749. else {
  93750. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93751. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93752. babylonAnimation.setKeys(keys);
  93753. if (targetNode._babylonAnimationTargets) {
  93754. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93755. var target = _a[_i];
  93756. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93757. }
  93758. }
  93759. }
  93760. });
  93761. };
  93762. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93763. if (sampler._data) {
  93764. return sampler._data;
  93765. }
  93766. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93767. switch (interpolation) {
  93768. case "STEP" /* STEP */:
  93769. case "LINEAR" /* LINEAR */:
  93770. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93771. break;
  93772. }
  93773. default: {
  93774. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93775. }
  93776. }
  93777. var inputData;
  93778. var outputData;
  93779. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93780. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93781. sampler._data = Promise.all([
  93782. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93783. inputData = data;
  93784. }),
  93785. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93786. outputData = data;
  93787. })
  93788. ]).then(function () {
  93789. return {
  93790. input: inputData,
  93791. interpolation: interpolation,
  93792. output: outputData,
  93793. };
  93794. });
  93795. return sampler._data;
  93796. };
  93797. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93798. if (buffer._data) {
  93799. return buffer._data;
  93800. }
  93801. if (!buffer.uri) {
  93802. throw new Error(context + ": Uri is missing");
  93803. }
  93804. buffer._data = this._loadUriAsync(context, buffer.uri);
  93805. return buffer._data;
  93806. };
  93807. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93808. if (bufferView._data) {
  93809. return bufferView._data;
  93810. }
  93811. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93812. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93813. try {
  93814. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93815. }
  93816. catch (e) {
  93817. throw new Error(context + ": " + e.message);
  93818. }
  93819. });
  93820. return bufferView._data;
  93821. };
  93822. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93823. var _this = this;
  93824. if (accessor.sparse) {
  93825. throw new Error(context + ": Sparse accessors are not currently supported");
  93826. }
  93827. if (accessor._data) {
  93828. return accessor._data;
  93829. }
  93830. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93831. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93832. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93833. var byteOffset = accessor.byteOffset || 0;
  93834. var byteStride = bufferView.byteStride;
  93835. if (byteStride === 0) {
  93836. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93837. }
  93838. try {
  93839. switch (accessor.componentType) {
  93840. case 5120 /* BYTE */: {
  93841. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93842. }
  93843. case 5121 /* UNSIGNED_BYTE */: {
  93844. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93845. }
  93846. case 5122 /* SHORT */: {
  93847. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93848. }
  93849. case 5123 /* UNSIGNED_SHORT */: {
  93850. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93851. }
  93852. case 5125 /* UNSIGNED_INT */: {
  93853. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93854. }
  93855. case 5126 /* FLOAT */: {
  93856. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93857. }
  93858. default: {
  93859. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93860. }
  93861. }
  93862. }
  93863. catch (e) {
  93864. throw new Error(context + ": " + e.messsage);
  93865. }
  93866. });
  93867. return accessor._data;
  93868. };
  93869. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93870. byteOffset += data.byteOffset;
  93871. var targetLength = count * numComponents;
  93872. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93873. return new typedArray(data.buffer, byteOffset, targetLength);
  93874. }
  93875. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93876. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93877. var targetBuffer = new typedArray(targetLength);
  93878. var sourceIndex = 0;
  93879. var targetIndex = 0;
  93880. while (targetIndex < targetLength) {
  93881. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93882. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93883. targetIndex++;
  93884. }
  93885. sourceIndex += elementStride;
  93886. }
  93887. return targetBuffer;
  93888. };
  93889. GLTFLoader.prototype._getDefaultMaterial = function () {
  93890. var id = "__gltf_default";
  93891. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93892. if (!babylonMaterial) {
  93893. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93894. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93895. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93896. babylonMaterial.metallic = 1;
  93897. babylonMaterial.roughness = 1;
  93898. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93899. }
  93900. return babylonMaterial;
  93901. };
  93902. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93903. var promises = new Array();
  93904. var babylonMaterial = material._babylonMaterial;
  93905. // Ensure metallic workflow
  93906. babylonMaterial.metallic = 1;
  93907. babylonMaterial.roughness = 1;
  93908. var properties = material.pbrMetallicRoughness;
  93909. if (properties) {
  93910. if (properties.baseColorFactor) {
  93911. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93912. babylonMaterial.alpha = properties.baseColorFactor[3];
  93913. }
  93914. else {
  93915. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93916. }
  93917. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93918. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93919. if (properties.baseColorTexture) {
  93920. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93921. babylonMaterial.albedoTexture = texture;
  93922. }));
  93923. }
  93924. if (properties.metallicRoughnessTexture) {
  93925. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93926. babylonMaterial.metallicTexture = texture;
  93927. }));
  93928. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93929. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93930. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93931. }
  93932. }
  93933. this._loadMaterialAlphaProperties(context, material);
  93934. return Promise.all(promises).then(function () { });
  93935. };
  93936. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93937. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93938. if (promise) {
  93939. return promise;
  93940. }
  93941. material._babylonMeshes = material._babylonMeshes || [];
  93942. material._babylonMeshes.push(babylonMesh);
  93943. if (!material._loaded) {
  93944. var promises = new Array();
  93945. var babylonMaterial = this._createMaterial(material);
  93946. material._babylonMaterial = babylonMaterial;
  93947. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93948. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93949. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93950. material._loaded = Promise.all(promises).then(function () { });
  93951. }
  93952. assign(material._babylonMaterial);
  93953. return material._loaded;
  93954. };
  93955. GLTFLoader.prototype._createMaterial = function (material) {
  93956. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93957. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93958. return babylonMaterial;
  93959. };
  93960. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93961. var promises = new Array();
  93962. var babylonMaterial = material._babylonMaterial;
  93963. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93964. if (material.doubleSided) {
  93965. babylonMaterial.backFaceCulling = false;
  93966. babylonMaterial.twoSidedLighting = true;
  93967. }
  93968. if (material.normalTexture) {
  93969. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93970. babylonMaterial.bumpTexture = texture;
  93971. }));
  93972. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93973. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93974. if (material.normalTexture.scale != undefined) {
  93975. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93976. }
  93977. }
  93978. if (material.occlusionTexture) {
  93979. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93980. babylonMaterial.ambientTexture = texture;
  93981. }));
  93982. babylonMaterial.useAmbientInGrayScale = true;
  93983. if (material.occlusionTexture.strength != undefined) {
  93984. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93985. }
  93986. }
  93987. if (material.emissiveTexture) {
  93988. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93989. babylonMaterial.emissiveTexture = texture;
  93990. }));
  93991. }
  93992. return Promise.all(promises).then(function () { });
  93993. };
  93994. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93995. var babylonMaterial = material._babylonMaterial;
  93996. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93997. switch (alphaMode) {
  93998. case "OPAQUE" /* OPAQUE */: {
  93999. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94000. break;
  94001. }
  94002. case "MASK" /* MASK */: {
  94003. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  94004. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  94005. if (babylonMaterial.alpha) {
  94006. if (babylonMaterial.alpha === 0) {
  94007. babylonMaterial.alphaCutOff = 1;
  94008. }
  94009. else {
  94010. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  94011. }
  94012. babylonMaterial.alpha = 1;
  94013. }
  94014. if (babylonMaterial.albedoTexture) {
  94015. babylonMaterial.albedoTexture.hasAlpha = true;
  94016. }
  94017. break;
  94018. }
  94019. case "BLEND" /* BLEND */: {
  94020. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  94021. if (babylonMaterial.albedoTexture) {
  94022. babylonMaterial.albedoTexture.hasAlpha = true;
  94023. babylonMaterial.useAlphaFromAlbedoTexture = true;
  94024. }
  94025. break;
  94026. }
  94027. default: {
  94028. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  94029. }
  94030. }
  94031. };
  94032. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  94033. var _this = this;
  94034. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  94035. context = "#/textures/" + textureInfo.index;
  94036. var promises = new Array();
  94037. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  94038. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  94039. var deferred = new BABYLON.Deferred();
  94040. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  94041. if (!_this._disposed) {
  94042. deferred.resolve();
  94043. }
  94044. }, function (message, exception) {
  94045. if (!_this._disposed) {
  94046. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  94047. }
  94048. });
  94049. promises.push(deferred.promise);
  94050. babylonTexture.name = texture.name || "texture" + texture._index;
  94051. babylonTexture.wrapU = samplerData.wrapU;
  94052. babylonTexture.wrapV = samplerData.wrapV;
  94053. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  94054. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  94055. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  94056. babylonTexture.updateURL(objectURL);
  94057. }));
  94058. assign(babylonTexture);
  94059. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  94060. return Promise.all(promises).then(function () { });
  94061. };
  94062. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  94063. if (!sampler._data) {
  94064. sampler._data = {
  94065. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  94066. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  94067. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  94068. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  94069. };
  94070. }
  94071. ;
  94072. return sampler._data;
  94073. };
  94074. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  94075. if (image._objectURL) {
  94076. return image._objectURL;
  94077. }
  94078. var promise;
  94079. if (image.uri) {
  94080. promise = this._loadUriAsync(context, image.uri);
  94081. }
  94082. else {
  94083. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  94084. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  94085. }
  94086. image._objectURL = promise.then(function (data) {
  94087. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  94088. });
  94089. return image._objectURL;
  94090. };
  94091. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  94092. var _this = this;
  94093. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  94094. if (promise) {
  94095. return promise;
  94096. }
  94097. if (!GLTFLoader._ValidateUri(uri)) {
  94098. throw new Error(context + ": Uri '" + uri + "' is invalid");
  94099. }
  94100. if (BABYLON.Tools.IsBase64(uri)) {
  94101. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  94102. }
  94103. return new Promise(function (resolve, reject) {
  94104. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  94105. if (!_this._disposed) {
  94106. resolve(new Uint8Array(data));
  94107. }
  94108. }, function (event) {
  94109. if (!_this._disposed) {
  94110. try {
  94111. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  94112. request._lengthComputable = event.lengthComputable;
  94113. request._loaded = event.loaded;
  94114. request._total = event.total;
  94115. _this._onProgress();
  94116. }
  94117. }
  94118. catch (e) {
  94119. reject(e);
  94120. }
  94121. }
  94122. }, _this._babylonScene.database, true, function (request, exception) {
  94123. if (!_this._disposed) {
  94124. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  94125. }
  94126. });
  94127. _this._requests.push(request);
  94128. });
  94129. };
  94130. GLTFLoader.prototype._onProgress = function () {
  94131. if (!this._progressCallback) {
  94132. return;
  94133. }
  94134. var lengthComputable = true;
  94135. var loaded = 0;
  94136. var total = 0;
  94137. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94138. var request = _a[_i];
  94139. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  94140. return;
  94141. }
  94142. lengthComputable = lengthComputable && request._lengthComputable;
  94143. loaded += request._loaded;
  94144. total += request._total;
  94145. }
  94146. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  94147. };
  94148. GLTFLoader._GetProperty = function (context, array, index) {
  94149. if (!array || index == undefined || !array[index]) {
  94150. throw new Error(context + ": Failed to find index (" + index + ")");
  94151. }
  94152. return array[index];
  94153. };
  94154. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  94155. // Set defaults if undefined
  94156. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  94157. switch (mode) {
  94158. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  94159. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  94160. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  94161. default:
  94162. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  94163. return BABYLON.Texture.WRAP_ADDRESSMODE;
  94164. }
  94165. };
  94166. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  94167. // Set defaults if undefined
  94168. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  94169. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  94170. if (magFilter === 9729 /* LINEAR */) {
  94171. switch (minFilter) {
  94172. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  94173. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  94174. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  94175. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  94176. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  94177. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94178. default:
  94179. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94180. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94181. }
  94182. }
  94183. else {
  94184. if (magFilter !== 9728 /* NEAREST */) {
  94185. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  94186. }
  94187. switch (minFilter) {
  94188. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  94189. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  94190. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94191. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  94192. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  94193. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  94194. default:
  94195. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94196. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94197. }
  94198. }
  94199. };
  94200. GLTFLoader._GetNumComponents = function (context, type) {
  94201. switch (type) {
  94202. case "SCALAR": return 1;
  94203. case "VEC2": return 2;
  94204. case "VEC3": return 3;
  94205. case "VEC4": return 4;
  94206. case "MAT2": return 4;
  94207. case "MAT3": return 9;
  94208. case "MAT4": return 16;
  94209. }
  94210. throw new Error(context + ": Invalid type (" + type + ")");
  94211. };
  94212. GLTFLoader._ValidateUri = function (uri) {
  94213. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  94214. };
  94215. GLTFLoader.prototype._compileMaterialsAsync = function () {
  94216. var promises = new Array();
  94217. if (this._gltf.materials) {
  94218. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  94219. var material = _a[_i];
  94220. var babylonMaterial = material._babylonMaterial;
  94221. var babylonMeshes = material._babylonMeshes;
  94222. if (babylonMaterial && babylonMeshes) {
  94223. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  94224. var babylonMesh = babylonMeshes_1[_b];
  94225. // Ensure nonUniformScaling is set if necessary.
  94226. babylonMesh.computeWorldMatrix(true);
  94227. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  94228. if (this.useClipPlane) {
  94229. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  94230. }
  94231. }
  94232. }
  94233. }
  94234. }
  94235. return Promise.all(promises).then(function () { });
  94236. };
  94237. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  94238. var promises = new Array();
  94239. var lights = this._babylonScene.lights;
  94240. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  94241. var light = lights_1[_i];
  94242. var generator = light.getShadowGenerator();
  94243. if (generator) {
  94244. promises.push(generator.forceCompilationAsync());
  94245. }
  94246. }
  94247. return Promise.all(promises).then(function () { });
  94248. };
  94249. GLTFLoader.prototype._clear = function () {
  94250. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94251. var request = _a[_i];
  94252. request.abort();
  94253. }
  94254. this._requests.length = 0;
  94255. if (this._gltf && this._gltf.images) {
  94256. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  94257. var image = _c[_b];
  94258. if (image._objectURL) {
  94259. image._objectURL.then(function (value) {
  94260. URL.revokeObjectURL(value);
  94261. });
  94262. image._objectURL = undefined;
  94263. }
  94264. }
  94265. }
  94266. delete this._gltf;
  94267. delete this._babylonScene;
  94268. this._completePromises.length = 0;
  94269. for (var name_3 in this._extensions) {
  94270. this._extensions[name_3].dispose();
  94271. }
  94272. this._extensions = {};
  94273. delete this._rootBabylonMesh;
  94274. delete this._progressCallback;
  94275. this.onMeshLoadedObservable.clear();
  94276. this.onTextureLoadedObservable.clear();
  94277. this.onMaterialLoadedObservable.clear();
  94278. };
  94279. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  94280. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94281. var name_4 = _a[_i];
  94282. var extension = this._extensions[name_4];
  94283. if (extension.enabled) {
  94284. var promise = actionAsync(extension);
  94285. if (promise) {
  94286. return promise;
  94287. }
  94288. }
  94289. }
  94290. return null;
  94291. };
  94292. GLTFLoader._Names = new Array();
  94293. GLTFLoader._Factories = {};
  94294. return GLTFLoader;
  94295. }());
  94296. GLTF2.GLTFLoader = GLTFLoader;
  94297. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  94298. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94299. })(BABYLON || (BABYLON = {}));
  94300. //# sourceMappingURL=babylon.glTFLoader.js.map
  94301. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94302. var BABYLON;
  94303. (function (BABYLON) {
  94304. var GLTF2;
  94305. (function (GLTF2) {
  94306. var GLTFLoaderExtension = /** @class */ (function () {
  94307. function GLTFLoaderExtension(loader) {
  94308. this.enabled = true;
  94309. this._loader = loader;
  94310. }
  94311. GLTFLoaderExtension.prototype.dispose = function () {
  94312. delete this._loader;
  94313. };
  94314. // #region Overridable Methods
  94315. /** Override this method to modify the default behavior for loading scenes. */
  94316. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  94317. /** Override this method to modify the default behavior for loading nodes. */
  94318. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  94319. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  94320. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  94321. /** Override this method to modify the default behavior for loading materials. */
  94322. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  94323. /** Override this method to modify the default behavior for loading uris. */
  94324. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  94325. // #endregion
  94326. /** Helper method called by a loader extension to load an glTF extension. */
  94327. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94328. if (!property.extensions) {
  94329. return null;
  94330. }
  94331. var extensions = property.extensions;
  94332. var extension = extensions[this.name];
  94333. if (!extension) {
  94334. return null;
  94335. }
  94336. // Clear out the extension before executing the action to avoid recursing into the same property.
  94337. delete extensions[this.name];
  94338. try {
  94339. return actionAsync(context + "/extensions/" + this.name, extension);
  94340. }
  94341. finally {
  94342. // Restore the extension after executing the action.
  94343. extensions[this.name] = extension;
  94344. }
  94345. };
  94346. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94347. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94348. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94349. };
  94350. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94351. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94352. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94353. };
  94354. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94355. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94356. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94357. };
  94358. /** Helper method called by the loader to allow extensions to override loading materials. */
  94359. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94360. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94361. };
  94362. /** Helper method called by the loader to allow extensions to override loading uris. */
  94363. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94364. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94365. };
  94366. return GLTFLoaderExtension;
  94367. }());
  94368. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94369. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94370. })(BABYLON || (BABYLON = {}));
  94371. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94372. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94373. var BABYLON;
  94374. (function (BABYLON) {
  94375. var GLTF2;
  94376. (function (GLTF2) {
  94377. var Extensions;
  94378. (function (Extensions) {
  94379. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94380. var NAME = "MSFT_lod";
  94381. var MSFT_lod = /** @class */ (function (_super) {
  94382. __extends(MSFT_lod, _super);
  94383. function MSFT_lod() {
  94384. var _this = _super !== null && _super.apply(this, arguments) || this;
  94385. _this.name = NAME;
  94386. /**
  94387. * Maximum number of LODs to load, starting from the lowest LOD.
  94388. */
  94389. _this.maxLODsToLoad = Number.MAX_VALUE;
  94390. _this._loadingNodeLOD = null;
  94391. _this._loadNodeSignals = {};
  94392. _this._loadingMaterialLOD = null;
  94393. _this._loadMaterialSignals = {};
  94394. return _this;
  94395. }
  94396. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94397. var _this = this;
  94398. return this._loadExtensionAsync(context, node, function (context, extension) {
  94399. var firstPromise;
  94400. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94401. var _loop_1 = function (indexLOD) {
  94402. var nodeLOD = nodeLODs[indexLOD];
  94403. if (indexLOD !== 0) {
  94404. _this._loadingNodeLOD = nodeLOD;
  94405. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94406. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94407. }
  94408. }
  94409. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94410. if (indexLOD !== 0) {
  94411. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94412. if (previousNodeLOD._babylonMesh) {
  94413. previousNodeLOD._babylonMesh.dispose();
  94414. delete previousNodeLOD._babylonMesh;
  94415. }
  94416. }
  94417. if (indexLOD !== nodeLODs.length - 1) {
  94418. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94419. if (_this._loadNodeSignals[nodeIndex]) {
  94420. _this._loadNodeSignals[nodeIndex].resolve();
  94421. delete _this._loadNodeSignals[nodeIndex];
  94422. }
  94423. }
  94424. });
  94425. if (indexLOD === 0) {
  94426. firstPromise = promise;
  94427. }
  94428. else {
  94429. _this._loader._completePromises.push(promise);
  94430. _this._loadingNodeLOD = null;
  94431. }
  94432. };
  94433. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94434. _loop_1(indexLOD);
  94435. }
  94436. return firstPromise;
  94437. });
  94438. };
  94439. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94440. var _this = this;
  94441. // Don't load material LODs if already loading a node LOD.
  94442. if (this._loadingNodeLOD) {
  94443. return null;
  94444. }
  94445. return this._loadExtensionAsync(context, material, function (context, extension) {
  94446. var firstPromise;
  94447. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94448. var _loop_2 = function (indexLOD) {
  94449. var materialLOD = materialLODs[indexLOD];
  94450. if (indexLOD !== 0) {
  94451. _this._loadingMaterialLOD = materialLOD;
  94452. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94453. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94454. }
  94455. }
  94456. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94457. if (indexLOD !== 0) {
  94458. assign(materialLOD._babylonMaterial);
  94459. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94460. if (previousMaterialLOD._babylonMaterial) {
  94461. previousMaterialLOD._babylonMaterial.dispose();
  94462. delete previousMaterialLOD._babylonMaterial;
  94463. }
  94464. }
  94465. if (indexLOD !== materialLODs.length - 1) {
  94466. var materialIndex = materialLODs[indexLOD + 1]._index;
  94467. if (_this._loadMaterialSignals[materialIndex]) {
  94468. _this._loadMaterialSignals[materialIndex].resolve();
  94469. delete _this._loadMaterialSignals[materialIndex];
  94470. }
  94471. }
  94472. });
  94473. if (indexLOD === 0) {
  94474. firstPromise = promise;
  94475. }
  94476. else {
  94477. _this._loader._completePromises.push(promise);
  94478. _this._loadingMaterialLOD = null;
  94479. }
  94480. };
  94481. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94482. _loop_2(indexLOD);
  94483. }
  94484. return firstPromise;
  94485. });
  94486. };
  94487. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94488. var _this = this;
  94489. // Defer the loading of uris if loading a material or node LOD.
  94490. if (this._loadingMaterialLOD) {
  94491. var index = this._loadingMaterialLOD._index;
  94492. return this._loadMaterialSignals[index].promise.then(function () {
  94493. return _this._loader._loadUriAsync(context, uri);
  94494. });
  94495. }
  94496. else if (this._loadingNodeLOD) {
  94497. var index = this._loadingNodeLOD._index;
  94498. return this._loadNodeSignals[index].promise.then(function () {
  94499. return _this._loader._loadUriAsync(context, uri);
  94500. });
  94501. }
  94502. return null;
  94503. };
  94504. /**
  94505. * Gets an array of LOD properties from lowest to highest.
  94506. */
  94507. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94508. if (this.maxLODsToLoad <= 0) {
  94509. throw new Error("maxLODsToLoad must be greater than zero");
  94510. }
  94511. var properties = new Array();
  94512. for (var i = ids.length - 1; i >= 0; i--) {
  94513. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94514. if (properties.length === this.maxLODsToLoad) {
  94515. return properties;
  94516. }
  94517. }
  94518. properties.push(property);
  94519. return properties;
  94520. };
  94521. return MSFT_lod;
  94522. }(GLTF2.GLTFLoaderExtension));
  94523. Extensions.MSFT_lod = MSFT_lod;
  94524. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94525. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94526. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94527. })(BABYLON || (BABYLON = {}));
  94528. //# sourceMappingURL=MSFT_lod.js.map
  94529. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94530. var BABYLON;
  94531. (function (BABYLON) {
  94532. var GLTF2;
  94533. (function (GLTF2) {
  94534. var Extensions;
  94535. (function (Extensions) {
  94536. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94537. var NAME = "KHR_draco_mesh_compression";
  94538. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94539. __extends(KHR_draco_mesh_compression, _super);
  94540. function KHR_draco_mesh_compression(loader) {
  94541. var _this = _super.call(this, loader) || this;
  94542. _this.name = NAME;
  94543. _this._dracoCompression = null;
  94544. // Disable extension if decoder is not available.
  94545. if (!BABYLON.DracoCompression.DecoderUrl) {
  94546. _this.enabled = false;
  94547. }
  94548. return _this;
  94549. }
  94550. KHR_draco_mesh_compression.prototype.dispose = function () {
  94551. if (this._dracoCompression) {
  94552. this._dracoCompression.dispose();
  94553. }
  94554. _super.prototype.dispose.call(this);
  94555. };
  94556. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94557. var _this = this;
  94558. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94559. if (primitive.mode != undefined) {
  94560. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94561. primitive.mode !== 4 /* TRIANGLES */) {
  94562. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94563. }
  94564. // TODO: handle triangle strips
  94565. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94566. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94567. }
  94568. }
  94569. var attributes = {};
  94570. var loadAttribute = function (name, kind) {
  94571. var uniqueId = extension.attributes[name];
  94572. if (uniqueId == undefined) {
  94573. return;
  94574. }
  94575. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94576. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94577. babylonMesh._delayInfo.push(kind);
  94578. }
  94579. attributes[kind] = uniqueId;
  94580. };
  94581. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94582. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94583. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94584. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94585. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94586. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94587. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94588. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94589. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94590. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94591. try {
  94592. if (!_this._dracoCompression) {
  94593. _this._dracoCompression = new BABYLON.DracoCompression();
  94594. }
  94595. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94596. }
  94597. catch (e) {
  94598. throw new Error(context + ": " + e.message);
  94599. }
  94600. });
  94601. });
  94602. };
  94603. return KHR_draco_mesh_compression;
  94604. }(GLTF2.GLTFLoaderExtension));
  94605. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94606. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94607. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94608. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94609. })(BABYLON || (BABYLON = {}));
  94610. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94611. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94612. var BABYLON;
  94613. (function (BABYLON) {
  94614. var GLTF2;
  94615. (function (GLTF2) {
  94616. var Extensions;
  94617. (function (Extensions) {
  94618. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94619. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94620. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94621. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94622. function KHR_materials_pbrSpecularGlossiness() {
  94623. var _this = _super !== null && _super.apply(this, arguments) || this;
  94624. _this.name = NAME;
  94625. return _this;
  94626. }
  94627. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94628. var _this = this;
  94629. return this._loadExtensionAsync(context, material, function (context, extension) {
  94630. material._babylonMeshes = material._babylonMeshes || [];
  94631. material._babylonMeshes.push(babylonMesh);
  94632. if (!material._loaded) {
  94633. var promises = new Array();
  94634. var babylonMaterial = _this._loader._createMaterial(material);
  94635. material._babylonMaterial = babylonMaterial;
  94636. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94637. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94638. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94639. material._loaded = Promise.all(promises).then(function () { });
  94640. }
  94641. assign(material._babylonMaterial);
  94642. return material._loaded;
  94643. });
  94644. };
  94645. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94646. var promises = new Array();
  94647. var babylonMaterial = material._babylonMaterial;
  94648. if (properties.diffuseFactor) {
  94649. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94650. babylonMaterial.alpha = properties.diffuseFactor[3];
  94651. }
  94652. else {
  94653. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94654. }
  94655. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94656. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94657. if (properties.diffuseTexture) {
  94658. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94659. babylonMaterial.albedoTexture = texture;
  94660. }));
  94661. }
  94662. if (properties.specularGlossinessTexture) {
  94663. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94664. babylonMaterial.reflectivityTexture = texture;
  94665. }));
  94666. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94667. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94668. }
  94669. this._loader._loadMaterialAlphaProperties(context, material);
  94670. return Promise.all(promises).then(function () { });
  94671. };
  94672. return KHR_materials_pbrSpecularGlossiness;
  94673. }(GLTF2.GLTFLoaderExtension));
  94674. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94675. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94676. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94677. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94678. })(BABYLON || (BABYLON = {}));
  94679. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94680. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94681. var BABYLON;
  94682. (function (BABYLON) {
  94683. var GLTF2;
  94684. (function (GLTF2) {
  94685. var Extensions;
  94686. (function (Extensions) {
  94687. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94688. var NAME = "KHR_lights";
  94689. var LightType;
  94690. (function (LightType) {
  94691. LightType["AMBIENT"] = "ambient";
  94692. LightType["DIRECTIONAL"] = "directional";
  94693. LightType["POINT"] = "point";
  94694. LightType["SPOT"] = "spot";
  94695. })(LightType || (LightType = {}));
  94696. var KHR_lights = /** @class */ (function (_super) {
  94697. __extends(KHR_lights, _super);
  94698. function KHR_lights() {
  94699. var _this = _super !== null && _super.apply(this, arguments) || this;
  94700. _this.name = NAME;
  94701. return _this;
  94702. }
  94703. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94704. var _this = this;
  94705. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94706. var promise = _this._loader._loadSceneAsync(context, scene);
  94707. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94708. if (light.type !== LightType.AMBIENT) {
  94709. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94710. }
  94711. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94712. return promise;
  94713. });
  94714. };
  94715. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94716. var _this = this;
  94717. return this._loadExtensionAsync(context, node, function (context, extension) {
  94718. var promise = _this._loader._loadNodeAsync(context, node);
  94719. var babylonLight;
  94720. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94721. var name = node._babylonMesh.name;
  94722. switch (light.type) {
  94723. case LightType.AMBIENT: {
  94724. throw new Error(context + ": Ambient lights are not allowed on a node");
  94725. }
  94726. case LightType.DIRECTIONAL: {
  94727. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94728. break;
  94729. }
  94730. case LightType.POINT: {
  94731. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94732. break;
  94733. }
  94734. case LightType.SPOT: {
  94735. var spotLight = light;
  94736. // TODO: support inner and outer cone angles
  94737. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94738. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94739. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94740. break;
  94741. }
  94742. default: {
  94743. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94744. }
  94745. }
  94746. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94747. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94748. babylonLight.parent = node._babylonMesh;
  94749. return promise;
  94750. });
  94751. };
  94752. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94753. get: function () {
  94754. var extensions = this._loader._gltf.extensions;
  94755. if (!extensions || !extensions[this.name]) {
  94756. throw new Error("#/extensions: '" + this.name + "' not found");
  94757. }
  94758. var extension = extensions[this.name];
  94759. return extension.lights;
  94760. },
  94761. enumerable: true,
  94762. configurable: true
  94763. });
  94764. return KHR_lights;
  94765. }(GLTF2.GLTFLoaderExtension));
  94766. Extensions.KHR_lights = KHR_lights;
  94767. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94768. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94769. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94770. })(BABYLON || (BABYLON = {}));
  94771. //# sourceMappingURL=KHR_lights.js.map
  94772. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94773. globalObject["BABYLON"] = BABYLON
  94774. return BABYLON;
  94775. });