babylon.max.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350
  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. break;
  10553. }
  10554. }
  10555. }
  10556. // GL
  10557. if (!options.disableWebGL2Support) {
  10558. try {
  10559. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10560. if (this._gl) {
  10561. this._webGLVersion = 2.0;
  10562. }
  10563. }
  10564. catch (e) {
  10565. // Do nothing
  10566. }
  10567. }
  10568. if (!this._gl) {
  10569. if (!canvas) {
  10570. throw new Error("The provided canvas is null or undefined.");
  10571. }
  10572. try {
  10573. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10574. }
  10575. catch (e) {
  10576. throw new Error("WebGL not supported");
  10577. }
  10578. }
  10579. if (!this._gl) {
  10580. throw new Error("WebGL not supported");
  10581. }
  10582. this._onCanvasFocus = function () {
  10583. _this.onCanvasFocusObservable.notifyObservers(_this);
  10584. };
  10585. this._onCanvasBlur = function () {
  10586. _this.onCanvasBlurObservable.notifyObservers(_this);
  10587. };
  10588. canvas.addEventListener("focus", this._onCanvasFocus);
  10589. canvas.addEventListener("blur", this._onCanvasBlur);
  10590. this._onBlur = function () {
  10591. if (_this.disablePerformanceMonitorInBackground) {
  10592. _this._performanceMonitor.disable();
  10593. }
  10594. _this._windowIsBackground = true;
  10595. };
  10596. this._onFocus = function () {
  10597. if (_this.disablePerformanceMonitorInBackground) {
  10598. _this._performanceMonitor.enable();
  10599. }
  10600. _this._windowIsBackground = false;
  10601. };
  10602. this._onCanvasPointerOut = function (ev) {
  10603. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10604. };
  10605. window.addEventListener("blur", this._onBlur);
  10606. window.addEventListener("focus", this._onFocus);
  10607. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10608. // Context lost
  10609. if (!this._doNotHandleContextLost) {
  10610. this._onContextLost = function (evt) {
  10611. evt.preventDefault();
  10612. _this._contextWasLost = true;
  10613. BABYLON.Tools.Warn("WebGL context lost.");
  10614. _this.onContextLostObservable.notifyObservers(_this);
  10615. };
  10616. this._onContextRestored = function (evt) {
  10617. // Adding a timeout to avoid race condition at browser level
  10618. setTimeout(function () {
  10619. // Rebuild gl context
  10620. _this._initGLContext();
  10621. // Rebuild effects
  10622. _this._rebuildEffects();
  10623. // Rebuild textures
  10624. _this._rebuildInternalTextures();
  10625. // Rebuild buffers
  10626. _this._rebuildBuffers();
  10627. // Cache
  10628. _this.wipeCaches(true);
  10629. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10630. _this.onContextRestoredObservable.notifyObservers(_this);
  10631. _this._contextWasLost = false;
  10632. }, 0);
  10633. };
  10634. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10635. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10636. }
  10637. }
  10638. else {
  10639. this._gl = canvasOrContext;
  10640. this._renderingCanvas = this._gl.canvas;
  10641. if (this._gl.renderbufferStorageMultisample) {
  10642. this._webGLVersion = 2.0;
  10643. }
  10644. options.stencil = this._gl.getContextAttributes().stencil;
  10645. }
  10646. // Viewport
  10647. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10648. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10649. this.resize();
  10650. this._isStencilEnable = options.stencil ? true : false;
  10651. this._initGLContext();
  10652. if (canvas) {
  10653. // Fullscreen
  10654. this._onFullscreenChange = function () {
  10655. if (document.fullscreen !== undefined) {
  10656. _this.isFullscreen = document.fullscreen;
  10657. }
  10658. else if (document.mozFullScreen !== undefined) {
  10659. _this.isFullscreen = document.mozFullScreen;
  10660. }
  10661. else if (document.webkitIsFullScreen !== undefined) {
  10662. _this.isFullscreen = document.webkitIsFullScreen;
  10663. }
  10664. else if (document.msIsFullScreen !== undefined) {
  10665. _this.isFullscreen = document.msIsFullScreen;
  10666. }
  10667. // Pointer lock
  10668. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10669. canvas.requestPointerLock = canvas.requestPointerLock ||
  10670. canvas.msRequestPointerLock ||
  10671. canvas.mozRequestPointerLock ||
  10672. canvas.webkitRequestPointerLock;
  10673. if (canvas.requestPointerLock) {
  10674. canvas.requestPointerLock();
  10675. }
  10676. }
  10677. };
  10678. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10679. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10680. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10681. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10682. // Pointer lock
  10683. this._onPointerLockChange = function () {
  10684. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10685. document.webkitPointerLockElement === canvas ||
  10686. document.msPointerLockElement === canvas ||
  10687. document.pointerLockElement === canvas);
  10688. };
  10689. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10690. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10691. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10692. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10693. this._onVRDisplayPointerRestricted = function () {
  10694. if (canvas) {
  10695. canvas.requestPointerLock();
  10696. }
  10697. };
  10698. this._onVRDisplayPointerUnrestricted = function () {
  10699. document.exitPointerLock();
  10700. };
  10701. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10702. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10703. }
  10704. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10705. Engine.audioEngine = new BABYLON.AudioEngine();
  10706. }
  10707. // Prepare buffer pointers
  10708. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10709. this._currentBufferPointers[i] = new BufferPointer();
  10710. }
  10711. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10712. // Load WebVR Devices
  10713. if (options.autoEnableWebVR) {
  10714. this.initWebVR();
  10715. }
  10716. // Detect if we are running on a faulty buggy OS.
  10717. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10718. // Detect if we are running on a faulty buggy desktop OS.
  10719. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10720. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10721. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10722. }
  10723. Object.defineProperty(Engine, "LastCreatedEngine", {
  10724. get: function () {
  10725. if (Engine.Instances.length === 0) {
  10726. return null;
  10727. }
  10728. return Engine.Instances[Engine.Instances.length - 1];
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Engine, "LastCreatedScene", {
  10734. get: function () {
  10735. var lastCreatedEngine = Engine.LastCreatedEngine;
  10736. if (!lastCreatedEngine) {
  10737. return null;
  10738. }
  10739. if (lastCreatedEngine.scenes.length === 0) {
  10740. return null;
  10741. }
  10742. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. /**
  10748. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10749. */
  10750. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10751. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10752. var engine = Engine.Instances[engineIndex];
  10753. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10754. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10755. }
  10756. }
  10757. };
  10758. Object.defineProperty(Engine, "NEVER", {
  10759. get: function () {
  10760. return Engine._NEVER;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(Engine, "ALWAYS", {
  10766. get: function () {
  10767. return Engine._ALWAYS;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(Engine, "LESS", {
  10773. get: function () {
  10774. return Engine._LESS;
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. Object.defineProperty(Engine, "EQUAL", {
  10780. get: function () {
  10781. return Engine._EQUAL;
  10782. },
  10783. enumerable: true,
  10784. configurable: true
  10785. });
  10786. Object.defineProperty(Engine, "LEQUAL", {
  10787. get: function () {
  10788. return Engine._LEQUAL;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(Engine, "GREATER", {
  10794. get: function () {
  10795. return Engine._GREATER;
  10796. },
  10797. enumerable: true,
  10798. configurable: true
  10799. });
  10800. Object.defineProperty(Engine, "GEQUAL", {
  10801. get: function () {
  10802. return Engine._GEQUAL;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(Engine, "NOTEQUAL", {
  10808. get: function () {
  10809. return Engine._NOTEQUAL;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Object.defineProperty(Engine, "KEEP", {
  10815. get: function () {
  10816. return Engine._KEEP;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(Engine, "REPLACE", {
  10822. get: function () {
  10823. return Engine._REPLACE;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Object.defineProperty(Engine, "INCR", {
  10829. get: function () {
  10830. return Engine._INCR;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(Engine, "DECR", {
  10836. get: function () {
  10837. return Engine._DECR;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(Engine, "INVERT", {
  10843. get: function () {
  10844. return Engine._INVERT;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Engine, "INCR_WRAP", {
  10850. get: function () {
  10851. return Engine._INCR_WRAP;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Engine, "DECR_WRAP", {
  10857. get: function () {
  10858. return Engine._DECR_WRAP;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10864. get: function () {
  10865. return Engine._ALPHA_DISABLE;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10871. get: function () {
  10872. return Engine._ALPHA_ONEONE;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "ALPHA_ADD", {
  10878. get: function () {
  10879. return Engine._ALPHA_ADD;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10885. get: function () {
  10886. return Engine._ALPHA_COMBINE;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10892. get: function () {
  10893. return Engine._ALPHA_SUBTRACT;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10899. get: function () {
  10900. return Engine._ALPHA_MULTIPLY;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10906. get: function () {
  10907. return Engine._ALPHA_MAXIMIZED;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10913. get: function () {
  10914. return Engine._ALPHA_PREMULTIPLIED;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10920. get: function () {
  10921. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10927. get: function () {
  10928. return Engine._ALPHA_INTERPOLATE;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10934. get: function () {
  10935. return Engine._ALPHA_SCREENMODE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10941. get: function () {
  10942. return Engine._DELAYLOADSTATE_NONE;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10948. get: function () {
  10949. return Engine._DELAYLOADSTATE_LOADED;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10955. get: function () {
  10956. return Engine._DELAYLOADSTATE_LOADING;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10962. get: function () {
  10963. return Engine._DELAYLOADSTATE_NOTLOADED;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10969. get: function () {
  10970. return Engine._TEXTUREFORMAT_ALPHA;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10976. get: function () {
  10977. return Engine._TEXTUREFORMAT_LUMINANCE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10983. /**
  10984. * R32F
  10985. */
  10986. get: function () {
  10987. return Engine._TEXTUREFORMAT_R32F;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10993. /**
  10994. * RG32F
  10995. */
  10996. get: function () {
  10997. return Engine._TEXTUREFORMAT_RG32F;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11003. /**
  11004. * RGB32F
  11005. */
  11006. get: function () {
  11007. return Engine._TEXTUREFORMAT_RGB32F;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11013. /**
  11014. * RGBA32F
  11015. */
  11016. get: function () {
  11017. return Engine._TEXTUREFORMAT_RGBA32F;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11023. get: function () {
  11024. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11030. get: function () {
  11031. return Engine._TEXTUREFORMAT_RGB;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11037. get: function () {
  11038. return Engine._TEXTUREFORMAT_RGBA;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11044. get: function () {
  11045. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11051. get: function () {
  11052. return Engine._TEXTURETYPE_FLOAT;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11058. get: function () {
  11059. return Engine._TEXTURETYPE_HALF_FLOAT;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11065. get: function () {
  11066. return Engine._SCALEMODE_FLOOR;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11072. get: function () {
  11073. return Engine._SCALEMODE_NEAREST;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11079. get: function () {
  11080. return Engine._SCALEMODE_CEILING;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "Version", {
  11086. get: function () {
  11087. return "3.2.0-alphaB";
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11093. get: function () {
  11094. return this._vrExclusivePointerMode;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11100. get: function () {
  11101. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11107. get: function () {
  11108. return this._webGLVersion < 2 || this.forcePOTTextures;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine.prototype, "badOS", {
  11114. get: function () {
  11115. return this._badOS;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11121. get: function () {
  11122. return this._badDesktopOS;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11128. get: function () {
  11129. return this._performanceMonitor;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11135. get: function () {
  11136. return this._texturesSupported;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11142. get: function () {
  11143. return this._textureFormatInUse;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine.prototype, "currentViewport", {
  11149. get: function () {
  11150. return this._cachedViewport;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11156. // Empty texture
  11157. get: function () {
  11158. if (!this._emptyTexture) {
  11159. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11160. }
  11161. return this._emptyTexture;
  11162. },
  11163. enumerable: true,
  11164. configurable: true
  11165. });
  11166. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11167. get: function () {
  11168. if (!this._emptyTexture3D) {
  11169. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11170. }
  11171. return this._emptyTexture3D;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11177. get: function () {
  11178. if (!this._emptyCubeTexture) {
  11179. var faceData = new Uint8Array(4);
  11180. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11181. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11182. }
  11183. return this._emptyCubeTexture;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Engine.prototype._rebuildInternalTextures = function () {
  11189. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11190. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11191. var internalTexture = currentState_1[_i];
  11192. internalTexture._rebuild();
  11193. }
  11194. };
  11195. Engine.prototype._rebuildEffects = function () {
  11196. for (var key in this._compiledEffects) {
  11197. var effect = this._compiledEffects[key];
  11198. effect._prepareEffect();
  11199. }
  11200. BABYLON.Effect.ResetCache();
  11201. };
  11202. Engine.prototype._rebuildBuffers = function () {
  11203. // Index / Vertex
  11204. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11205. var scene = _a[_i];
  11206. scene.resetCachedMaterial();
  11207. scene._rebuildGeometries();
  11208. scene._rebuildTextures();
  11209. }
  11210. // Uniforms
  11211. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11212. var uniformBuffer = _c[_b];
  11213. uniformBuffer._rebuild();
  11214. }
  11215. };
  11216. Engine.prototype._initGLContext = function () {
  11217. // Caps
  11218. this._caps = new EngineCapabilities();
  11219. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11220. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11221. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11222. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11223. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11224. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11225. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11226. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11227. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11228. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11229. // Infos
  11230. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11231. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11232. if (rendererInfo != null) {
  11233. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11234. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11235. }
  11236. if (!this._glVendor) {
  11237. this._glVendor = "Unknown vendor";
  11238. }
  11239. if (!this._glRenderer) {
  11240. this._glRenderer = "Unknown renderer";
  11241. }
  11242. // Constants
  11243. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11244. if (this._gl.RGBA16F !== 0x881A) {
  11245. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11246. }
  11247. if (this._gl.RGBA32F !== 0x8814) {
  11248. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11249. }
  11250. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11251. this._gl.DEPTH24_STENCIL8 = 35056;
  11252. }
  11253. // Extensions
  11254. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11255. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11256. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11257. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11258. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11259. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11260. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11261. 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');
  11262. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11263. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11264. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11265. this._caps.highPrecisionShaderSupported = true;
  11266. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11267. if (this._caps.timerQuery) {
  11268. if (this._webGLVersion === 1) {
  11269. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11270. }
  11271. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11272. }
  11273. // Checks if some of the format renders first to allow the use of webgl inspector.
  11274. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11275. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11276. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11277. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11278. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11279. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11280. if (this._webGLVersion > 1) {
  11281. this._gl.HALF_FLOAT_OES = 0x140B;
  11282. }
  11283. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11284. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11285. // Draw buffers
  11286. if (this._webGLVersion > 1) {
  11287. this._caps.drawBuffersExtension = true;
  11288. }
  11289. else {
  11290. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11291. if (drawBuffersExtension !== null) {
  11292. this._caps.drawBuffersExtension = true;
  11293. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11294. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11295. for (var i = 0; i < 16; i++) {
  11296. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11297. }
  11298. }
  11299. else {
  11300. this._caps.drawBuffersExtension = false;
  11301. }
  11302. }
  11303. // Depth Texture
  11304. if (this._webGLVersion > 1) {
  11305. this._caps.depthTextureExtension = true;
  11306. }
  11307. else {
  11308. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11309. if (depthTextureExtension != null) {
  11310. this._caps.depthTextureExtension = true;
  11311. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11312. }
  11313. }
  11314. // Vertex array object
  11315. if (this._webGLVersion > 1) {
  11316. this._caps.vertexArrayObject = true;
  11317. }
  11318. else {
  11319. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11320. if (vertexArrayObjectExtension != null) {
  11321. this._caps.vertexArrayObject = true;
  11322. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11323. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11324. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11325. }
  11326. else {
  11327. this._caps.vertexArrayObject = false;
  11328. }
  11329. }
  11330. // Instances count
  11331. if (this._webGLVersion > 1) {
  11332. this._caps.instancedArrays = true;
  11333. }
  11334. else {
  11335. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11336. if (instanceExtension != null) {
  11337. this._caps.instancedArrays = true;
  11338. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11339. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11340. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11341. }
  11342. else {
  11343. this._caps.instancedArrays = false;
  11344. }
  11345. }
  11346. // Intelligently add supported compressed formats in order to check for.
  11347. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11348. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11349. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11350. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11351. if (this._caps.astc)
  11352. this.texturesSupported.push('-astc.ktx');
  11353. if (this._caps.s3tc)
  11354. this.texturesSupported.push('-dxt.ktx');
  11355. if (this._caps.pvrtc)
  11356. this.texturesSupported.push('-pvrtc.ktx');
  11357. if (this._caps.etc2)
  11358. this.texturesSupported.push('-etc2.ktx');
  11359. if (this._caps.etc1)
  11360. this.texturesSupported.push('-etc1.ktx');
  11361. if (this._gl.getShaderPrecisionFormat) {
  11362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11363. if (highp) {
  11364. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11365. }
  11366. }
  11367. // Depth buffer
  11368. this.setDepthBuffer(true);
  11369. this.setDepthFunctionToLessOrEqual();
  11370. this.setDepthWrite(true);
  11371. // Texture maps
  11372. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11373. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11374. this._nextFreeTextureSlots.push(slot);
  11375. }
  11376. };
  11377. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11378. get: function () {
  11379. return this._webGLVersion;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11385. /**
  11386. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11387. */
  11388. get: function () {
  11389. return this._isStencilEnable;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Engine.prototype._prepareWorkingCanvas = function () {
  11395. if (this._workingCanvas) {
  11396. return;
  11397. }
  11398. this._workingCanvas = document.createElement("canvas");
  11399. var context = this._workingCanvas.getContext("2d");
  11400. if (context) {
  11401. this._workingContext = context;
  11402. }
  11403. };
  11404. Engine.prototype.resetTextureCache = function () {
  11405. for (var key in this._boundTexturesCache) {
  11406. var boundTexture = this._boundTexturesCache[key];
  11407. if (boundTexture) {
  11408. this._removeDesignatedSlot(boundTexture);
  11409. }
  11410. this._boundTexturesCache[key] = null;
  11411. }
  11412. if (!this.disableTextureBindingOptimization) {
  11413. this._nextFreeTextureSlots = [];
  11414. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11415. this._nextFreeTextureSlots.push(slot);
  11416. }
  11417. }
  11418. this._currentTextureChannel = -1;
  11419. };
  11420. Engine.prototype.isDeterministicLockStep = function () {
  11421. return this._deterministicLockstep;
  11422. };
  11423. Engine.prototype.getLockstepMaxSteps = function () {
  11424. return this._lockstepMaxSteps;
  11425. };
  11426. Engine.prototype.getGlInfo = function () {
  11427. return {
  11428. vendor: this._glVendor,
  11429. renderer: this._glRenderer,
  11430. version: this._glVersion
  11431. };
  11432. };
  11433. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11434. if (useScreen === void 0) { useScreen = false; }
  11435. var viewport = camera.viewport;
  11436. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11437. };
  11438. Engine.prototype.getRenderWidth = function (useScreen) {
  11439. if (useScreen === void 0) { useScreen = false; }
  11440. if (!useScreen && this._currentRenderTarget) {
  11441. return this._currentRenderTarget.width;
  11442. }
  11443. return this._gl.drawingBufferWidth;
  11444. };
  11445. Engine.prototype.getRenderHeight = function (useScreen) {
  11446. if (useScreen === void 0) { useScreen = false; }
  11447. if (!useScreen && this._currentRenderTarget) {
  11448. return this._currentRenderTarget.height;
  11449. }
  11450. return this._gl.drawingBufferHeight;
  11451. };
  11452. Engine.prototype.getRenderingCanvas = function () {
  11453. return this._renderingCanvas;
  11454. };
  11455. Engine.prototype.getRenderingCanvasClientRect = function () {
  11456. if (!this._renderingCanvas) {
  11457. return null;
  11458. }
  11459. return this._renderingCanvas.getBoundingClientRect();
  11460. };
  11461. Engine.prototype.setHardwareScalingLevel = function (level) {
  11462. this._hardwareScalingLevel = level;
  11463. this.resize();
  11464. };
  11465. Engine.prototype.getHardwareScalingLevel = function () {
  11466. return this._hardwareScalingLevel;
  11467. };
  11468. Engine.prototype.getLoadedTexturesCache = function () {
  11469. return this._internalTexturesCache;
  11470. };
  11471. Engine.prototype.getCaps = function () {
  11472. return this._caps;
  11473. };
  11474. Object.defineProperty(Engine.prototype, "drawCalls", {
  11475. /** The number of draw calls submitted last frame */
  11476. get: function () {
  11477. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11478. return 0;
  11479. },
  11480. enumerable: true,
  11481. configurable: true
  11482. });
  11483. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11484. get: function () {
  11485. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11486. return null;
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Engine.prototype.getDepthFunction = function () {
  11492. return this._depthCullingState.depthFunc;
  11493. };
  11494. Engine.prototype.setDepthFunction = function (depthFunc) {
  11495. this._depthCullingState.depthFunc = depthFunc;
  11496. };
  11497. Engine.prototype.setDepthFunctionToGreater = function () {
  11498. this._depthCullingState.depthFunc = this._gl.GREATER;
  11499. };
  11500. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11501. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11502. };
  11503. Engine.prototype.setDepthFunctionToLess = function () {
  11504. this._depthCullingState.depthFunc = this._gl.LESS;
  11505. };
  11506. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11507. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11508. };
  11509. Engine.prototype.getStencilBuffer = function () {
  11510. return this._stencilState.stencilTest;
  11511. };
  11512. Engine.prototype.setStencilBuffer = function (enable) {
  11513. this._stencilState.stencilTest = enable;
  11514. };
  11515. Engine.prototype.getStencilMask = function () {
  11516. return this._stencilState.stencilMask;
  11517. };
  11518. Engine.prototype.setStencilMask = function (mask) {
  11519. this._stencilState.stencilMask = mask;
  11520. };
  11521. Engine.prototype.getStencilFunction = function () {
  11522. return this._stencilState.stencilFunc;
  11523. };
  11524. Engine.prototype.getStencilFunctionReference = function () {
  11525. return this._stencilState.stencilFuncRef;
  11526. };
  11527. Engine.prototype.getStencilFunctionMask = function () {
  11528. return this._stencilState.stencilFuncMask;
  11529. };
  11530. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11531. this._stencilState.stencilFunc = stencilFunc;
  11532. };
  11533. Engine.prototype.setStencilFunctionReference = function (reference) {
  11534. this._stencilState.stencilFuncRef = reference;
  11535. };
  11536. Engine.prototype.setStencilFunctionMask = function (mask) {
  11537. this._stencilState.stencilFuncMask = mask;
  11538. };
  11539. Engine.prototype.getStencilOperationFail = function () {
  11540. return this._stencilState.stencilOpStencilFail;
  11541. };
  11542. Engine.prototype.getStencilOperationDepthFail = function () {
  11543. return this._stencilState.stencilOpDepthFail;
  11544. };
  11545. Engine.prototype.getStencilOperationPass = function () {
  11546. return this._stencilState.stencilOpStencilDepthPass;
  11547. };
  11548. Engine.prototype.setStencilOperationFail = function (operation) {
  11549. this._stencilState.stencilOpStencilFail = operation;
  11550. };
  11551. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11552. this._stencilState.stencilOpDepthFail = operation;
  11553. };
  11554. Engine.prototype.setStencilOperationPass = function (operation) {
  11555. this._stencilState.stencilOpStencilDepthPass = operation;
  11556. };
  11557. Engine.prototype.setDitheringState = function (value) {
  11558. if (value) {
  11559. this._gl.enable(this._gl.DITHER);
  11560. }
  11561. else {
  11562. this._gl.disable(this._gl.DITHER);
  11563. }
  11564. };
  11565. Engine.prototype.setRasterizerState = function (value) {
  11566. if (value) {
  11567. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11568. }
  11569. else {
  11570. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11571. }
  11572. };
  11573. /**
  11574. * stop executing a render loop function and remove it from the execution array
  11575. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11576. */
  11577. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11578. if (!renderFunction) {
  11579. this._activeRenderLoops = [];
  11580. return;
  11581. }
  11582. var index = this._activeRenderLoops.indexOf(renderFunction);
  11583. if (index >= 0) {
  11584. this._activeRenderLoops.splice(index, 1);
  11585. }
  11586. };
  11587. Engine.prototype._renderLoop = function () {
  11588. if (!this._contextWasLost) {
  11589. var shouldRender = true;
  11590. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11591. shouldRender = false;
  11592. }
  11593. if (shouldRender) {
  11594. // Start new frame
  11595. this.beginFrame();
  11596. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11597. var renderFunction = this._activeRenderLoops[index];
  11598. renderFunction();
  11599. }
  11600. // Present
  11601. this.endFrame();
  11602. }
  11603. }
  11604. if (this._activeRenderLoops.length > 0) {
  11605. // Register new frame
  11606. var requester = null;
  11607. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11608. requester = this._vrDisplay;
  11609. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11610. }
  11611. else {
  11612. this._renderingQueueLaunched = false;
  11613. }
  11614. };
  11615. /**
  11616. * Register and execute a render loop. The engine can have more than one render function.
  11617. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11618. * @example
  11619. * engine.runRenderLoop(function () {
  11620. * scene.render()
  11621. * })
  11622. */
  11623. Engine.prototype.runRenderLoop = function (renderFunction) {
  11624. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11625. return;
  11626. }
  11627. this._activeRenderLoops.push(renderFunction);
  11628. if (!this._renderingQueueLaunched) {
  11629. this._renderingQueueLaunched = true;
  11630. this._bindedRenderFunction = this._renderLoop.bind(this);
  11631. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11632. }
  11633. };
  11634. /**
  11635. * Toggle full screen mode.
  11636. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11637. * @param {any} options - an options object to be sent to the requestFullscreen function
  11638. */
  11639. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11640. if (this.isFullscreen) {
  11641. BABYLON.Tools.ExitFullscreen();
  11642. }
  11643. else {
  11644. this._pointerLockRequested = requestPointerLock;
  11645. if (this._renderingCanvas) {
  11646. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11647. }
  11648. }
  11649. };
  11650. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11651. if (stencil === void 0) { stencil = false; }
  11652. this.applyStates();
  11653. var mode = 0;
  11654. if (backBuffer && color) {
  11655. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11656. mode |= this._gl.COLOR_BUFFER_BIT;
  11657. }
  11658. if (depth) {
  11659. this._gl.clearDepth(1.0);
  11660. mode |= this._gl.DEPTH_BUFFER_BIT;
  11661. }
  11662. if (stencil) {
  11663. this._gl.clearStencil(0);
  11664. mode |= this._gl.STENCIL_BUFFER_BIT;
  11665. }
  11666. this._gl.clear(mode);
  11667. };
  11668. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11669. var gl = this._gl;
  11670. // Save state
  11671. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11672. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11673. // Change state
  11674. gl.enable(gl.SCISSOR_TEST);
  11675. gl.scissor(x, y, width, height);
  11676. // Clear
  11677. this.clear(clearColor, true, true, true);
  11678. // Restore state
  11679. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11680. if (curScissor === true) {
  11681. gl.enable(gl.SCISSOR_TEST);
  11682. }
  11683. else {
  11684. gl.disable(gl.SCISSOR_TEST);
  11685. }
  11686. };
  11687. /**
  11688. * Set the WebGL's viewport
  11689. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11690. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11691. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11692. */
  11693. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11694. var width = requiredWidth || this.getRenderWidth();
  11695. var height = requiredHeight || this.getRenderHeight();
  11696. var x = viewport.x || 0;
  11697. var y = viewport.y || 0;
  11698. this._cachedViewport = viewport;
  11699. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11700. };
  11701. /**
  11702. * Directly set the WebGL Viewport
  11703. * The x, y, width & height are directly passed to the WebGL call
  11704. * @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.
  11705. */
  11706. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11707. var currentViewport = this._cachedViewport;
  11708. this._cachedViewport = null;
  11709. this._gl.viewport(x, y, width, height);
  11710. return currentViewport;
  11711. };
  11712. Engine.prototype.beginFrame = function () {
  11713. this.onBeginFrameObservable.notifyObservers(this);
  11714. this._measureFps();
  11715. };
  11716. Engine.prototype.endFrame = function () {
  11717. //force a flush in case we are using a bad OS.
  11718. if (this._badOS) {
  11719. this.flushFramebuffer();
  11720. }
  11721. //submit frame to the vr device, if enabled
  11722. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11723. // TODO: We should only submit the frame if we read frameData successfully.
  11724. this._vrDisplay.submitFrame();
  11725. }
  11726. this.onEndFrameObservable.notifyObservers(this);
  11727. };
  11728. /**
  11729. * resize the view according to the canvas' size.
  11730. * @example
  11731. * window.addEventListener("resize", function () {
  11732. * engine.resize();
  11733. * });
  11734. */
  11735. Engine.prototype.resize = function () {
  11736. // We're not resizing the size of the canvas while in VR mode & presenting
  11737. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11738. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11739. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11740. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11741. }
  11742. };
  11743. /**
  11744. * force a specific size of the canvas
  11745. * @param {number} width - the new canvas' width
  11746. * @param {number} height - the new canvas' height
  11747. */
  11748. Engine.prototype.setSize = function (width, height) {
  11749. if (!this._renderingCanvas) {
  11750. return;
  11751. }
  11752. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11753. return;
  11754. }
  11755. this._renderingCanvas.width = width;
  11756. this._renderingCanvas.height = height;
  11757. for (var index = 0; index < this.scenes.length; index++) {
  11758. var scene = this.scenes[index];
  11759. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11760. var cam = scene.cameras[camIndex];
  11761. cam._currentRenderId = 0;
  11762. }
  11763. }
  11764. if (this.onResizeObservable.hasObservers) {
  11765. this.onResizeObservable.notifyObservers(this);
  11766. }
  11767. };
  11768. // WebVR functions
  11769. Engine.prototype.isVRDevicePresent = function () {
  11770. return !!this._vrDisplay;
  11771. };
  11772. Engine.prototype.getVRDevice = function () {
  11773. return this._vrDisplay;
  11774. };
  11775. /**
  11776. * Initializes a webVR display and starts listening to display change events.
  11777. * The onVRDisplayChangedObservable will be notified upon these changes.
  11778. * @returns The onVRDisplayChangedObservable.
  11779. */
  11780. Engine.prototype.initWebVR = function () {
  11781. this.initWebVRAsync();
  11782. return this.onVRDisplayChangedObservable;
  11783. };
  11784. /**
  11785. * Initializes a webVR display and starts listening to display change events.
  11786. * The onVRDisplayChangedObservable will be notified upon these changes.
  11787. * @returns A promise containing a VRDisplay and if vr is supported.
  11788. */
  11789. Engine.prototype.initWebVRAsync = function () {
  11790. var _this = this;
  11791. var notifyObservers = function () {
  11792. var eventArgs = {
  11793. vrDisplay: _this._vrDisplay,
  11794. vrSupported: _this._vrSupported
  11795. };
  11796. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11797. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11798. };
  11799. if (!this._onVrDisplayConnect) {
  11800. this._onVrDisplayConnect = function (event) {
  11801. _this._vrDisplay = event.display;
  11802. notifyObservers();
  11803. };
  11804. this._onVrDisplayDisconnect = function () {
  11805. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11806. _this._vrDisplay = undefined;
  11807. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11808. notifyObservers();
  11809. };
  11810. this._onVrDisplayPresentChange = function () {
  11811. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11812. };
  11813. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11814. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11815. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11816. }
  11817. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11818. this._webVRInitPromise.then(notifyObservers);
  11819. return this._webVRInitPromise;
  11820. };
  11821. Engine.prototype.enableVR = function () {
  11822. var _this = this;
  11823. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11824. var onResolved = function () {
  11825. _this.onVRRequestPresentComplete.notifyObservers(true);
  11826. _this._onVRFullScreenTriggered();
  11827. };
  11828. var onRejected = function () {
  11829. _this.onVRRequestPresentComplete.notifyObservers(false);
  11830. };
  11831. this.onVRRequestPresentStart.notifyObservers(this);
  11832. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11833. }
  11834. };
  11835. Engine.prototype.disableVR = function () {
  11836. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11837. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11838. }
  11839. };
  11840. Engine.prototype._getVRDisplaysAsync = function () {
  11841. var _this = this;
  11842. return new Promise(function (res, rej) {
  11843. if (navigator.getVRDisplays) {
  11844. navigator.getVRDisplays().then(function (devices) {
  11845. _this._vrSupported = true;
  11846. // note that devices may actually be an empty array. This is fine;
  11847. // we expect this._vrDisplay to be undefined in this case.
  11848. _this._vrDisplay = devices[0];
  11849. res({
  11850. vrDisplay: _this._vrDisplay,
  11851. vrSupported: _this._vrSupported
  11852. });
  11853. });
  11854. }
  11855. else {
  11856. _this._vrDisplay = undefined;
  11857. _this._vrSupported = false;
  11858. res({
  11859. vrDisplay: _this._vrDisplay,
  11860. vrSupported: _this._vrSupported
  11861. });
  11862. }
  11863. });
  11864. };
  11865. /**
  11866. * Binds the frame buffer to the specified texture.
  11867. * @param texture The texture to render to or null for the default canvas
  11868. * @param faceIndex The face of the texture to render to in case of cube texture
  11869. * @param requiredWidth The width of the target to render to
  11870. * @param requiredHeight The height of the target to render to
  11871. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11872. * @param depthStencilTexture The depth stencil texture to use to render
  11873. */
  11874. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11875. if (this._currentRenderTarget) {
  11876. this.unBindFramebuffer(this._currentRenderTarget);
  11877. }
  11878. this._currentRenderTarget = texture;
  11879. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11880. var gl = this._gl;
  11881. if (texture.isCube) {
  11882. if (faceIndex === undefined) {
  11883. faceIndex = 0;
  11884. }
  11885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11886. if (depthStencilTexture) {
  11887. if (depthStencilTexture._generateStencilBuffer) {
  11888. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11889. }
  11890. else {
  11891. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11892. }
  11893. }
  11894. }
  11895. if (this._cachedViewport && !forceFullscreenViewport) {
  11896. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11897. }
  11898. else {
  11899. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11900. }
  11901. this.wipeCaches();
  11902. };
  11903. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11904. if (this._currentFramebuffer !== framebuffer) {
  11905. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11906. this._currentFramebuffer = framebuffer;
  11907. }
  11908. };
  11909. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11910. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11911. this._currentRenderTarget = null;
  11912. // If MSAA, we need to bitblt back to main texture
  11913. var gl = this._gl;
  11914. if (texture._MSAAFramebuffer) {
  11915. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11916. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11917. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11918. }
  11919. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11920. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11921. gl.generateMipmap(gl.TEXTURE_2D);
  11922. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11923. }
  11924. if (onBeforeUnbind) {
  11925. if (texture._MSAAFramebuffer) {
  11926. // Bind the correct framebuffer
  11927. this.bindUnboundFramebuffer(texture._framebuffer);
  11928. }
  11929. onBeforeUnbind();
  11930. }
  11931. this.bindUnboundFramebuffer(null);
  11932. };
  11933. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11934. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11935. this._currentRenderTarget = null;
  11936. // If MSAA, we need to bitblt back to main texture
  11937. var gl = this._gl;
  11938. if (textures[0]._MSAAFramebuffer) {
  11939. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11940. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11941. var attachments = textures[0]._attachments;
  11942. if (!attachments) {
  11943. attachments = new Array(textures.length);
  11944. textures[0]._attachments = attachments;
  11945. }
  11946. for (var i = 0; i < textures.length; i++) {
  11947. var texture = textures[i];
  11948. for (var j = 0; j < attachments.length; j++) {
  11949. attachments[j] = gl.NONE;
  11950. }
  11951. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11952. gl.readBuffer(attachments[i]);
  11953. gl.drawBuffers(attachments);
  11954. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11955. }
  11956. for (var i = 0; i < attachments.length; i++) {
  11957. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11958. }
  11959. gl.drawBuffers(attachments);
  11960. }
  11961. for (var i = 0; i < textures.length; i++) {
  11962. var texture = textures[i];
  11963. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11964. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11965. gl.generateMipmap(gl.TEXTURE_2D);
  11966. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11967. }
  11968. }
  11969. if (onBeforeUnbind) {
  11970. if (textures[0]._MSAAFramebuffer) {
  11971. // Bind the correct framebuffer
  11972. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11973. }
  11974. onBeforeUnbind();
  11975. }
  11976. this.bindUnboundFramebuffer(null);
  11977. };
  11978. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11979. if (texture.generateMipMaps) {
  11980. var gl = this._gl;
  11981. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11982. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11984. }
  11985. };
  11986. Engine.prototype.flushFramebuffer = function () {
  11987. this._gl.flush();
  11988. };
  11989. Engine.prototype.restoreDefaultFramebuffer = function () {
  11990. if (this._currentRenderTarget) {
  11991. this.unBindFramebuffer(this._currentRenderTarget);
  11992. }
  11993. else {
  11994. this.bindUnboundFramebuffer(null);
  11995. }
  11996. if (this._cachedViewport) {
  11997. this.setViewport(this._cachedViewport);
  11998. }
  11999. this.wipeCaches();
  12000. };
  12001. // UBOs
  12002. Engine.prototype.createUniformBuffer = function (elements) {
  12003. var ubo = this._gl.createBuffer();
  12004. if (!ubo) {
  12005. throw new Error("Unable to create uniform buffer");
  12006. }
  12007. this.bindUniformBuffer(ubo);
  12008. if (elements instanceof Float32Array) {
  12009. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12010. }
  12011. else {
  12012. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12013. }
  12014. this.bindUniformBuffer(null);
  12015. ubo.references = 1;
  12016. return ubo;
  12017. };
  12018. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12019. var ubo = this._gl.createBuffer();
  12020. if (!ubo) {
  12021. throw new Error("Unable to create dynamic uniform buffer");
  12022. }
  12023. this.bindUniformBuffer(ubo);
  12024. if (elements instanceof Float32Array) {
  12025. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12026. }
  12027. else {
  12028. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12029. }
  12030. this.bindUniformBuffer(null);
  12031. ubo.references = 1;
  12032. return ubo;
  12033. };
  12034. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12035. this.bindUniformBuffer(uniformBuffer);
  12036. if (offset === undefined) {
  12037. offset = 0;
  12038. }
  12039. if (count === undefined) {
  12040. if (elements instanceof Float32Array) {
  12041. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12042. }
  12043. else {
  12044. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12045. }
  12046. }
  12047. else {
  12048. if (elements instanceof Float32Array) {
  12049. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12050. }
  12051. else {
  12052. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12053. }
  12054. }
  12055. this.bindUniformBuffer(null);
  12056. };
  12057. // VBOs
  12058. Engine.prototype._resetVertexBufferBinding = function () {
  12059. this.bindArrayBuffer(null);
  12060. this._cachedVertexBuffers = null;
  12061. };
  12062. Engine.prototype.createVertexBuffer = function (vertices) {
  12063. var vbo = this._gl.createBuffer();
  12064. if (!vbo) {
  12065. throw new Error("Unable to create vertex buffer");
  12066. }
  12067. this.bindArrayBuffer(vbo);
  12068. if (vertices instanceof Float32Array) {
  12069. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12070. }
  12071. else {
  12072. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12073. }
  12074. this._resetVertexBufferBinding();
  12075. vbo.references = 1;
  12076. return vbo;
  12077. };
  12078. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12079. var vbo = this._gl.createBuffer();
  12080. if (!vbo) {
  12081. throw new Error("Unable to create dynamic vertex buffer");
  12082. }
  12083. this.bindArrayBuffer(vbo);
  12084. if (vertices instanceof Float32Array) {
  12085. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12086. }
  12087. else {
  12088. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12089. }
  12090. this._resetVertexBufferBinding();
  12091. vbo.references = 1;
  12092. return vbo;
  12093. };
  12094. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12095. if (offset === void 0) { offset = 0; }
  12096. // Force cache update
  12097. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12098. this.bindIndexBuffer(indexBuffer);
  12099. var arrayBuffer;
  12100. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12101. arrayBuffer = indices;
  12102. }
  12103. else {
  12104. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12105. }
  12106. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12107. this._resetIndexBufferBinding();
  12108. };
  12109. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12110. this.bindArrayBuffer(vertexBuffer);
  12111. if (offset === undefined) {
  12112. offset = 0;
  12113. }
  12114. if (count === undefined) {
  12115. if (vertices instanceof Float32Array) {
  12116. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12117. }
  12118. else {
  12119. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12120. }
  12121. }
  12122. else {
  12123. if (vertices instanceof Float32Array) {
  12124. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12125. }
  12126. else {
  12127. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12128. }
  12129. }
  12130. this._resetVertexBufferBinding();
  12131. };
  12132. Engine.prototype._resetIndexBufferBinding = function () {
  12133. this.bindIndexBuffer(null);
  12134. this._cachedIndexBuffer = null;
  12135. };
  12136. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12137. var vbo = this._gl.createBuffer();
  12138. if (!vbo) {
  12139. throw new Error("Unable to create index buffer");
  12140. }
  12141. this.bindIndexBuffer(vbo);
  12142. // Check for 32 bits indices
  12143. var arrayBuffer;
  12144. var need32Bits = false;
  12145. if (indices instanceof Uint16Array) {
  12146. arrayBuffer = indices;
  12147. }
  12148. else {
  12149. //check 32 bit support
  12150. if (this._caps.uintIndices) {
  12151. if (indices instanceof Uint32Array) {
  12152. arrayBuffer = indices;
  12153. need32Bits = true;
  12154. }
  12155. else {
  12156. //number[] or Int32Array, check if 32 bit is necessary
  12157. for (var index = 0; index < indices.length; index++) {
  12158. if (indices[index] > 65535) {
  12159. need32Bits = true;
  12160. break;
  12161. }
  12162. }
  12163. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12164. }
  12165. }
  12166. else {
  12167. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12168. arrayBuffer = new Uint16Array(indices);
  12169. }
  12170. }
  12171. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12172. this._resetIndexBufferBinding();
  12173. vbo.references = 1;
  12174. vbo.is32Bits = need32Bits;
  12175. return vbo;
  12176. };
  12177. Engine.prototype.bindArrayBuffer = function (buffer) {
  12178. if (!this._vaoRecordInProgress) {
  12179. this._unbindVertexArrayObject();
  12180. }
  12181. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12182. };
  12183. Engine.prototype.bindUniformBuffer = function (buffer) {
  12184. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12185. };
  12186. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12187. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12188. };
  12189. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12190. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12191. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12192. };
  12193. ;
  12194. Engine.prototype.bindIndexBuffer = function (buffer) {
  12195. if (!this._vaoRecordInProgress) {
  12196. this._unbindVertexArrayObject();
  12197. }
  12198. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12199. };
  12200. Engine.prototype.bindBuffer = function (buffer, target) {
  12201. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12202. this._gl.bindBuffer(target, buffer);
  12203. this._currentBoundBuffer[target] = buffer;
  12204. }
  12205. };
  12206. Engine.prototype.updateArrayBuffer = function (data) {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12208. };
  12209. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12210. var pointer = this._currentBufferPointers[indx];
  12211. var changed = false;
  12212. if (!pointer.active) {
  12213. changed = true;
  12214. pointer.active = true;
  12215. pointer.index = indx;
  12216. pointer.size = size;
  12217. pointer.type = type;
  12218. pointer.normalized = normalized;
  12219. pointer.stride = stride;
  12220. pointer.offset = offset;
  12221. pointer.buffer = buffer;
  12222. }
  12223. else {
  12224. if (pointer.buffer !== buffer) {
  12225. pointer.buffer = buffer;
  12226. changed = true;
  12227. }
  12228. if (pointer.size !== size) {
  12229. pointer.size = size;
  12230. changed = true;
  12231. }
  12232. if (pointer.type !== type) {
  12233. pointer.type = type;
  12234. changed = true;
  12235. }
  12236. if (pointer.normalized !== normalized) {
  12237. pointer.normalized = normalized;
  12238. changed = true;
  12239. }
  12240. if (pointer.stride !== stride) {
  12241. pointer.stride = stride;
  12242. changed = true;
  12243. }
  12244. if (pointer.offset !== offset) {
  12245. pointer.offset = offset;
  12246. changed = true;
  12247. }
  12248. }
  12249. if (changed || this._vaoRecordInProgress) {
  12250. this.bindArrayBuffer(buffer);
  12251. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12252. }
  12253. };
  12254. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12255. if (indexBuffer == null) {
  12256. return;
  12257. }
  12258. if (this._cachedIndexBuffer !== indexBuffer) {
  12259. this._cachedIndexBuffer = indexBuffer;
  12260. this.bindIndexBuffer(indexBuffer);
  12261. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12262. }
  12263. };
  12264. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12265. var attributes = effect.getAttributesNames();
  12266. if (!this._vaoRecordInProgress) {
  12267. this._unbindVertexArrayObject();
  12268. }
  12269. this.unbindAllAttributes();
  12270. for (var index = 0; index < attributes.length; index++) {
  12271. var order = effect.getAttributeLocation(index);
  12272. if (order >= 0) {
  12273. var vertexBuffer = vertexBuffers[attributes[index]];
  12274. if (!vertexBuffer) {
  12275. continue;
  12276. }
  12277. this._gl.enableVertexAttribArray(order);
  12278. if (!this._vaoRecordInProgress) {
  12279. this._vertexAttribArraysEnabled[order] = true;
  12280. }
  12281. var buffer = vertexBuffer.getBuffer();
  12282. if (buffer) {
  12283. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12284. if (vertexBuffer.getIsInstanced()) {
  12285. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12286. if (!this._vaoRecordInProgress) {
  12287. this._currentInstanceLocations.push(order);
  12288. this._currentInstanceBuffers.push(buffer);
  12289. }
  12290. }
  12291. }
  12292. }
  12293. }
  12294. };
  12295. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12296. var vao = this._gl.createVertexArray();
  12297. this._vaoRecordInProgress = true;
  12298. this._gl.bindVertexArray(vao);
  12299. this._mustWipeVertexAttributes = true;
  12300. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12301. this.bindIndexBuffer(indexBuffer);
  12302. this._vaoRecordInProgress = false;
  12303. this._gl.bindVertexArray(null);
  12304. return vao;
  12305. };
  12306. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12307. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12308. this._cachedVertexArrayObject = vertexArrayObject;
  12309. this._gl.bindVertexArray(vertexArrayObject);
  12310. this._cachedVertexBuffers = null;
  12311. this._cachedIndexBuffer = null;
  12312. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12313. this._mustWipeVertexAttributes = true;
  12314. }
  12315. };
  12316. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12317. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12318. this._cachedVertexBuffers = vertexBuffer;
  12319. this._cachedEffectForVertexBuffers = effect;
  12320. var attributesCount = effect.getAttributesCount();
  12321. this._unbindVertexArrayObject();
  12322. this.unbindAllAttributes();
  12323. var offset = 0;
  12324. for (var index = 0; index < attributesCount; index++) {
  12325. if (index < vertexDeclaration.length) {
  12326. var order = effect.getAttributeLocation(index);
  12327. if (order >= 0) {
  12328. this._gl.enableVertexAttribArray(order);
  12329. this._vertexAttribArraysEnabled[order] = true;
  12330. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12331. }
  12332. offset += vertexDeclaration[index] * 4;
  12333. }
  12334. }
  12335. }
  12336. this._bindIndexBufferWithCache(indexBuffer);
  12337. };
  12338. Engine.prototype._unbindVertexArrayObject = function () {
  12339. if (!this._cachedVertexArrayObject) {
  12340. return;
  12341. }
  12342. this._cachedVertexArrayObject = null;
  12343. this._gl.bindVertexArray(null);
  12344. };
  12345. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12346. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12347. this._cachedVertexBuffers = vertexBuffers;
  12348. this._cachedEffectForVertexBuffers = effect;
  12349. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12350. }
  12351. this._bindIndexBufferWithCache(indexBuffer);
  12352. };
  12353. Engine.prototype.unbindInstanceAttributes = function () {
  12354. var boundBuffer;
  12355. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12356. var instancesBuffer = this._currentInstanceBuffers[i];
  12357. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12358. boundBuffer = instancesBuffer;
  12359. this.bindArrayBuffer(instancesBuffer);
  12360. }
  12361. var offsetLocation = this._currentInstanceLocations[i];
  12362. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12363. }
  12364. this._currentInstanceBuffers.length = 0;
  12365. this._currentInstanceLocations.length = 0;
  12366. };
  12367. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12368. this._gl.deleteVertexArray(vao);
  12369. };
  12370. Engine.prototype._releaseBuffer = function (buffer) {
  12371. buffer.references--;
  12372. if (buffer.references === 0) {
  12373. this._gl.deleteBuffer(buffer);
  12374. return true;
  12375. }
  12376. return false;
  12377. };
  12378. Engine.prototype.createInstancesBuffer = function (capacity) {
  12379. var buffer = this._gl.createBuffer();
  12380. if (!buffer) {
  12381. throw new Error("Unable to create instance buffer");
  12382. }
  12383. buffer.capacity = capacity;
  12384. this.bindArrayBuffer(buffer);
  12385. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12386. return buffer;
  12387. };
  12388. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12389. this._gl.deleteBuffer(buffer);
  12390. };
  12391. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12392. this.bindArrayBuffer(instancesBuffer);
  12393. if (data) {
  12394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12395. }
  12396. if (offsetLocations[0].index !== undefined) {
  12397. var stride = 0;
  12398. for (var i = 0; i < offsetLocations.length; i++) {
  12399. var ai = offsetLocations[i];
  12400. stride += ai.attributeSize * 4;
  12401. }
  12402. for (var i = 0; i < offsetLocations.length; i++) {
  12403. var ai = offsetLocations[i];
  12404. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12405. this._gl.enableVertexAttribArray(ai.index);
  12406. this._vertexAttribArraysEnabled[ai.index] = true;
  12407. }
  12408. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12409. this._gl.vertexAttribDivisor(ai.index, 1);
  12410. this._currentInstanceLocations.push(ai.index);
  12411. this._currentInstanceBuffers.push(instancesBuffer);
  12412. }
  12413. }
  12414. else {
  12415. for (var index = 0; index < 4; index++) {
  12416. var offsetLocation = offsetLocations[index];
  12417. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12418. this._gl.enableVertexAttribArray(offsetLocation);
  12419. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12420. }
  12421. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12422. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12423. this._currentInstanceLocations.push(offsetLocation);
  12424. this._currentInstanceBuffers.push(instancesBuffer);
  12425. }
  12426. }
  12427. };
  12428. Engine.prototype.applyStates = function () {
  12429. this._depthCullingState.apply(this._gl);
  12430. this._stencilState.apply(this._gl);
  12431. this._alphaState.apply(this._gl);
  12432. };
  12433. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12434. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12435. };
  12436. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12437. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12438. };
  12439. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12440. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12441. };
  12442. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12443. // Apply states
  12444. this.applyStates();
  12445. this._drawCalls.addCount(1, false);
  12446. // Render
  12447. var drawMode = this.DrawMode(fillMode);
  12448. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12449. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12450. if (instancesCount) {
  12451. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12452. }
  12453. else {
  12454. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12455. }
  12456. };
  12457. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12458. // Apply states
  12459. this.applyStates();
  12460. this._drawCalls.addCount(1, false);
  12461. var drawMode = this.DrawMode(fillMode);
  12462. if (instancesCount) {
  12463. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12464. }
  12465. else {
  12466. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12467. }
  12468. };
  12469. Engine.prototype.DrawMode = function (fillMode) {
  12470. switch (fillMode) {
  12471. // Triangle views
  12472. case BABYLON.Material.TriangleFillMode:
  12473. return this._gl.TRIANGLES;
  12474. case BABYLON.Material.PointFillMode:
  12475. return this._gl.POINTS;
  12476. case BABYLON.Material.WireFrameFillMode:
  12477. return this._gl.LINES;
  12478. // Draw modes
  12479. case BABYLON.Material.PointListDrawMode:
  12480. return this._gl.POINTS;
  12481. case BABYLON.Material.LineListDrawMode:
  12482. return this._gl.LINES;
  12483. case BABYLON.Material.LineLoopDrawMode:
  12484. return this._gl.LINE_LOOP;
  12485. case BABYLON.Material.LineStripDrawMode:
  12486. return this._gl.LINE_STRIP;
  12487. case BABYLON.Material.TriangleStripDrawMode:
  12488. return this._gl.TRIANGLE_STRIP;
  12489. case BABYLON.Material.TriangleFanDrawMode:
  12490. return this._gl.TRIANGLE_FAN;
  12491. default:
  12492. return this._gl.TRIANGLES;
  12493. }
  12494. };
  12495. // Shaders
  12496. Engine.prototype._releaseEffect = function (effect) {
  12497. if (this._compiledEffects[effect._key]) {
  12498. delete this._compiledEffects[effect._key];
  12499. this._deleteProgram(effect.getProgram());
  12500. }
  12501. };
  12502. Engine.prototype._deleteProgram = function (program) {
  12503. if (program) {
  12504. program.__SPECTOR_rebuildProgram = null;
  12505. if (program.transformFeedback) {
  12506. this.deleteTransformFeedback(program.transformFeedback);
  12507. program.transformFeedback = null;
  12508. }
  12509. this._gl.deleteProgram(program);
  12510. }
  12511. };
  12512. /**
  12513. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12514. * @param samplers An array of string used to represent textures
  12515. */
  12516. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12517. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12518. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12519. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12520. if (this._compiledEffects[name]) {
  12521. var compiledEffect = this._compiledEffects[name];
  12522. if (onCompiled && compiledEffect.isReady()) {
  12523. onCompiled(compiledEffect);
  12524. }
  12525. return compiledEffect;
  12526. }
  12527. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12528. effect._key = name;
  12529. this._compiledEffects[name] = effect;
  12530. return effect;
  12531. };
  12532. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12533. if (uniformsNames === void 0) { uniformsNames = []; }
  12534. if (samplers === void 0) { samplers = []; }
  12535. if (defines === void 0) { defines = ""; }
  12536. return this.createEffect({
  12537. vertex: "particles",
  12538. fragmentElement: fragmentName
  12539. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12540. };
  12541. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12542. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12543. context = context || this._gl;
  12544. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12545. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12546. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12547. };
  12548. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12549. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12550. context = context || this._gl;
  12551. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12552. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12553. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12554. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12555. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12556. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12557. return program;
  12558. };
  12559. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12560. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12561. var shaderProgram = context.createProgram();
  12562. if (!shaderProgram) {
  12563. throw new Error("Unable to create program");
  12564. }
  12565. context.attachShader(shaderProgram, vertexShader);
  12566. context.attachShader(shaderProgram, fragmentShader);
  12567. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12568. var transformFeedback = this.createTransformFeedback();
  12569. this.bindTransformFeedback(transformFeedback);
  12570. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12571. shaderProgram.transformFeedback = transformFeedback;
  12572. }
  12573. context.linkProgram(shaderProgram);
  12574. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12575. this.bindTransformFeedback(null);
  12576. }
  12577. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12578. if (!linked) {
  12579. context.validateProgram(shaderProgram);
  12580. var error = context.getProgramInfoLog(shaderProgram);
  12581. if (error) {
  12582. throw new Error(error);
  12583. }
  12584. }
  12585. context.deleteShader(vertexShader);
  12586. context.deleteShader(fragmentShader);
  12587. return shaderProgram;
  12588. };
  12589. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12590. var results = new Array();
  12591. for (var index = 0; index < uniformsNames.length; index++) {
  12592. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12593. }
  12594. return results;
  12595. };
  12596. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12597. var results = [];
  12598. for (var index = 0; index < attributesNames.length; index++) {
  12599. try {
  12600. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12601. }
  12602. catch (e) {
  12603. results.push(-1);
  12604. }
  12605. }
  12606. return results;
  12607. };
  12608. Engine.prototype.enableEffect = function (effect) {
  12609. if (!effect) {
  12610. return;
  12611. }
  12612. // Use program
  12613. this.bindSamplers(effect);
  12614. this._currentEffect = effect;
  12615. if (effect.onBind) {
  12616. effect.onBind(effect);
  12617. }
  12618. effect.onBindObservable.notifyObservers(effect);
  12619. };
  12620. Engine.prototype.setIntArray = function (uniform, array) {
  12621. if (!uniform)
  12622. return;
  12623. this._gl.uniform1iv(uniform, array);
  12624. };
  12625. Engine.prototype.setIntArray2 = function (uniform, array) {
  12626. if (!uniform || array.length % 2 !== 0)
  12627. return;
  12628. this._gl.uniform2iv(uniform, array);
  12629. };
  12630. Engine.prototype.setIntArray3 = function (uniform, array) {
  12631. if (!uniform || array.length % 3 !== 0)
  12632. return;
  12633. this._gl.uniform3iv(uniform, array);
  12634. };
  12635. Engine.prototype.setIntArray4 = function (uniform, array) {
  12636. if (!uniform || array.length % 4 !== 0)
  12637. return;
  12638. this._gl.uniform4iv(uniform, array);
  12639. };
  12640. Engine.prototype.setFloatArray = function (uniform, array) {
  12641. if (!uniform)
  12642. return;
  12643. this._gl.uniform1fv(uniform, array);
  12644. };
  12645. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12646. if (!uniform || array.length % 2 !== 0)
  12647. return;
  12648. this._gl.uniform2fv(uniform, array);
  12649. };
  12650. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12651. if (!uniform || array.length % 3 !== 0)
  12652. return;
  12653. this._gl.uniform3fv(uniform, array);
  12654. };
  12655. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12656. if (!uniform || array.length % 4 !== 0)
  12657. return;
  12658. this._gl.uniform4fv(uniform, array);
  12659. };
  12660. Engine.prototype.setArray = function (uniform, array) {
  12661. if (!uniform)
  12662. return;
  12663. this._gl.uniform1fv(uniform, array);
  12664. };
  12665. Engine.prototype.setArray2 = function (uniform, array) {
  12666. if (!uniform || array.length % 2 !== 0)
  12667. return;
  12668. this._gl.uniform2fv(uniform, array);
  12669. };
  12670. Engine.prototype.setArray3 = function (uniform, array) {
  12671. if (!uniform || array.length % 3 !== 0)
  12672. return;
  12673. this._gl.uniform3fv(uniform, array);
  12674. };
  12675. Engine.prototype.setArray4 = function (uniform, array) {
  12676. if (!uniform || array.length % 4 !== 0)
  12677. return;
  12678. this._gl.uniform4fv(uniform, array);
  12679. };
  12680. Engine.prototype.setMatrices = function (uniform, matrices) {
  12681. if (!uniform)
  12682. return;
  12683. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12684. };
  12685. Engine.prototype.setMatrix = function (uniform, matrix) {
  12686. if (!uniform)
  12687. return;
  12688. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12689. };
  12690. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12691. if (!uniform)
  12692. return;
  12693. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12694. };
  12695. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12696. if (!uniform)
  12697. return;
  12698. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12699. };
  12700. Engine.prototype.setInt = function (uniform, value) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform1i(uniform, value);
  12704. };
  12705. Engine.prototype.setFloat = function (uniform, value) {
  12706. if (!uniform)
  12707. return;
  12708. this._gl.uniform1f(uniform, value);
  12709. };
  12710. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12711. if (!uniform)
  12712. return;
  12713. this._gl.uniform2f(uniform, x, y);
  12714. };
  12715. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12716. if (!uniform)
  12717. return;
  12718. this._gl.uniform3f(uniform, x, y, z);
  12719. };
  12720. Engine.prototype.setBool = function (uniform, bool) {
  12721. if (!uniform)
  12722. return;
  12723. this._gl.uniform1i(uniform, bool);
  12724. };
  12725. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12726. if (!uniform)
  12727. return;
  12728. this._gl.uniform4f(uniform, x, y, z, w);
  12729. };
  12730. Engine.prototype.setColor3 = function (uniform, color3) {
  12731. if (!uniform)
  12732. return;
  12733. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12734. };
  12735. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12736. if (!uniform)
  12737. return;
  12738. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12739. };
  12740. /**
  12741. * Sets a Color4 on a uniform variable
  12742. * @param uniform defines the uniform location
  12743. * @param color4 defines the value to be set
  12744. */
  12745. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12746. if (!uniform)
  12747. return;
  12748. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12749. };
  12750. // States
  12751. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12752. if (zOffset === void 0) { zOffset = 0; }
  12753. if (reverseSide === void 0) { reverseSide = false; }
  12754. // Culling
  12755. if (this._depthCullingState.cull !== culling || force) {
  12756. this._depthCullingState.cull = culling;
  12757. }
  12758. // Cull face
  12759. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12760. if (this._depthCullingState.cullFace !== cullFace || force) {
  12761. this._depthCullingState.cullFace = cullFace;
  12762. }
  12763. // Z offset
  12764. this.setZOffset(zOffset);
  12765. // Front face
  12766. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12767. if (this._depthCullingState.frontFace !== frontFace || force) {
  12768. this._depthCullingState.frontFace = frontFace;
  12769. }
  12770. };
  12771. Engine.prototype.setZOffset = function (value) {
  12772. this._depthCullingState.zOffset = value;
  12773. };
  12774. Engine.prototype.getZOffset = function () {
  12775. return this._depthCullingState.zOffset;
  12776. };
  12777. Engine.prototype.setDepthBuffer = function (enable) {
  12778. this._depthCullingState.depthTest = enable;
  12779. };
  12780. Engine.prototype.getDepthWrite = function () {
  12781. return this._depthCullingState.depthMask;
  12782. };
  12783. Engine.prototype.setDepthWrite = function (enable) {
  12784. this._depthCullingState.depthMask = enable;
  12785. };
  12786. Engine.prototype.setColorWrite = function (enable) {
  12787. this._gl.colorMask(enable, enable, enable, enable);
  12788. this._colorWrite = enable;
  12789. };
  12790. Engine.prototype.getColorWrite = function () {
  12791. return this._colorWrite;
  12792. };
  12793. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12794. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12795. };
  12796. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12797. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12798. if (this._alphaMode === mode) {
  12799. return;
  12800. }
  12801. switch (mode) {
  12802. case Engine.ALPHA_DISABLE:
  12803. this._alphaState.alphaBlend = false;
  12804. break;
  12805. case Engine.ALPHA_PREMULTIPLIED:
  12806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12807. this._alphaState.alphaBlend = true;
  12808. break;
  12809. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12811. this._alphaState.alphaBlend = true;
  12812. break;
  12813. case Engine.ALPHA_COMBINE:
  12814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12815. this._alphaState.alphaBlend = true;
  12816. break;
  12817. case Engine.ALPHA_ONEONE:
  12818. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12819. this._alphaState.alphaBlend = true;
  12820. break;
  12821. case Engine.ALPHA_ADD:
  12822. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12823. this._alphaState.alphaBlend = true;
  12824. break;
  12825. case Engine.ALPHA_SUBTRACT:
  12826. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12827. this._alphaState.alphaBlend = true;
  12828. break;
  12829. case Engine.ALPHA_MULTIPLY:
  12830. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12831. this._alphaState.alphaBlend = true;
  12832. break;
  12833. case Engine.ALPHA_MAXIMIZED:
  12834. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12835. this._alphaState.alphaBlend = true;
  12836. break;
  12837. case Engine.ALPHA_INTERPOLATE:
  12838. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12839. this._alphaState.alphaBlend = true;
  12840. break;
  12841. case Engine.ALPHA_SCREENMODE:
  12842. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12843. this._alphaState.alphaBlend = true;
  12844. break;
  12845. }
  12846. if (!noDepthWriteChange) {
  12847. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12848. }
  12849. this._alphaMode = mode;
  12850. };
  12851. Engine.prototype.getAlphaMode = function () {
  12852. return this._alphaMode;
  12853. };
  12854. // Textures
  12855. Engine.prototype.wipeCaches = function (bruteForce) {
  12856. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12857. return;
  12858. }
  12859. this._currentEffect = null;
  12860. // 6/8/2017: deltakosh: Should not be required anymore.
  12861. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12862. if (bruteForce) {
  12863. this.resetTextureCache();
  12864. this._currentProgram = null;
  12865. this._stencilState.reset();
  12866. this._depthCullingState.reset();
  12867. this.setDepthFunctionToLessOrEqual();
  12868. this._alphaState.reset();
  12869. }
  12870. this._resetVertexBufferBinding();
  12871. this._cachedIndexBuffer = null;
  12872. this._cachedEffectForVertexBuffers = null;
  12873. this._unbindVertexArrayObject();
  12874. this.bindIndexBuffer(null);
  12875. };
  12876. /**
  12877. * Set the compressed texture format to use, based on the formats you have, and the formats
  12878. * supported by the hardware / browser.
  12879. *
  12880. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12881. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12882. * to API arguments needed to compressed textures. This puts the burden on the container
  12883. * generator to house the arcane code for determining these for current & future formats.
  12884. *
  12885. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12886. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12887. *
  12888. * Note: The result of this call is not taken into account when a texture is base64.
  12889. *
  12890. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12891. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12892. *
  12893. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12894. * @returns The extension selected.
  12895. */
  12896. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12897. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12898. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12899. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12900. return this._textureFormatInUse = this._texturesSupported[i];
  12901. }
  12902. }
  12903. }
  12904. // actively set format to nothing, to allow this to be called more than once
  12905. // and possibly fail the 2nd time
  12906. this._textureFormatInUse = null;
  12907. return null;
  12908. };
  12909. Engine.prototype._createTexture = function () {
  12910. var texture = this._gl.createTexture();
  12911. if (!texture) {
  12912. throw new Error("Unable to create texture");
  12913. }
  12914. return texture;
  12915. };
  12916. /**
  12917. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12918. * @param {string} urlArg- This contains one of the following:
  12919. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12920. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12921. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12922. *
  12923. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12924. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12925. * @param {Scene} scene- Needed for loading to the correct scene.
  12926. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12927. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12928. * @param {callback} onError- Optional callback to be called upon failure.
  12929. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12930. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12931. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12932. *
  12933. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12934. */
  12935. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12936. var _this = this;
  12937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12938. if (onLoad === void 0) { onLoad = null; }
  12939. if (onError === void 0) { onError = null; }
  12940. if (buffer === void 0) { buffer = null; }
  12941. if (fallBack === void 0) { fallBack = null; }
  12942. if (format === void 0) { format = null; }
  12943. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12944. var fromData = url.substr(0, 5) === "data:";
  12945. var fromBlob = url.substr(0, 5) === "blob:";
  12946. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12947. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12948. // establish the file extension, if possible
  12949. var lastDot = url.lastIndexOf('.');
  12950. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12951. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12952. var isTGA = (extension.indexOf(".tga") === 0);
  12953. // determine if a ktx file should be substituted
  12954. var isKTX = false;
  12955. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12956. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12957. isKTX = true;
  12958. }
  12959. if (scene) {
  12960. scene._addPendingData(texture);
  12961. }
  12962. texture.url = url;
  12963. texture.generateMipMaps = !noMipmap;
  12964. texture.samplingMode = samplingMode;
  12965. texture.invertY = invertY;
  12966. if (!this._doNotHandleContextLost) {
  12967. // Keep a link to the buffer only if we plan to handle context lost
  12968. texture._buffer = buffer;
  12969. }
  12970. var onLoadObserver = null;
  12971. if (onLoad && !fallBack) {
  12972. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12973. }
  12974. if (!fallBack)
  12975. this._internalTexturesCache.push(texture);
  12976. var onerror = function (message, exception) {
  12977. if (scene) {
  12978. scene._removePendingData(texture);
  12979. }
  12980. if (onLoadObserver) {
  12981. texture.onLoadedObservable.remove(onLoadObserver);
  12982. }
  12983. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12984. if (isKTX) {
  12985. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12986. }
  12987. else if (BABYLON.Tools.UseFallbackTexture) {
  12988. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12989. }
  12990. if (onError) {
  12991. onError(message || "Unknown error", exception);
  12992. }
  12993. };
  12994. var callback = null;
  12995. // processing for non-image formats
  12996. if (isKTX || isTGA || isDDS) {
  12997. if (isKTX) {
  12998. callback = function (data) {
  12999. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13000. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13001. ktx.uploadLevels(_this._gl, !noMipmap);
  13002. return false;
  13003. }, samplingMode);
  13004. };
  13005. }
  13006. else if (isTGA) {
  13007. callback = function (arrayBuffer) {
  13008. var data = new Uint8Array(arrayBuffer);
  13009. var header = BABYLON.TGATools.GetTGAHeader(data);
  13010. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13011. BABYLON.TGATools.UploadContent(_this._gl, data);
  13012. return false;
  13013. }, samplingMode);
  13014. };
  13015. }
  13016. else if (isDDS) {
  13017. callback = function (data) {
  13018. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13019. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13020. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13021. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13022. return false;
  13023. }, samplingMode);
  13024. };
  13025. }
  13026. if (!buffer) {
  13027. this._loadFile(url, function (data) {
  13028. if (callback) {
  13029. callback(data);
  13030. }
  13031. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13032. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13033. });
  13034. }
  13035. else {
  13036. if (callback) {
  13037. callback(buffer);
  13038. }
  13039. }
  13040. // image format processing
  13041. }
  13042. else {
  13043. var onload = function (img) {
  13044. if (fromBlob && !_this._doNotHandleContextLost) {
  13045. // We need to store the image if we need to rebuild the texture
  13046. // in case of a webgl context lost
  13047. texture._buffer = img;
  13048. }
  13049. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13050. var gl = _this._gl;
  13051. var isPot = (img.width === potWidth && img.height === potHeight);
  13052. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13053. if (isPot) {
  13054. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13055. return false;
  13056. }
  13057. // Using shaders to rescale because canvas.drawImage is lossy
  13058. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13059. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13060. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13065. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13066. _this._releaseTexture(source);
  13067. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13068. continuationCallback();
  13069. });
  13070. return true;
  13071. }, samplingMode);
  13072. };
  13073. if (!fromData || isBase64)
  13074. if (buffer instanceof HTMLImageElement) {
  13075. onload(buffer);
  13076. }
  13077. else {
  13078. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13079. }
  13080. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13081. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13082. else
  13083. onload(buffer);
  13084. }
  13085. return texture;
  13086. };
  13087. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13088. var _this = this;
  13089. var rtt = this.createRenderTargetTexture({
  13090. width: destination.width,
  13091. height: destination.height,
  13092. }, {
  13093. generateMipMaps: false,
  13094. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13095. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13096. generateDepthBuffer: false,
  13097. generateStencilBuffer: false
  13098. });
  13099. if (!this._rescalePostProcess) {
  13100. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13101. }
  13102. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13103. _this._rescalePostProcess.onApply = function (effect) {
  13104. effect._bindTexture("textureSampler", source);
  13105. };
  13106. var hostingScene = scene;
  13107. if (!hostingScene) {
  13108. hostingScene = _this.scenes[_this.scenes.length - 1];
  13109. }
  13110. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13111. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13112. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13113. _this.unBindFramebuffer(rtt);
  13114. _this._releaseTexture(rtt);
  13115. if (onComplete) {
  13116. onComplete();
  13117. }
  13118. });
  13119. };
  13120. Engine.prototype._getInternalFormat = function (format) {
  13121. var internalFormat = this._gl.RGBA;
  13122. switch (format) {
  13123. case Engine.TEXTUREFORMAT_ALPHA:
  13124. internalFormat = this._gl.ALPHA;
  13125. break;
  13126. case Engine.TEXTUREFORMAT_LUMINANCE:
  13127. internalFormat = this._gl.LUMINANCE;
  13128. break;
  13129. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13130. internalFormat = this._gl.LUMINANCE_ALPHA;
  13131. break;
  13132. case Engine.TEXTUREFORMAT_RGB:
  13133. case Engine.TEXTUREFORMAT_RGB32F:
  13134. internalFormat = this._gl.RGB;
  13135. break;
  13136. case Engine.TEXTUREFORMAT_RGBA:
  13137. case Engine.TEXTUREFORMAT_RGBA32F:
  13138. internalFormat = this._gl.RGBA;
  13139. break;
  13140. case Engine.TEXTUREFORMAT_R32F:
  13141. internalFormat = this._gl.RED;
  13142. break;
  13143. case Engine.TEXTUREFORMAT_RG32F:
  13144. internalFormat = this._gl.RG;
  13145. break;
  13146. }
  13147. return internalFormat;
  13148. };
  13149. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13150. if (compression === void 0) { compression = null; }
  13151. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13152. if (!texture) {
  13153. return;
  13154. }
  13155. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13156. var internalFormat = this._getInternalFormat(format);
  13157. var textureType = this._getWebGLTextureType(type);
  13158. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13160. if (!this._doNotHandleContextLost) {
  13161. texture._bufferView = data;
  13162. texture.format = format;
  13163. texture.type = type;
  13164. texture.invertY = invertY;
  13165. texture._compression = compression;
  13166. }
  13167. if (texture.width % 4 !== 0) {
  13168. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13169. }
  13170. if (compression && data) {
  13171. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13172. }
  13173. else {
  13174. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13175. }
  13176. if (texture.generateMipMaps) {
  13177. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13178. }
  13179. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13180. // this.resetTextureCache();
  13181. texture.isReady = true;
  13182. };
  13183. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13184. if (compression === void 0) { compression = null; }
  13185. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13187. texture.baseWidth = width;
  13188. texture.baseHeight = height;
  13189. texture.width = width;
  13190. texture.height = height;
  13191. texture.format = format;
  13192. texture.generateMipMaps = generateMipMaps;
  13193. texture.samplingMode = samplingMode;
  13194. texture.invertY = invertY;
  13195. texture._compression = compression;
  13196. texture.type = type;
  13197. if (!this._doNotHandleContextLost) {
  13198. texture._bufferView = data;
  13199. }
  13200. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13201. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13202. // Filters
  13203. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13206. if (generateMipMaps) {
  13207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13208. }
  13209. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13210. this._internalTexturesCache.push(texture);
  13211. return texture;
  13212. };
  13213. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13214. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13215. texture.baseWidth = width;
  13216. texture.baseHeight = height;
  13217. if (generateMipMaps) {
  13218. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13219. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13220. }
  13221. // this.resetTextureCache();
  13222. texture.width = width;
  13223. texture.height = height;
  13224. texture.isReady = false;
  13225. texture.generateMipMaps = generateMipMaps;
  13226. texture.samplingMode = samplingMode;
  13227. this.updateTextureSamplingMode(samplingMode, texture);
  13228. this._internalTexturesCache.push(texture);
  13229. return texture;
  13230. };
  13231. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13232. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13233. if (texture.isCube) {
  13234. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13235. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13236. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13237. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13238. }
  13239. else if (texture.is3D) {
  13240. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13241. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13242. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13243. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13244. }
  13245. else {
  13246. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13248. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13250. }
  13251. texture.samplingMode = samplingMode;
  13252. };
  13253. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13254. if (premulAlpha === void 0) { premulAlpha = false; }
  13255. if (!texture) {
  13256. return;
  13257. }
  13258. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13259. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13260. if (premulAlpha) {
  13261. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13262. }
  13263. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13264. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13265. if (texture.generateMipMaps) {
  13266. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13267. }
  13268. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13269. if (premulAlpha) {
  13270. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13271. }
  13272. texture.isReady = true;
  13273. };
  13274. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13275. if (!texture || texture._isDisabled) {
  13276. return;
  13277. }
  13278. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13279. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13280. try {
  13281. // Testing video texture support
  13282. if (this._videoTextureSupported === undefined) {
  13283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13284. if (this._gl.getError() !== 0) {
  13285. this._videoTextureSupported = false;
  13286. }
  13287. else {
  13288. this._videoTextureSupported = true;
  13289. }
  13290. }
  13291. // Copy video through the current working canvas if video texture is not supported
  13292. if (!this._videoTextureSupported) {
  13293. if (!texture._workingCanvas) {
  13294. texture._workingCanvas = document.createElement("canvas");
  13295. var context = texture._workingCanvas.getContext("2d");
  13296. if (!context) {
  13297. throw new Error("Unable to get 2d context");
  13298. }
  13299. texture._workingContext = context;
  13300. texture._workingCanvas.width = texture.width;
  13301. texture._workingCanvas.height = texture.height;
  13302. }
  13303. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13304. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13305. }
  13306. else {
  13307. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13308. }
  13309. if (texture.generateMipMaps) {
  13310. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13311. }
  13312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13313. // this.resetTextureCache();
  13314. texture.isReady = true;
  13315. }
  13316. catch (ex) {
  13317. // Something unexpected
  13318. // Let's disable the texture
  13319. texture._isDisabled = true;
  13320. }
  13321. };
  13322. /**
  13323. * Updates a depth texture Comparison Mode and Function.
  13324. * If the comparison Function is equal to 0, the mode will be set to none.
  13325. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13326. * @param texture The texture to set the comparison function for
  13327. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13328. */
  13329. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13330. if (this.webGLVersion === 1) {
  13331. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13332. return;
  13333. }
  13334. var gl = this._gl;
  13335. if (texture.isCube) {
  13336. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13337. if (comparisonFunction === 0) {
  13338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13339. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13340. }
  13341. else {
  13342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13343. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13344. }
  13345. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13346. }
  13347. else {
  13348. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13349. if (comparisonFunction === 0) {
  13350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13352. }
  13353. else {
  13354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13356. }
  13357. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13358. }
  13359. texture._comparisonFunction = comparisonFunction;
  13360. };
  13361. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13362. var width = size.width || size;
  13363. var height = size.height || size;
  13364. internalTexture.baseWidth = width;
  13365. internalTexture.baseHeight = height;
  13366. internalTexture.width = width;
  13367. internalTexture.height = height;
  13368. internalTexture.isReady = true;
  13369. internalTexture.samples = 1;
  13370. internalTexture.generateMipMaps = false;
  13371. internalTexture._generateDepthBuffer = true;
  13372. internalTexture._generateStencilBuffer = generateStencil;
  13373. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13374. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13375. internalTexture._comparisonFunction = comparisonFunction;
  13376. var gl = this._gl;
  13377. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13378. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13379. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13380. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13381. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13382. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13383. if (comparisonFunction === 0) {
  13384. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13385. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13386. }
  13387. else {
  13388. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13389. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13390. }
  13391. };
  13392. /**
  13393. * Creates a depth stencil texture.
  13394. * This is only available in WebGL 2 or with the depth texture extension available.
  13395. * @param size The size of face edge in the texture.
  13396. * @param options The options defining the texture.
  13397. * @returns The texture
  13398. */
  13399. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13400. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13401. if (!this._caps.depthTextureExtension) {
  13402. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13403. return internalTexture;
  13404. }
  13405. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13406. var gl = this._gl;
  13407. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13408. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13409. if (this.webGLVersion > 1) {
  13410. if (internalOptions.generateStencil) {
  13411. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13412. }
  13413. else {
  13414. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13415. }
  13416. }
  13417. else {
  13418. if (internalOptions.generateStencil) {
  13419. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13420. }
  13421. else {
  13422. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13423. }
  13424. }
  13425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13426. return internalTexture;
  13427. };
  13428. /**
  13429. * Creates a depth stencil cube texture.
  13430. * This is only available in WebGL 2.
  13431. * @param size The size of face edge in the cube texture.
  13432. * @param options The options defining the cube texture.
  13433. * @returns The cube texture
  13434. */
  13435. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13436. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13437. internalTexture.isCube = true;
  13438. if (this.webGLVersion === 1) {
  13439. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13440. return internalTexture;
  13441. }
  13442. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13443. var gl = this._gl;
  13444. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13445. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13446. // Create the depth/stencil buffer
  13447. for (var face = 0; face < 6; face++) {
  13448. if (internalOptions.generateStencil) {
  13449. 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);
  13450. }
  13451. else {
  13452. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13453. }
  13454. }
  13455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13456. return internalTexture;
  13457. };
  13458. /**
  13459. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13460. * @param renderTarget The render target to set the frame buffer for
  13461. */
  13462. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13463. // Create the framebuffer
  13464. var internalTexture = renderTarget.getInternalTexture();
  13465. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13466. return;
  13467. }
  13468. var gl = this._gl;
  13469. var depthStencilTexture = renderTarget.depthStencilTexture;
  13470. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13471. if (depthStencilTexture.isCube) {
  13472. if (depthStencilTexture._generateStencilBuffer) {
  13473. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13474. }
  13475. else {
  13476. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13477. }
  13478. }
  13479. else {
  13480. if (depthStencilTexture._generateStencilBuffer) {
  13481. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13482. }
  13483. else {
  13484. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13485. }
  13486. }
  13487. this.bindUnboundFramebuffer(null);
  13488. };
  13489. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13490. var fullOptions = new RenderTargetCreationOptions();
  13491. if (options !== undefined && typeof options === "object") {
  13492. fullOptions.generateMipMaps = options.generateMipMaps;
  13493. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13494. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13495. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13496. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13497. }
  13498. else {
  13499. fullOptions.generateMipMaps = options;
  13500. fullOptions.generateDepthBuffer = true;
  13501. fullOptions.generateStencilBuffer = false;
  13502. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13503. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13504. }
  13505. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13506. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13507. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13508. }
  13509. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13510. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13511. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13512. }
  13513. var gl = this._gl;
  13514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13515. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13516. var width = size.width || size;
  13517. var height = size.height || size;
  13518. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13519. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13520. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13521. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13522. }
  13523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13527. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13528. // Create the framebuffer
  13529. var framebuffer = gl.createFramebuffer();
  13530. this.bindUnboundFramebuffer(framebuffer);
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13532. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13533. if (fullOptions.generateMipMaps) {
  13534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13535. }
  13536. // Unbind
  13537. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13538. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13539. this.bindUnboundFramebuffer(null);
  13540. texture._framebuffer = framebuffer;
  13541. texture.baseWidth = width;
  13542. texture.baseHeight = height;
  13543. texture.width = width;
  13544. texture.height = height;
  13545. texture.isReady = true;
  13546. texture.samples = 1;
  13547. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13548. texture.samplingMode = fullOptions.samplingMode;
  13549. texture.type = fullOptions.type;
  13550. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13551. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13552. // this.resetTextureCache();
  13553. this._internalTexturesCache.push(texture);
  13554. return texture;
  13555. };
  13556. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13557. var generateMipMaps = false;
  13558. var generateDepthBuffer = true;
  13559. var generateStencilBuffer = false;
  13560. var generateDepthTexture = false;
  13561. var textureCount = 1;
  13562. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13563. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13564. var types = [], samplingModes = [];
  13565. if (options !== undefined) {
  13566. generateMipMaps = options.generateMipMaps;
  13567. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13568. generateStencilBuffer = options.generateStencilBuffer;
  13569. generateDepthTexture = options.generateDepthTexture;
  13570. textureCount = options.textureCount || 1;
  13571. if (options.types) {
  13572. types = options.types;
  13573. }
  13574. if (options.samplingModes) {
  13575. samplingModes = options.samplingModes;
  13576. }
  13577. }
  13578. var gl = this._gl;
  13579. // Create the framebuffer
  13580. var framebuffer = gl.createFramebuffer();
  13581. this.bindUnboundFramebuffer(framebuffer);
  13582. var width = size.width || size;
  13583. var height = size.height || size;
  13584. var textures = [];
  13585. var attachments = [];
  13586. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13587. for (var i = 0; i < textureCount; i++) {
  13588. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13589. var type = types[i] || defaultType;
  13590. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13591. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13592. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13593. }
  13594. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13595. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13596. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13597. }
  13598. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13599. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13600. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13601. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13602. }
  13603. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13604. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13605. textures.push(texture);
  13606. attachments.push(attachment);
  13607. gl.activeTexture(gl["TEXTURE" + i]);
  13608. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13613. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13614. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13615. if (generateMipMaps) {
  13616. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13617. }
  13618. // Unbind
  13619. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13620. texture._framebuffer = framebuffer;
  13621. texture._depthStencilBuffer = depthStencilBuffer;
  13622. texture.baseWidth = width;
  13623. texture.baseHeight = height;
  13624. texture.width = width;
  13625. texture.height = height;
  13626. texture.isReady = true;
  13627. texture.samples = 1;
  13628. texture.generateMipMaps = generateMipMaps;
  13629. texture.samplingMode = samplingMode;
  13630. texture.type = type;
  13631. texture._generateDepthBuffer = generateDepthBuffer;
  13632. texture._generateStencilBuffer = generateStencilBuffer;
  13633. texture._attachments = attachments;
  13634. this._internalTexturesCache.push(texture);
  13635. }
  13636. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13637. // Depth texture
  13638. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13639. gl.activeTexture(gl.TEXTURE0);
  13640. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13645. 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);
  13646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13647. depthTexture._framebuffer = framebuffer;
  13648. depthTexture.baseWidth = width;
  13649. depthTexture.baseHeight = height;
  13650. depthTexture.width = width;
  13651. depthTexture.height = height;
  13652. depthTexture.isReady = true;
  13653. depthTexture.samples = 1;
  13654. depthTexture.generateMipMaps = generateMipMaps;
  13655. depthTexture.samplingMode = gl.NEAREST;
  13656. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13657. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13658. textures.push(depthTexture);
  13659. this._internalTexturesCache.push(depthTexture);
  13660. }
  13661. gl.drawBuffers(attachments);
  13662. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13663. this.bindUnboundFramebuffer(null);
  13664. this.resetTextureCache();
  13665. return textures;
  13666. };
  13667. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13668. if (samples === void 0) { samples = 1; }
  13669. var depthStencilBuffer = null;
  13670. var gl = this._gl;
  13671. // Create the depth/stencil buffer
  13672. if (generateStencilBuffer) {
  13673. depthStencilBuffer = gl.createRenderbuffer();
  13674. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13675. if (samples > 1) {
  13676. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13677. }
  13678. else {
  13679. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13680. }
  13681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13682. }
  13683. else if (generateDepthBuffer) {
  13684. depthStencilBuffer = gl.createRenderbuffer();
  13685. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13686. if (samples > 1) {
  13687. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13688. }
  13689. else {
  13690. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13691. }
  13692. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13693. }
  13694. return depthStencilBuffer;
  13695. };
  13696. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13697. if (this.webGLVersion < 2 || !texture) {
  13698. return 1;
  13699. }
  13700. if (texture.samples === samples) {
  13701. return samples;
  13702. }
  13703. var gl = this._gl;
  13704. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13705. // Dispose previous render buffers
  13706. if (texture._depthStencilBuffer) {
  13707. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13708. texture._depthStencilBuffer = null;
  13709. }
  13710. if (texture._MSAAFramebuffer) {
  13711. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13712. texture._MSAAFramebuffer = null;
  13713. }
  13714. if (texture._MSAARenderBuffer) {
  13715. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13716. texture._MSAARenderBuffer = null;
  13717. }
  13718. if (samples > 1) {
  13719. var framebuffer = gl.createFramebuffer();
  13720. if (!framebuffer) {
  13721. throw new Error("Unable to create multi sampled framebuffer");
  13722. }
  13723. texture._MSAAFramebuffer = framebuffer;
  13724. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13725. var colorRenderbuffer = gl.createRenderbuffer();
  13726. if (!colorRenderbuffer) {
  13727. throw new Error("Unable to create multi sampled framebuffer");
  13728. }
  13729. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13730. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13731. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13732. texture._MSAARenderBuffer = colorRenderbuffer;
  13733. }
  13734. else {
  13735. this.bindUnboundFramebuffer(texture._framebuffer);
  13736. }
  13737. texture.samples = samples;
  13738. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13739. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13740. this.bindUnboundFramebuffer(null);
  13741. return samples;
  13742. };
  13743. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13744. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13745. return 1;
  13746. }
  13747. if (textures[0].samples === samples) {
  13748. return samples;
  13749. }
  13750. var gl = this._gl;
  13751. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13752. // Dispose previous render buffers
  13753. if (textures[0]._depthStencilBuffer) {
  13754. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13755. textures[0]._depthStencilBuffer = null;
  13756. }
  13757. if (textures[0]._MSAAFramebuffer) {
  13758. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13759. textures[0]._MSAAFramebuffer = null;
  13760. }
  13761. for (var i = 0; i < textures.length; i++) {
  13762. if (textures[i]._MSAARenderBuffer) {
  13763. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13764. textures[i]._MSAARenderBuffer = null;
  13765. }
  13766. }
  13767. if (samples > 1) {
  13768. var framebuffer = gl.createFramebuffer();
  13769. if (!framebuffer) {
  13770. throw new Error("Unable to create multi sampled framebuffer");
  13771. }
  13772. this.bindUnboundFramebuffer(framebuffer);
  13773. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13774. var attachments = [];
  13775. for (var i = 0; i < textures.length; i++) {
  13776. var texture = textures[i];
  13777. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13778. var colorRenderbuffer = gl.createRenderbuffer();
  13779. if (!colorRenderbuffer) {
  13780. throw new Error("Unable to create multi sampled framebuffer");
  13781. }
  13782. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13783. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13784. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13785. texture._MSAAFramebuffer = framebuffer;
  13786. texture._MSAARenderBuffer = colorRenderbuffer;
  13787. texture.samples = samples;
  13788. texture._depthStencilBuffer = depthStencilBuffer;
  13789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13790. attachments.push(attachment);
  13791. }
  13792. gl.drawBuffers(attachments);
  13793. }
  13794. else {
  13795. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13796. }
  13797. this.bindUnboundFramebuffer(null);
  13798. return samples;
  13799. };
  13800. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13801. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13802. };
  13803. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13804. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13805. };
  13806. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13807. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13808. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13809. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13810. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13811. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13812. }
  13813. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13814. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13815. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13816. }
  13817. var gl = this._gl;
  13818. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13819. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13820. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13821. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13822. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13823. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13824. }
  13825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13829. for (var face = 0; face < 6; face++) {
  13830. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13831. }
  13832. // Create the framebuffer
  13833. var framebuffer = gl.createFramebuffer();
  13834. this.bindUnboundFramebuffer(framebuffer);
  13835. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13836. // MipMaps
  13837. if (fullOptions.generateMipMaps) {
  13838. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13839. }
  13840. // Unbind
  13841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13842. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13843. this.bindUnboundFramebuffer(null);
  13844. texture._framebuffer = framebuffer;
  13845. texture.width = size;
  13846. texture.height = size;
  13847. texture.isReady = true;
  13848. texture.isCube = true;
  13849. texture.samples = 1;
  13850. texture.generateMipMaps = fullOptions.generateMipMaps;
  13851. texture.samplingMode = fullOptions.samplingMode;
  13852. texture.type = fullOptions.type;
  13853. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13854. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13855. this._internalTexturesCache.push(texture);
  13856. return texture;
  13857. };
  13858. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13859. var _this = this;
  13860. if (onLoad === void 0) { onLoad = null; }
  13861. if (onError === void 0) { onError = null; }
  13862. if (forcedExtension === void 0) { forcedExtension = null; }
  13863. var callback = function (loadData) {
  13864. if (!loadData) {
  13865. if (onLoad) {
  13866. onLoad(null);
  13867. }
  13868. return;
  13869. }
  13870. var texture = loadData.texture;
  13871. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13872. texture._lodGenerationScale = scale;
  13873. texture._lodGenerationOffset = offset;
  13874. if (_this._caps.textureLOD) {
  13875. // Do not add extra process if texture lod is supported.
  13876. if (onLoad) {
  13877. onLoad(texture);
  13878. }
  13879. return;
  13880. }
  13881. var mipSlices = 3;
  13882. var gl = _this._gl;
  13883. var width = loadData.width;
  13884. if (!width) {
  13885. return;
  13886. }
  13887. var textures = [];
  13888. for (var i = 0; i < mipSlices; i++) {
  13889. //compute LOD from even spacing in smoothness (matching shader calculation)
  13890. var smoothness = i / (mipSlices - 1);
  13891. var roughness = 1 - smoothness;
  13892. var minLODIndex = offset; // roughness = 0
  13893. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13894. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13895. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13896. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13897. glTextureFromLod.isCube = true;
  13898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13903. if (loadData.isDDS) {
  13904. var info = loadData.info;
  13905. var data = loadData.data;
  13906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13907. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13908. }
  13909. else {
  13910. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13911. }
  13912. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13913. // Wrap in a base texture for easy binding.
  13914. var lodTexture = new BABYLON.BaseTexture(scene);
  13915. lodTexture.isCube = true;
  13916. lodTexture._texture = glTextureFromLod;
  13917. glTextureFromLod.isReady = true;
  13918. textures.push(lodTexture);
  13919. }
  13920. texture._lodTextureHigh = textures[2];
  13921. texture._lodTextureMid = textures[1];
  13922. texture._lodTextureLow = textures[0];
  13923. if (onLoad) {
  13924. onLoad(texture);
  13925. }
  13926. };
  13927. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13928. };
  13929. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13930. var _this = this;
  13931. if (onLoad === void 0) { onLoad = null; }
  13932. if (onError === void 0) { onError = null; }
  13933. if (forcedExtension === void 0) { forcedExtension = null; }
  13934. var gl = this._gl;
  13935. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13936. texture.isCube = true;
  13937. texture.url = rootUrl;
  13938. texture.generateMipMaps = !noMipmap;
  13939. if (!this._doNotHandleContextLost) {
  13940. texture._extension = forcedExtension;
  13941. texture._files = files;
  13942. }
  13943. var isKTX = false;
  13944. var isDDS = false;
  13945. var lastDot = rootUrl.lastIndexOf('.');
  13946. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13947. if (this._textureFormatInUse) {
  13948. extension = this._textureFormatInUse;
  13949. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13950. isKTX = true;
  13951. }
  13952. else {
  13953. isDDS = (extension === ".dds");
  13954. }
  13955. var onerror = function (request, exception) {
  13956. if (onError && request) {
  13957. onError(request.status + " " + request.statusText, exception);
  13958. }
  13959. };
  13960. if (isKTX) {
  13961. this._loadFile(rootUrl, function (data) {
  13962. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13963. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13964. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13965. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13966. ktx.uploadLevels(_this._gl, !noMipmap);
  13967. _this.setCubeMapTextureParams(gl, loadMipmap);
  13968. texture.width = ktx.pixelWidth;
  13969. texture.height = ktx.pixelHeight;
  13970. texture.isReady = true;
  13971. }, undefined, undefined, true, onerror);
  13972. }
  13973. else if (isDDS) {
  13974. if (files && files.length === 6) {
  13975. this._cascadeLoadFiles(scene, function (imgs) {
  13976. var info;
  13977. var loadMipmap = false;
  13978. var width = 0;
  13979. for (var index = 0; index < imgs.length; index++) {
  13980. var data = imgs[index];
  13981. info = BABYLON.DDSTools.GetDDSInfo(data);
  13982. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13983. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13984. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13985. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13986. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13987. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13988. }
  13989. texture.width = info.width;
  13990. texture.height = info.height;
  13991. texture.type = info.textureType;
  13992. width = info.width;
  13993. }
  13994. _this.setCubeMapTextureParams(gl, loadMipmap);
  13995. texture.isReady = true;
  13996. if (onLoad) {
  13997. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13998. }
  13999. }, files, onError);
  14000. }
  14001. else {
  14002. this._loadFile(rootUrl, function (data) {
  14003. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14004. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14007. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14008. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14009. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14010. }
  14011. _this.setCubeMapTextureParams(gl, loadMipmap);
  14012. texture.width = info.width;
  14013. texture.height = info.height;
  14014. texture.isReady = true;
  14015. texture.type = info.textureType;
  14016. if (onLoad) {
  14017. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14018. }
  14019. }, undefined, undefined, true, onerror);
  14020. }
  14021. }
  14022. else {
  14023. if (!files) {
  14024. throw new Error("Cannot load cubemap because files were not defined");
  14025. }
  14026. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14027. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14028. var height = width;
  14029. _this._prepareWorkingCanvas();
  14030. if (!_this._workingCanvas || !_this._workingContext) {
  14031. return;
  14032. }
  14033. _this._workingCanvas.width = width;
  14034. _this._workingCanvas.height = height;
  14035. var faces = [
  14036. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14037. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14038. ];
  14039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14040. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14041. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14042. for (var index = 0; index < faces.length; index++) {
  14043. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14044. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14045. }
  14046. if (!noMipmap) {
  14047. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14048. }
  14049. _this.setCubeMapTextureParams(gl, !noMipmap);
  14050. texture.width = width;
  14051. texture.height = height;
  14052. texture.isReady = true;
  14053. if (format) {
  14054. texture.format = format;
  14055. }
  14056. texture.onLoadedObservable.notifyObservers(texture);
  14057. texture.onLoadedObservable.clear();
  14058. if (onLoad) {
  14059. onLoad();
  14060. }
  14061. }, files, onError);
  14062. }
  14063. this._internalTexturesCache.push(texture);
  14064. return texture;
  14065. };
  14066. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14071. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14072. // this.resetTextureCache();
  14073. };
  14074. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14075. if (compression === void 0) { compression = null; }
  14076. if (level === void 0) { level = 0; }
  14077. texture._bufferViewArray = data;
  14078. texture.format = format;
  14079. texture.type = type;
  14080. texture.invertY = invertY;
  14081. texture._compression = compression;
  14082. var gl = this._gl;
  14083. var textureType = this._getWebGLTextureType(type);
  14084. var internalFormat = this._getInternalFormat(format);
  14085. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14086. var needConversion = false;
  14087. if (internalFormat === gl.RGB) {
  14088. internalFormat = gl.RGBA;
  14089. needConversion = true;
  14090. }
  14091. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14092. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14093. if (texture.width % 4 !== 0) {
  14094. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14095. }
  14096. // Data are known to be in +X +Y +Z -X -Y -Z
  14097. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14098. var faceData = data[faceIndex];
  14099. if (compression) {
  14100. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14101. }
  14102. else {
  14103. if (needConversion) {
  14104. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14105. }
  14106. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14107. }
  14108. }
  14109. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14110. if (isPot && texture.generateMipMaps && level === 0) {
  14111. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14112. }
  14113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14114. // this.resetTextureCache();
  14115. texture.isReady = true;
  14116. };
  14117. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14118. if (compression === void 0) { compression = null; }
  14119. var gl = this._gl;
  14120. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14121. texture.isCube = true;
  14122. texture.generateMipMaps = generateMipMaps;
  14123. texture.format = format;
  14124. texture.type = type;
  14125. if (!this._doNotHandleContextLost) {
  14126. texture._bufferViewArray = data;
  14127. }
  14128. var textureType = this._getWebGLTextureType(type);
  14129. var internalFormat = this._getInternalFormat(format);
  14130. if (internalFormat === gl.RGB) {
  14131. internalFormat = gl.RGBA;
  14132. }
  14133. var width = size;
  14134. var height = width;
  14135. texture.width = width;
  14136. texture.height = height;
  14137. // Double check on POT to generate Mips.
  14138. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14139. if (!isPot) {
  14140. generateMipMaps = false;
  14141. }
  14142. // Upload data if needed. The texture won't be ready until then.
  14143. if (data) {
  14144. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14145. }
  14146. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14147. // Filters
  14148. if (data && generateMipMaps) {
  14149. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14150. }
  14151. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14154. }
  14155. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14158. }
  14159. else {
  14160. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14163. }
  14164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14167. return texture;
  14168. };
  14169. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14170. var _this = this;
  14171. if (onLoad === void 0) { onLoad = null; }
  14172. if (onError === void 0) { onError = null; }
  14173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14174. if (invertY === void 0) { invertY = false; }
  14175. var gl = this._gl;
  14176. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14177. scene._addPendingData(texture);
  14178. texture.url = url;
  14179. this._internalTexturesCache.push(texture);
  14180. var onerror = function (request, exception) {
  14181. scene._removePendingData(texture);
  14182. if (onError && request) {
  14183. onError(request.status + " " + request.statusText, exception);
  14184. }
  14185. };
  14186. var internalCallback = function (data) {
  14187. var width = texture.width;
  14188. var faceDataArrays = callback(data);
  14189. if (!faceDataArrays) {
  14190. return;
  14191. }
  14192. if (mipmmapGenerator) {
  14193. var textureType = _this._getWebGLTextureType(type);
  14194. var internalFormat = _this._getInternalFormat(format);
  14195. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14196. var needConversion = false;
  14197. if (internalFormat === gl.RGB) {
  14198. internalFormat = gl.RGBA;
  14199. needConversion = true;
  14200. }
  14201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14203. var mipData = mipmmapGenerator(faceDataArrays);
  14204. for (var level = 0; level < mipData.length; level++) {
  14205. var mipSize = width >> level;
  14206. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14207. var mipFaceData = mipData[level][faceIndex];
  14208. if (needConversion) {
  14209. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14210. }
  14211. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14212. }
  14213. }
  14214. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14215. }
  14216. else {
  14217. texture.generateMipMaps = !noMipmap;
  14218. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14219. }
  14220. texture.isReady = true;
  14221. // this.resetTextureCache();
  14222. scene._removePendingData(texture);
  14223. if (onLoad) {
  14224. onLoad();
  14225. }
  14226. };
  14227. this._loadFile(url, function (data) {
  14228. internalCallback(data);
  14229. }, undefined, scene.database, true, onerror);
  14230. return texture;
  14231. };
  14232. ;
  14233. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14234. if (compression === void 0) { compression = null; }
  14235. var internalFormat = this._getInternalFormat(format);
  14236. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14237. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14238. if (!this._doNotHandleContextLost) {
  14239. texture._bufferView = data;
  14240. texture.format = format;
  14241. texture.invertY = invertY;
  14242. texture._compression = compression;
  14243. }
  14244. if (texture.width % 4 !== 0) {
  14245. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14246. }
  14247. if (compression && data) {
  14248. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14249. }
  14250. else {
  14251. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14252. }
  14253. if (texture.generateMipMaps) {
  14254. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14255. }
  14256. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14257. // this.resetTextureCache();
  14258. texture.isReady = true;
  14259. };
  14260. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14261. if (compression === void 0) { compression = null; }
  14262. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14263. texture.baseWidth = width;
  14264. texture.baseHeight = height;
  14265. texture.baseDepth = depth;
  14266. texture.width = width;
  14267. texture.height = height;
  14268. texture.depth = depth;
  14269. texture.format = format;
  14270. texture.generateMipMaps = generateMipMaps;
  14271. texture.samplingMode = samplingMode;
  14272. texture.is3D = true;
  14273. if (!this._doNotHandleContextLost) {
  14274. texture._bufferView = data;
  14275. }
  14276. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14277. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14278. // Filters
  14279. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14281. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14282. if (generateMipMaps) {
  14283. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14284. }
  14285. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14286. this._internalTexturesCache.push(texture);
  14287. return texture;
  14288. };
  14289. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14290. var gl = this._gl;
  14291. if (!gl) {
  14292. return;
  14293. }
  14294. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14297. if (!noMipmap && !isCompressed) {
  14298. gl.generateMipmap(gl.TEXTURE_2D);
  14299. }
  14300. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14301. // this.resetTextureCache();
  14302. if (scene) {
  14303. scene._removePendingData(texture);
  14304. }
  14305. texture.onLoadedObservable.notifyObservers(texture);
  14306. texture.onLoadedObservable.clear();
  14307. };
  14308. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14309. var _this = this;
  14310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14311. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14312. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14313. var gl = this._gl;
  14314. if (!gl) {
  14315. return;
  14316. }
  14317. if (!texture._webGLTexture) {
  14318. // this.resetTextureCache();
  14319. if (scene) {
  14320. scene._removePendingData(texture);
  14321. }
  14322. return;
  14323. }
  14324. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14325. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14326. texture.baseWidth = width;
  14327. texture.baseHeight = height;
  14328. texture.width = potWidth;
  14329. texture.height = potHeight;
  14330. texture.isReady = true;
  14331. if (processFunction(potWidth, potHeight, function () {
  14332. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14333. })) {
  14334. // Returning as texture needs extra async steps
  14335. return;
  14336. }
  14337. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14338. };
  14339. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14340. // Create new RGBA data container.
  14341. var rgbaData;
  14342. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14343. rgbaData = new Float32Array(width * height * 4);
  14344. }
  14345. else {
  14346. rgbaData = new Uint32Array(width * height * 4);
  14347. }
  14348. // Convert each pixel.
  14349. for (var x = 0; x < width; x++) {
  14350. for (var y = 0; y < height; y++) {
  14351. var index = (y * width + x) * 3;
  14352. var newIndex = (y * width + x) * 4;
  14353. // Map Old Value to new value.
  14354. rgbaData[newIndex + 0] = rgbData[index + 0];
  14355. rgbaData[newIndex + 1] = rgbData[index + 1];
  14356. rgbaData[newIndex + 2] = rgbData[index + 2];
  14357. // Add fully opaque alpha channel.
  14358. rgbaData[newIndex + 3] = 1;
  14359. }
  14360. }
  14361. return rgbaData;
  14362. };
  14363. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14364. var gl = this._gl;
  14365. if (texture._framebuffer) {
  14366. gl.deleteFramebuffer(texture._framebuffer);
  14367. texture._framebuffer = null;
  14368. }
  14369. if (texture._depthStencilBuffer) {
  14370. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14371. texture._depthStencilBuffer = null;
  14372. }
  14373. if (texture._MSAAFramebuffer) {
  14374. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14375. texture._MSAAFramebuffer = null;
  14376. }
  14377. if (texture._MSAARenderBuffer) {
  14378. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14379. texture._MSAARenderBuffer = null;
  14380. }
  14381. };
  14382. Engine.prototype._releaseTexture = function (texture) {
  14383. var gl = this._gl;
  14384. this._releaseFramebufferObjects(texture);
  14385. gl.deleteTexture(texture._webGLTexture);
  14386. // Unbind channels
  14387. this.unbindAllTextures();
  14388. var index = this._internalTexturesCache.indexOf(texture);
  14389. if (index !== -1) {
  14390. this._internalTexturesCache.splice(index, 1);
  14391. }
  14392. // Integrated fixed lod samplers.
  14393. if (texture._lodTextureHigh) {
  14394. texture._lodTextureHigh.dispose();
  14395. }
  14396. if (texture._lodTextureMid) {
  14397. texture._lodTextureMid.dispose();
  14398. }
  14399. if (texture._lodTextureLow) {
  14400. texture._lodTextureLow.dispose();
  14401. }
  14402. };
  14403. Engine.prototype.setProgram = function (program) {
  14404. if (this._currentProgram !== program) {
  14405. this._gl.useProgram(program);
  14406. this._currentProgram = program;
  14407. }
  14408. };
  14409. Engine.prototype.bindSamplers = function (effect) {
  14410. this.setProgram(effect.getProgram());
  14411. var samplers = effect.getSamplers();
  14412. for (var index = 0; index < samplers.length; index++) {
  14413. var uniform = effect.getUniform(samplers[index]);
  14414. if (uniform) {
  14415. this._boundUniforms[index] = uniform;
  14416. }
  14417. }
  14418. this._currentEffect = null;
  14419. };
  14420. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14421. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14422. return;
  14423. }
  14424. // Remove
  14425. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14426. // Bind last to it
  14427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14428. // Bind to dummy
  14429. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14430. };
  14431. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14432. if (!internalTexture) {
  14433. return -1;
  14434. }
  14435. internalTexture._initialSlot = channel;
  14436. if (this.disableTextureBindingOptimization) {
  14437. if (channel !== internalTexture._designatedSlot) {
  14438. this._textureCollisions.addCount(1, false);
  14439. }
  14440. }
  14441. else {
  14442. if (channel !== internalTexture._designatedSlot) {
  14443. if (internalTexture._designatedSlot > -1) {
  14444. return internalTexture._designatedSlot;
  14445. }
  14446. else {
  14447. // No slot for this texture, let's pick a new one (if we find a free slot)
  14448. if (this._nextFreeTextureSlots.length) {
  14449. return this._nextFreeTextureSlots[0];
  14450. }
  14451. // We need to recycle the oldest bound texture, sorry.
  14452. this._textureCollisions.addCount(1, false);
  14453. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14454. }
  14455. }
  14456. }
  14457. return channel;
  14458. };
  14459. Engine.prototype._linkTrackers = function (previous, next) {
  14460. previous.next = next;
  14461. next.previous = previous;
  14462. };
  14463. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14464. var currentSlot = internalTexture._designatedSlot;
  14465. if (currentSlot === -1) {
  14466. return -1;
  14467. }
  14468. internalTexture._designatedSlot = -1;
  14469. if (this.disableTextureBindingOptimization) {
  14470. return -1;
  14471. }
  14472. // Remove from bound list
  14473. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14474. // Free the slot
  14475. this._boundTexturesCache[currentSlot] = null;
  14476. this._nextFreeTextureSlots.push(currentSlot);
  14477. return currentSlot;
  14478. };
  14479. Engine.prototype._activateCurrentTexture = function () {
  14480. if (this._currentTextureChannel !== this._activeChannel) {
  14481. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14482. this._currentTextureChannel = this._activeChannel;
  14483. }
  14484. };
  14485. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14486. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14487. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14488. this._activeChannel = texture._designatedSlot;
  14489. }
  14490. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14491. var isTextureForRendering = texture && texture._initialSlot > -1;
  14492. if (currentTextureBound !== texture) {
  14493. if (currentTextureBound) {
  14494. this._removeDesignatedSlot(currentTextureBound);
  14495. }
  14496. this._activateCurrentTexture();
  14497. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14498. this._boundTexturesCache[this._activeChannel] = texture;
  14499. if (texture) {
  14500. if (!this.disableTextureBindingOptimization) {
  14501. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14502. if (slotIndex > -1) {
  14503. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14504. }
  14505. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14506. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14507. }
  14508. texture._designatedSlot = this._activeChannel;
  14509. }
  14510. }
  14511. else if (forTextureDataUpdate) {
  14512. this._activateCurrentTexture();
  14513. }
  14514. if (isTextureForRendering && !forTextureDataUpdate) {
  14515. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14516. }
  14517. };
  14518. Engine.prototype._bindTexture = function (channel, texture) {
  14519. if (channel < 0) {
  14520. return;
  14521. }
  14522. if (texture) {
  14523. channel = this._getCorrectTextureChannel(channel, texture);
  14524. }
  14525. this._activeChannel = channel;
  14526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14527. };
  14528. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14529. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14530. };
  14531. Engine.prototype.unbindAllTextures = function () {
  14532. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14533. this._activeChannel = channel;
  14534. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14535. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14536. if (this.webGLVersion > 1) {
  14537. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14538. }
  14539. }
  14540. };
  14541. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14542. if (channel < 0) {
  14543. return;
  14544. }
  14545. if (uniform) {
  14546. this._boundUniforms[channel] = uniform;
  14547. }
  14548. this._setTexture(channel, texture);
  14549. };
  14550. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14551. var uniform = this._boundUniforms[sourceSlot];
  14552. if (uniform._currentState === destination) {
  14553. return;
  14554. }
  14555. this._gl.uniform1i(uniform, destination);
  14556. uniform._currentState = destination;
  14557. };
  14558. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14559. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14560. // Not ready?
  14561. if (!texture) {
  14562. if (this._boundTexturesCache[channel] != null) {
  14563. this._activeChannel = channel;
  14564. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14565. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14566. if (this.webGLVersion > 1) {
  14567. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14568. }
  14569. }
  14570. return false;
  14571. }
  14572. // Video
  14573. if (texture.video) {
  14574. this._activeChannel = channel;
  14575. texture.update();
  14576. }
  14577. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14578. texture.delayLoad();
  14579. return false;
  14580. }
  14581. var internalTexture;
  14582. if (texture.isReady()) {
  14583. internalTexture = texture.getInternalTexture();
  14584. }
  14585. else if (texture.isCube) {
  14586. internalTexture = this.emptyCubeTexture;
  14587. }
  14588. else if (texture.is3D) {
  14589. internalTexture = this.emptyTexture3D;
  14590. }
  14591. else {
  14592. internalTexture = this.emptyTexture;
  14593. }
  14594. if (!isPartOfTextureArray) {
  14595. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14596. }
  14597. if (this._boundTexturesCache[channel] === internalTexture) {
  14598. this._moveBoundTextureOnTop(internalTexture);
  14599. if (!isPartOfTextureArray) {
  14600. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14601. }
  14602. return false;
  14603. }
  14604. this._activeChannel = channel;
  14605. if (internalTexture && internalTexture.is3D) {
  14606. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14607. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14608. internalTexture._cachedWrapU = texture.wrapU;
  14609. switch (texture.wrapU) {
  14610. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14611. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14612. break;
  14613. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14614. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14615. break;
  14616. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14617. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14618. break;
  14619. }
  14620. }
  14621. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14622. internalTexture._cachedWrapV = texture.wrapV;
  14623. switch (texture.wrapV) {
  14624. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14625. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14626. break;
  14627. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14628. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14629. break;
  14630. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14631. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14632. break;
  14633. }
  14634. }
  14635. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14636. internalTexture._cachedWrapR = texture.wrapR;
  14637. switch (texture.wrapR) {
  14638. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14639. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14640. break;
  14641. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14642. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14643. break;
  14644. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14645. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14646. break;
  14647. }
  14648. }
  14649. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14650. }
  14651. else if (internalTexture && internalTexture.isCube) {
  14652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14653. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14654. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14655. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14656. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14658. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14659. }
  14660. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14661. }
  14662. else {
  14663. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14664. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14665. internalTexture._cachedWrapU = texture.wrapU;
  14666. switch (texture.wrapU) {
  14667. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14668. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14669. break;
  14670. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14672. break;
  14673. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14674. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14675. break;
  14676. }
  14677. }
  14678. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14679. internalTexture._cachedWrapV = texture.wrapV;
  14680. switch (texture.wrapV) {
  14681. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14683. break;
  14684. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14686. break;
  14687. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14689. break;
  14690. }
  14691. }
  14692. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14693. }
  14694. return true;
  14695. };
  14696. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14697. if (channel < 0 || !uniform) {
  14698. return;
  14699. }
  14700. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14701. this._textureUnits = new Int32Array(textures.length);
  14702. }
  14703. for (var i = 0; i < textures.length; i++) {
  14704. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14705. }
  14706. this._gl.uniform1iv(uniform, this._textureUnits);
  14707. for (var index = 0; index < textures.length; index++) {
  14708. this._setTexture(this._textureUnits[index], textures[index], true);
  14709. }
  14710. };
  14711. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14712. var internalTexture = texture.getInternalTexture();
  14713. if (!internalTexture) {
  14714. return;
  14715. }
  14716. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14717. var value = texture.anisotropicFilteringLevel;
  14718. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14719. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14720. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14721. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14722. }
  14723. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14724. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14725. internalTexture._cachedAnisotropicFilteringLevel = value;
  14726. }
  14727. };
  14728. Engine.prototype.readPixels = function (x, y, width, height) {
  14729. var data = new Uint8Array(height * width * 4);
  14730. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14731. return data;
  14732. };
  14733. /**
  14734. * Add an externaly attached data from its key.
  14735. * This method call will fail and return false, if such key already exists.
  14736. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14737. * @param key the unique key that identifies the data
  14738. * @param data the data object to associate to the key for this Engine instance
  14739. * @return true if no such key were already present and the data was added successfully, false otherwise
  14740. */
  14741. Engine.prototype.addExternalData = function (key, data) {
  14742. if (!this._externalData) {
  14743. this._externalData = new BABYLON.StringDictionary();
  14744. }
  14745. return this._externalData.add(key, data);
  14746. };
  14747. /**
  14748. * Get an externaly attached data from its key
  14749. * @param key the unique key that identifies the data
  14750. * @return the associated data, if present (can be null), or undefined if not present
  14751. */
  14752. Engine.prototype.getExternalData = function (key) {
  14753. if (!this._externalData) {
  14754. this._externalData = new BABYLON.StringDictionary();
  14755. }
  14756. return this._externalData.get(key);
  14757. };
  14758. /**
  14759. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14760. * @param key the unique key that identifies the data
  14761. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14762. * @return the associated data, can be null if the factory returned null.
  14763. */
  14764. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14765. if (!this._externalData) {
  14766. this._externalData = new BABYLON.StringDictionary();
  14767. }
  14768. return this._externalData.getOrAddWithFactory(key, factory);
  14769. };
  14770. /**
  14771. * Remove an externaly attached data from the Engine instance
  14772. * @param key the unique key that identifies the data
  14773. * @return true if the data was successfully removed, false if it doesn't exist
  14774. */
  14775. Engine.prototype.removeExternalData = function (key) {
  14776. if (!this._externalData) {
  14777. this._externalData = new BABYLON.StringDictionary();
  14778. }
  14779. return this._externalData.remove(key);
  14780. };
  14781. Engine.prototype.unbindAllAttributes = function () {
  14782. if (this._mustWipeVertexAttributes) {
  14783. this._mustWipeVertexAttributes = false;
  14784. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14785. this._gl.disableVertexAttribArray(i);
  14786. this._vertexAttribArraysEnabled[i] = false;
  14787. this._currentBufferPointers[i].active = false;
  14788. }
  14789. return;
  14790. }
  14791. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14792. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14793. continue;
  14794. }
  14795. this._gl.disableVertexAttribArray(i);
  14796. this._vertexAttribArraysEnabled[i] = false;
  14797. this._currentBufferPointers[i].active = false;
  14798. }
  14799. };
  14800. Engine.prototype.releaseEffects = function () {
  14801. for (var name in this._compiledEffects) {
  14802. this._deleteProgram(this._compiledEffects[name]._program);
  14803. }
  14804. this._compiledEffects = {};
  14805. };
  14806. // Dispose
  14807. Engine.prototype.dispose = function () {
  14808. this.hideLoadingUI();
  14809. this.stopRenderLoop();
  14810. // Release postProcesses
  14811. while (this.postProcesses.length) {
  14812. this.postProcesses[0].dispose();
  14813. }
  14814. // Empty texture
  14815. if (this._emptyTexture) {
  14816. this._releaseTexture(this._emptyTexture);
  14817. this._emptyTexture = null;
  14818. }
  14819. if (this._emptyCubeTexture) {
  14820. this._releaseTexture(this._emptyCubeTexture);
  14821. this._emptyCubeTexture = null;
  14822. }
  14823. // Rescale PP
  14824. if (this._rescalePostProcess) {
  14825. this._rescalePostProcess.dispose();
  14826. }
  14827. // Release scenes
  14828. while (this.scenes.length) {
  14829. this.scenes[0].dispose();
  14830. }
  14831. // Release audio engine
  14832. if (Engine.audioEngine) {
  14833. Engine.audioEngine.dispose();
  14834. }
  14835. // Release effects
  14836. this.releaseEffects();
  14837. // Unbind
  14838. this.unbindAllAttributes();
  14839. if (this._dummyFramebuffer) {
  14840. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14841. }
  14842. //WebVR
  14843. this.disableVR();
  14844. // Events
  14845. if (BABYLON.Tools.IsWindowObjectExist()) {
  14846. window.removeEventListener("blur", this._onBlur);
  14847. window.removeEventListener("focus", this._onFocus);
  14848. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14849. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14850. if (this._renderingCanvas) {
  14851. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14852. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14853. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14854. if (!this._doNotHandleContextLost) {
  14855. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14856. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14857. }
  14858. }
  14859. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14860. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14861. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14862. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14863. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14864. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14865. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14866. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14867. if (this._onVrDisplayConnect) {
  14868. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14869. if (this._onVrDisplayDisconnect) {
  14870. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14871. }
  14872. if (this._onVrDisplayPresentChange) {
  14873. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14874. }
  14875. this._onVrDisplayConnect = null;
  14876. this._onVrDisplayDisconnect = null;
  14877. }
  14878. }
  14879. // Remove from Instances
  14880. var index = Engine.Instances.indexOf(this);
  14881. if (index >= 0) {
  14882. Engine.Instances.splice(index, 1);
  14883. }
  14884. this._workingCanvas = null;
  14885. this._workingContext = null;
  14886. this._currentBufferPointers = [];
  14887. this._renderingCanvas = null;
  14888. this._currentProgram = 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. // Action manager
  18471. if (this.actionManager !== undefined && this.actionManager !== null) {
  18472. this.actionManager.dispose();
  18473. this.actionManager = null;
  18474. }
  18475. // Skeleton
  18476. this.skeleton = null;
  18477. // Physics
  18478. if (this.physicsImpostor) {
  18479. this.physicsImpostor.dispose();
  18480. }
  18481. // Intersections in progress
  18482. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18483. var other = this._intersectionsInProgress[index];
  18484. var pos = other._intersectionsInProgress.indexOf(this);
  18485. other._intersectionsInProgress.splice(pos, 1);
  18486. }
  18487. this._intersectionsInProgress = [];
  18488. // Lights
  18489. var lights = this.getScene().lights;
  18490. lights.forEach(function (light) {
  18491. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18492. if (meshIndex !== -1) {
  18493. light.includedOnlyMeshes.splice(meshIndex, 1);
  18494. }
  18495. meshIndex = light.excludedMeshes.indexOf(_this);
  18496. if (meshIndex !== -1) {
  18497. light.excludedMeshes.splice(meshIndex, 1);
  18498. }
  18499. // Shadow generators
  18500. var generator = light.getShadowGenerator();
  18501. if (generator) {
  18502. var shadowMap = generator.getShadowMap();
  18503. if (shadowMap && shadowMap.renderList) {
  18504. meshIndex = shadowMap.renderList.indexOf(_this);
  18505. if (meshIndex !== -1) {
  18506. shadowMap.renderList.splice(meshIndex, 1);
  18507. }
  18508. }
  18509. }
  18510. });
  18511. // Edges
  18512. if (this._edgesRenderer) {
  18513. this._edgesRenderer.dispose();
  18514. this._edgesRenderer = null;
  18515. }
  18516. // SubMeshes
  18517. if (this.getClassName() !== "InstancedMesh") {
  18518. this.releaseSubMeshes();
  18519. }
  18520. // Octree
  18521. var sceneOctree = this.getScene().selectionOctree;
  18522. if (sceneOctree !== undefined && sceneOctree !== null) {
  18523. var index = sceneOctree.dynamicContent.indexOf(this);
  18524. if (index !== -1) {
  18525. sceneOctree.dynamicContent.splice(index, 1);
  18526. }
  18527. }
  18528. // Query
  18529. var engine = this.getScene().getEngine();
  18530. if (this._occlusionQuery) {
  18531. this._isOcclusionQueryInProgress = false;
  18532. engine.deleteQuery(this._occlusionQuery);
  18533. this._occlusionQuery = null;
  18534. }
  18535. // Engine
  18536. engine.wipeCaches();
  18537. // Remove from scene
  18538. this.getScene().removeMesh(this);
  18539. if (disposeMaterialAndTextures) {
  18540. if (this.material) {
  18541. this.material.dispose(false, true);
  18542. }
  18543. }
  18544. if (!doNotRecurse) {
  18545. // Particles
  18546. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18547. if (this.getScene().particleSystems[index].emitter === this) {
  18548. this.getScene().particleSystems[index].dispose();
  18549. index--;
  18550. }
  18551. }
  18552. }
  18553. // facet data
  18554. if (this._facetDataEnabled) {
  18555. this.disableFacetData();
  18556. }
  18557. this.onAfterWorldMatrixUpdateObservable.clear();
  18558. this.onCollideObservable.clear();
  18559. this.onCollisionPositionChangeObservable.clear();
  18560. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18561. };
  18562. /**
  18563. * Adds the passed mesh as a child to the current mesh.
  18564. * Returns the AbstractMesh.
  18565. */
  18566. AbstractMesh.prototype.addChild = function (mesh) {
  18567. mesh.setParent(this);
  18568. return this;
  18569. };
  18570. /**
  18571. * Removes the passed mesh from the current mesh children list.
  18572. * Returns the AbstractMesh.
  18573. */
  18574. AbstractMesh.prototype.removeChild = function (mesh) {
  18575. mesh.setParent(null);
  18576. return this;
  18577. };
  18578. // Facet data
  18579. /**
  18580. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18581. * Returns the AbstractMesh.
  18582. */
  18583. AbstractMesh.prototype._initFacetData = function () {
  18584. if (!this._facetNormals) {
  18585. this._facetNormals = new Array();
  18586. }
  18587. if (!this._facetPositions) {
  18588. this._facetPositions = new Array();
  18589. }
  18590. if (!this._facetPartitioning) {
  18591. this._facetPartitioning = new Array();
  18592. }
  18593. this._facetNb = (this.getIndices().length / 3) | 0;
  18594. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18595. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18596. for (var f = 0; f < this._facetNb; f++) {
  18597. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18598. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18599. }
  18600. this._facetDataEnabled = true;
  18601. return this;
  18602. };
  18603. /**
  18604. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18605. * This method can be called within the render loop.
  18606. * 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.
  18607. * Returns the AbstractMesh.
  18608. */
  18609. AbstractMesh.prototype.updateFacetData = function () {
  18610. if (!this._facetDataEnabled) {
  18611. this._initFacetData();
  18612. }
  18613. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18614. var indices = this.getIndices();
  18615. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18616. var bInfo = this.getBoundingInfo();
  18617. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18618. // init arrays, matrix and sort function on first call
  18619. this._facetDepthSortEnabled = true;
  18620. if (indices instanceof Uint16Array) {
  18621. this._depthSortedIndices = new Uint16Array(indices);
  18622. }
  18623. else if (indices instanceof Uint32Array) {
  18624. this._depthSortedIndices = new Uint32Array(indices);
  18625. }
  18626. else {
  18627. var needs32bits = false;
  18628. for (var i = 0; i < indices.length; i++) {
  18629. if (indices[i] > 65535) {
  18630. needs32bits = true;
  18631. break;
  18632. }
  18633. }
  18634. if (needs32bits) {
  18635. this._depthSortedIndices = new Uint32Array(indices);
  18636. }
  18637. else {
  18638. this._depthSortedIndices = new Uint16Array(indices);
  18639. }
  18640. }
  18641. this._facetDepthSortFunction = function (f1, f2) {
  18642. return (f2.sqDistance - f1.sqDistance);
  18643. };
  18644. if (!this._facetDepthSortFrom) {
  18645. var camera = this.getScene().activeCamera;
  18646. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18647. }
  18648. this._depthSortedFacets = [];
  18649. for (var f = 0; f < this._facetNb; f++) {
  18650. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18651. this._depthSortedFacets.push(depthSortedFacet);
  18652. }
  18653. this._invertedMatrix = BABYLON.Matrix.Identity();
  18654. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18655. }
  18656. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18657. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18658. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18659. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18660. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18661. this._subDiv.max = this._partitioningSubdivisions;
  18662. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18663. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18664. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18665. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18666. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18667. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18668. // set the parameters for ComputeNormals()
  18669. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18670. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18671. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18672. this._facetParameters.bInfo = bInfo;
  18673. this._facetParameters.bbSize = this._bbSize;
  18674. this._facetParameters.subDiv = this._subDiv;
  18675. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18676. this._facetParameters.depthSort = this._facetDepthSort;
  18677. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18678. this.computeWorldMatrix(true);
  18679. this._worldMatrix.invertToRef(this._invertedMatrix);
  18680. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18681. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18682. }
  18683. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18684. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18685. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18686. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18687. var l = (this._depthSortedIndices.length / 3) | 0;
  18688. for (var f = 0; f < l; f++) {
  18689. var sind = this._depthSortedFacets[f].ind;
  18690. this._depthSortedIndices[f * 3] = indices[sind];
  18691. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18692. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18693. }
  18694. this.updateIndices(this._depthSortedIndices);
  18695. }
  18696. return this;
  18697. };
  18698. /**
  18699. * Returns the facetLocalNormals array.
  18700. * The normals are expressed in the mesh local space.
  18701. */
  18702. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18703. if (!this._facetNormals) {
  18704. this.updateFacetData();
  18705. }
  18706. return this._facetNormals;
  18707. };
  18708. /**
  18709. * Returns the facetLocalPositions array.
  18710. * The facet positions are expressed in the mesh local space.
  18711. */
  18712. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18713. if (!this._facetPositions) {
  18714. this.updateFacetData();
  18715. }
  18716. return this._facetPositions;
  18717. };
  18718. /**
  18719. * Returns the facetLocalPartioning array.
  18720. */
  18721. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18722. if (!this._facetPartitioning) {
  18723. this.updateFacetData();
  18724. }
  18725. return this._facetPartitioning;
  18726. };
  18727. /**
  18728. * Returns the i-th facet position in the world system.
  18729. * This method allocates a new Vector3 per call.
  18730. */
  18731. AbstractMesh.prototype.getFacetPosition = function (i) {
  18732. var pos = BABYLON.Vector3.Zero();
  18733. this.getFacetPositionToRef(i, pos);
  18734. return pos;
  18735. };
  18736. /**
  18737. * Sets the reference Vector3 with the i-th facet position in the world system.
  18738. * Returns the AbstractMesh.
  18739. */
  18740. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18741. var localPos = (this.getFacetLocalPositions())[i];
  18742. var world = this.getWorldMatrix();
  18743. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18744. return this;
  18745. };
  18746. /**
  18747. * Returns the i-th facet normal in the world system.
  18748. * This method allocates a new Vector3 per call.
  18749. */
  18750. AbstractMesh.prototype.getFacetNormal = function (i) {
  18751. var norm = BABYLON.Vector3.Zero();
  18752. this.getFacetNormalToRef(i, norm);
  18753. return norm;
  18754. };
  18755. /**
  18756. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18757. * Returns the AbstractMesh.
  18758. */
  18759. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18760. var localNorm = (this.getFacetLocalNormals())[i];
  18761. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18762. return this;
  18763. };
  18764. /**
  18765. * 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).
  18766. */
  18767. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18768. var bInfo = this.getBoundingInfo();
  18769. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18770. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18771. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18772. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18773. return null;
  18774. }
  18775. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18776. };
  18777. /**
  18778. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18779. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18780. * 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.
  18781. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18782. * 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.
  18783. */
  18784. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18785. if (checkFace === void 0) { checkFace = false; }
  18786. if (facing === void 0) { facing = true; }
  18787. var world = this.getWorldMatrix();
  18788. var invMat = BABYLON.Tmp.Matrix[5];
  18789. world.invertToRef(invMat);
  18790. var invVect = BABYLON.Tmp.Vector3[8];
  18791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18792. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18793. if (projected) {
  18794. // tranform the local computed projected vector to world coordinates
  18795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18796. }
  18797. return closest;
  18798. };
  18799. /**
  18800. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18801. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18802. * 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.
  18803. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18804. * 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.
  18805. */
  18806. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18807. if (checkFace === void 0) { checkFace = false; }
  18808. if (facing === void 0) { facing = true; }
  18809. var closest = null;
  18810. var tmpx = 0.0;
  18811. var tmpy = 0.0;
  18812. var tmpz = 0.0;
  18813. var d = 0.0; // tmp dot facet normal * facet position
  18814. var t0 = 0.0;
  18815. var projx = 0.0;
  18816. var projy = 0.0;
  18817. var projz = 0.0;
  18818. // Get all the facets in the same partitioning block than (x, y, z)
  18819. var facetPositions = this.getFacetLocalPositions();
  18820. var facetNormals = this.getFacetLocalNormals();
  18821. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18822. if (!facetsInBlock) {
  18823. return null;
  18824. }
  18825. // Get the closest facet to (x, y, z)
  18826. var shortest = Number.MAX_VALUE; // init distance vars
  18827. var tmpDistance = shortest;
  18828. var fib; // current facet in the block
  18829. var norm; // current facet normal
  18830. var p0; // current facet barycenter position
  18831. // loop on all the facets in the current partitioning block
  18832. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18833. fib = facetsInBlock[idx];
  18834. norm = facetNormals[fib];
  18835. p0 = facetPositions[fib];
  18836. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18837. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18838. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18839. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18840. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18841. projx = x + norm.x * t0;
  18842. projy = y + norm.y * t0;
  18843. projz = z + norm.z * t0;
  18844. tmpx = projx - x;
  18845. tmpy = projy - y;
  18846. tmpz = projz - z;
  18847. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18848. if (tmpDistance < shortest) {
  18849. shortest = tmpDistance;
  18850. closest = fib;
  18851. if (projected) {
  18852. projected.x = projx;
  18853. projected.y = projy;
  18854. projected.z = projz;
  18855. }
  18856. }
  18857. }
  18858. }
  18859. return closest;
  18860. };
  18861. /**
  18862. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18863. */
  18864. AbstractMesh.prototype.getFacetDataParameters = function () {
  18865. return this._facetParameters;
  18866. };
  18867. /**
  18868. * Disables the feature FacetData and frees the related memory.
  18869. * Returns the AbstractMesh.
  18870. */
  18871. AbstractMesh.prototype.disableFacetData = function () {
  18872. if (this._facetDataEnabled) {
  18873. this._facetDataEnabled = false;
  18874. this._facetPositions = new Array();
  18875. this._facetNormals = new Array();
  18876. this._facetPartitioning = new Array();
  18877. this._facetParameters = null;
  18878. this._depthSortedIndices = new Uint32Array(0);
  18879. }
  18880. return this;
  18881. };
  18882. /**
  18883. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18884. * Returns the mesh.
  18885. */
  18886. AbstractMesh.prototype.updateIndices = function (indices) {
  18887. return this;
  18888. };
  18889. /**
  18890. * The mesh Geometry. Actually used by the Mesh object.
  18891. * Returns a blank geometry object.
  18892. */
  18893. /**
  18894. * Creates new normals data for the mesh.
  18895. * @param updatable.
  18896. */
  18897. AbstractMesh.prototype.createNormals = function (updatable) {
  18898. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18899. var indices = this.getIndices();
  18900. var normals;
  18901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18902. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18903. }
  18904. else {
  18905. normals = [];
  18906. }
  18907. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18908. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18909. };
  18910. /**
  18911. * Align the mesh with a normal.
  18912. * Returns the mesh.
  18913. */
  18914. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18915. if (!upDirection) {
  18916. upDirection = BABYLON.Axis.Y;
  18917. }
  18918. var axisX = BABYLON.Tmp.Vector3[0];
  18919. var axisZ = BABYLON.Tmp.Vector3[1];
  18920. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18921. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18922. if (this.rotationQuaternion) {
  18923. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18924. }
  18925. else {
  18926. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18927. }
  18928. return this;
  18929. };
  18930. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18931. var engine = this.getEngine();
  18932. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18933. this._isOccluded = false;
  18934. return;
  18935. }
  18936. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18937. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18938. if (isOcclusionQueryAvailable) {
  18939. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18940. this._isOcclusionQueryInProgress = false;
  18941. this._occlusionInternalRetryCounter = 0;
  18942. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18943. }
  18944. else {
  18945. this._occlusionInternalRetryCounter++;
  18946. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18947. this._isOcclusionQueryInProgress = false;
  18948. this._occlusionInternalRetryCounter = 0;
  18949. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18950. // if strict continue the last state of the object.
  18951. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18952. }
  18953. else {
  18954. return;
  18955. }
  18956. }
  18957. }
  18958. var scene = this.getScene();
  18959. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18960. if (!this._occlusionQuery) {
  18961. this._occlusionQuery = engine.createQuery();
  18962. }
  18963. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18964. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18965. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18966. this._isOcclusionQueryInProgress = true;
  18967. };
  18968. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18969. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18970. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18971. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18972. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18973. return AbstractMesh;
  18974. }(BABYLON.TransformNode));
  18975. BABYLON.AbstractMesh = AbstractMesh;
  18976. })(BABYLON || (BABYLON = {}));
  18977. //# sourceMappingURL=babylon.abstractMesh.js.map
  18978. var BABYLON;
  18979. (function (BABYLON) {
  18980. /**
  18981. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18982. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18983. * 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.
  18984. */
  18985. var Light = /** @class */ (function (_super) {
  18986. __extends(Light, _super);
  18987. /**
  18988. * Creates a Light object in the scene.
  18989. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18990. * @param name The firendly name of the light
  18991. * @param scene The scene the light belongs too
  18992. */
  18993. function Light(name, scene) {
  18994. var _this = _super.call(this, name, scene) || this;
  18995. /**
  18996. * Diffuse gives the basic color to an object.
  18997. */
  18998. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18999. /**
  19000. * Specular produces a highlight color on an object.
  19001. * Note: This is note affecting PBR materials.
  19002. */
  19003. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19004. /**
  19005. * Strength of the light.
  19006. * Note: By default it is define in the framework own unit.
  19007. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19008. */
  19009. _this.intensity = 1.0;
  19010. /**
  19011. * Defines how far from the source the light is impacting in scene units.
  19012. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19013. */
  19014. _this.range = Number.MAX_VALUE;
  19015. /**
  19016. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19017. * of light.
  19018. */
  19019. _this._photometricScale = 1.0;
  19020. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19021. _this._radius = 0.00001;
  19022. /**
  19023. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19024. * exceeding the number allowed of the materials.
  19025. */
  19026. _this.renderPriority = 0;
  19027. /**
  19028. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19029. * the current shadow generator.
  19030. */
  19031. _this.shadowEnabled = true;
  19032. _this._excludeWithLayerMask = 0;
  19033. _this._includeOnlyWithLayerMask = 0;
  19034. _this._lightmapMode = 0;
  19035. /**
  19036. * @ignore Internal use only.
  19037. */
  19038. _this._excludedMeshesIds = new Array();
  19039. /**
  19040. * @ignore Internal use only.
  19041. */
  19042. _this._includedOnlyMeshesIds = new Array();
  19043. _this.getScene().addLight(_this);
  19044. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19045. _this._buildUniformLayout();
  19046. _this.includedOnlyMeshes = new Array();
  19047. _this.excludedMeshes = new Array();
  19048. _this._resyncMeshes();
  19049. return _this;
  19050. }
  19051. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19052. /**
  19053. * If every light affecting the material is in this lightmapMode,
  19054. * material.lightmapTexture adds or multiplies
  19055. * (depends on material.useLightmapAsShadowmap)
  19056. * after every other light calculations.
  19057. */
  19058. get: function () {
  19059. return Light._LIGHTMAP_DEFAULT;
  19060. },
  19061. enumerable: true,
  19062. configurable: true
  19063. });
  19064. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19065. /**
  19066. * material.lightmapTexture as only diffuse lighting from this light
  19067. * adds only specular lighting from this light
  19068. * adds dynamic shadows
  19069. */
  19070. get: function () {
  19071. return Light._LIGHTMAP_SPECULAR;
  19072. },
  19073. enumerable: true,
  19074. configurable: true
  19075. });
  19076. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19077. /**
  19078. * material.lightmapTexture as only lighting
  19079. * no light calculation from this light
  19080. * only adds dynamic shadows from this light
  19081. */
  19082. get: function () {
  19083. return Light._LIGHTMAP_SHADOWSONLY;
  19084. },
  19085. enumerable: true,
  19086. configurable: true
  19087. });
  19088. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19089. /**
  19090. * Each light type uses the default quantity according to its type:
  19091. * point/spot lights use luminous intensity
  19092. * directional lights use illuminance
  19093. */
  19094. get: function () {
  19095. return Light._INTENSITYMODE_AUTOMATIC;
  19096. },
  19097. enumerable: true,
  19098. configurable: true
  19099. });
  19100. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19101. /**
  19102. * lumen (lm)
  19103. */
  19104. get: function () {
  19105. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19106. },
  19107. enumerable: true,
  19108. configurable: true
  19109. });
  19110. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19111. /**
  19112. * candela (lm/sr)
  19113. */
  19114. get: function () {
  19115. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19116. },
  19117. enumerable: true,
  19118. configurable: true
  19119. });
  19120. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19121. /**
  19122. * lux (lm/m^2)
  19123. */
  19124. get: function () {
  19125. return Light._INTENSITYMODE_ILLUMINANCE;
  19126. },
  19127. enumerable: true,
  19128. configurable: true
  19129. });
  19130. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19131. /**
  19132. * nit (cd/m^2)
  19133. */
  19134. get: function () {
  19135. return Light._INTENSITYMODE_LUMINANCE;
  19136. },
  19137. enumerable: true,
  19138. configurable: true
  19139. });
  19140. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19141. /**
  19142. * Light type const id of the point light.
  19143. */
  19144. get: function () {
  19145. return Light._LIGHTTYPEID_POINTLIGHT;
  19146. },
  19147. enumerable: true,
  19148. configurable: true
  19149. });
  19150. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19151. /**
  19152. * Light type const id of the directional light.
  19153. */
  19154. get: function () {
  19155. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19156. },
  19157. enumerable: true,
  19158. configurable: true
  19159. });
  19160. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19161. /**
  19162. * Light type const id of the spot light.
  19163. */
  19164. get: function () {
  19165. return Light._LIGHTTYPEID_SPOTLIGHT;
  19166. },
  19167. enumerable: true,
  19168. configurable: true
  19169. });
  19170. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19171. /**
  19172. * Light type const id of the hemispheric light.
  19173. */
  19174. get: function () {
  19175. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. Object.defineProperty(Light.prototype, "intensityMode", {
  19181. /**
  19182. * Gets the photometric scale used to interpret the intensity.
  19183. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19184. */
  19185. get: function () {
  19186. return this._intensityMode;
  19187. },
  19188. /**
  19189. * Sets the photometric scale used to interpret the intensity.
  19190. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19191. */
  19192. set: function (value) {
  19193. this._intensityMode = value;
  19194. this._computePhotometricScale();
  19195. },
  19196. enumerable: true,
  19197. configurable: true
  19198. });
  19199. ;
  19200. ;
  19201. Object.defineProperty(Light.prototype, "radius", {
  19202. /**
  19203. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19204. */
  19205. get: function () {
  19206. return this._radius;
  19207. },
  19208. /**
  19209. * sets the light radius used by PBR Materials to simulate soft area lights.
  19210. */
  19211. set: function (value) {
  19212. this._radius = value;
  19213. this._computePhotometricScale();
  19214. },
  19215. enumerable: true,
  19216. configurable: true
  19217. });
  19218. ;
  19219. ;
  19220. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19221. /**
  19222. * Gets the only meshes impacted by this light.
  19223. */
  19224. get: function () {
  19225. return this._includedOnlyMeshes;
  19226. },
  19227. /**
  19228. * Sets the only meshes impacted by this light.
  19229. */
  19230. set: function (value) {
  19231. this._includedOnlyMeshes = value;
  19232. this._hookArrayForIncludedOnly(value);
  19233. },
  19234. enumerable: true,
  19235. configurable: true
  19236. });
  19237. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19238. /**
  19239. * Gets the meshes not impacted by this light.
  19240. */
  19241. get: function () {
  19242. return this._excludedMeshes;
  19243. },
  19244. /**
  19245. * Sets the meshes not impacted by this light.
  19246. */
  19247. set: function (value) {
  19248. this._excludedMeshes = value;
  19249. this._hookArrayForExcluded(value);
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19255. /**
  19256. * Gets the layer id use to find what meshes are not impacted by the light.
  19257. * Inactive if 0
  19258. */
  19259. get: function () {
  19260. return this._excludeWithLayerMask;
  19261. },
  19262. /**
  19263. * Sets the layer id use to find what meshes are not impacted by the light.
  19264. * Inactive if 0
  19265. */
  19266. set: function (value) {
  19267. this._excludeWithLayerMask = value;
  19268. this._resyncMeshes();
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19274. /**
  19275. * Gets the layer id use to find what meshes are impacted by the light.
  19276. * Inactive if 0
  19277. */
  19278. get: function () {
  19279. return this._includeOnlyWithLayerMask;
  19280. },
  19281. /**
  19282. * Sets the layer id use to find what meshes are impacted by the light.
  19283. * Inactive if 0
  19284. */
  19285. set: function (value) {
  19286. this._includeOnlyWithLayerMask = value;
  19287. this._resyncMeshes();
  19288. },
  19289. enumerable: true,
  19290. configurable: true
  19291. });
  19292. Object.defineProperty(Light.prototype, "lightmapMode", {
  19293. /**
  19294. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19295. */
  19296. get: function () {
  19297. return this._lightmapMode;
  19298. },
  19299. /**
  19300. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19301. */
  19302. set: function (value) {
  19303. if (this._lightmapMode === value) {
  19304. return;
  19305. }
  19306. this._lightmapMode = value;
  19307. this._markMeshesAsLightDirty();
  19308. },
  19309. enumerable: true,
  19310. configurable: true
  19311. });
  19312. /**
  19313. * Returns the string "Light".
  19314. * @returns the class name
  19315. */
  19316. Light.prototype.getClassName = function () {
  19317. return "Light";
  19318. };
  19319. /**
  19320. * Converts the light information to a readable string for debug purpose.
  19321. * @param fullDetails Supports for multiple levels of logging within scene loading
  19322. * @returns the human readable light info
  19323. */
  19324. Light.prototype.toString = function (fullDetails) {
  19325. var ret = "Name: " + this.name;
  19326. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19327. if (this.animations) {
  19328. for (var i = 0; i < this.animations.length; i++) {
  19329. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19330. }
  19331. }
  19332. if (fullDetails) {
  19333. }
  19334. return ret;
  19335. };
  19336. /**
  19337. * Set the enabled state of this node.
  19338. * @param value - the new enabled state
  19339. * @see isEnabled
  19340. */
  19341. Light.prototype.setEnabled = function (value) {
  19342. _super.prototype.setEnabled.call(this, value);
  19343. this._resyncMeshes();
  19344. };
  19345. /**
  19346. * Returns the Light associated shadow generator if any.
  19347. * @return the associated shadow generator.
  19348. */
  19349. Light.prototype.getShadowGenerator = function () {
  19350. return this._shadowGenerator;
  19351. };
  19352. /**
  19353. * Returns a Vector3, the absolute light position in the World.
  19354. * @returns the world space position of the light
  19355. */
  19356. Light.prototype.getAbsolutePosition = function () {
  19357. return BABYLON.Vector3.Zero();
  19358. };
  19359. /**
  19360. * Specifies if the light will affect the passed mesh.
  19361. * @param mesh The mesh to test against the light
  19362. * @return true the mesh is affected otherwise, false.
  19363. */
  19364. Light.prototype.canAffectMesh = function (mesh) {
  19365. if (!mesh) {
  19366. return true;
  19367. }
  19368. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19369. return false;
  19370. }
  19371. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19372. return false;
  19373. }
  19374. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19375. return false;
  19376. }
  19377. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19378. return false;
  19379. }
  19380. return true;
  19381. };
  19382. /**
  19383. * Computes and Returns the light World matrix.
  19384. * @returns the world matrix
  19385. */
  19386. Light.prototype.getWorldMatrix = function () {
  19387. this._currentRenderId = this.getScene().getRenderId();
  19388. var worldMatrix = this._getWorldMatrix();
  19389. if (this.parent && this.parent.getWorldMatrix) {
  19390. if (!this._parentedWorldMatrix) {
  19391. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19392. }
  19393. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19394. this._markSyncedWithParent();
  19395. return this._parentedWorldMatrix;
  19396. }
  19397. return worldMatrix;
  19398. };
  19399. /**
  19400. * Sort function to order lights for rendering.
  19401. * @param a First Light object to compare to second.
  19402. * @param b Second Light object to compare first.
  19403. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19404. */
  19405. Light.CompareLightsPriority = function (a, b) {
  19406. //shadow-casting lights have priority over non-shadow-casting lights
  19407. //the renderPrioirty is a secondary sort criterion
  19408. if (a.shadowEnabled !== b.shadowEnabled) {
  19409. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19410. }
  19411. return b.renderPriority - a.renderPriority;
  19412. };
  19413. /**
  19414. * Releases resources associated with this node.
  19415. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19416. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19417. */
  19418. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19419. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19420. if (this._shadowGenerator) {
  19421. this._shadowGenerator.dispose();
  19422. this._shadowGenerator = null;
  19423. }
  19424. // Animations
  19425. this.getScene().stopAnimation(this);
  19426. // Remove from meshes
  19427. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19428. var mesh = _a[_i];
  19429. mesh._removeLightSource(this);
  19430. }
  19431. this._uniformBuffer.dispose();
  19432. // Remove from scene
  19433. this.getScene().removeLight(this);
  19434. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19435. };
  19436. /**
  19437. * Returns the light type ID (integer).
  19438. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19439. */
  19440. Light.prototype.getTypeID = function () {
  19441. return 0;
  19442. };
  19443. /**
  19444. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19445. * @returns the scaled intensity in intensity mode unit
  19446. */
  19447. Light.prototype.getScaledIntensity = function () {
  19448. return this._photometricScale * this.intensity;
  19449. };
  19450. /**
  19451. * Returns a new Light object, named "name", from the current one.
  19452. * @param name The name of the cloned light
  19453. * @returns the new created light
  19454. */
  19455. Light.prototype.clone = function (name) {
  19456. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19457. if (!constructor) {
  19458. return null;
  19459. }
  19460. return BABYLON.SerializationHelper.Clone(constructor, this);
  19461. };
  19462. /**
  19463. * Serializes the current light into a Serialization object.
  19464. * @returns the serialized object.
  19465. */
  19466. Light.prototype.serialize = function () {
  19467. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19468. // Type
  19469. serializationObject.type = this.getTypeID();
  19470. // Parent
  19471. if (this.parent) {
  19472. serializationObject.parentId = this.parent.id;
  19473. }
  19474. // Inclusion / exclusions
  19475. if (this.excludedMeshes.length > 0) {
  19476. serializationObject.excludedMeshesIds = [];
  19477. this.excludedMeshes.forEach(function (mesh) {
  19478. serializationObject.excludedMeshesIds.push(mesh.id);
  19479. });
  19480. }
  19481. if (this.includedOnlyMeshes.length > 0) {
  19482. serializationObject.includedOnlyMeshesIds = [];
  19483. this.includedOnlyMeshes.forEach(function (mesh) {
  19484. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19485. });
  19486. }
  19487. // Animations
  19488. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19489. serializationObject.ranges = this.serializeAnimationRanges();
  19490. return serializationObject;
  19491. };
  19492. /**
  19493. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19494. * This new light is named "name" and added to the passed scene.
  19495. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19496. * @param name The friendly name of the light
  19497. * @param scene The scene the new light will belong to
  19498. * @returns the constructor function
  19499. */
  19500. Light.GetConstructorFromName = function (type, name, scene) {
  19501. switch (type) {
  19502. case 0:
  19503. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19504. case 1:
  19505. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19506. case 2:
  19507. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19508. case 3:
  19509. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19510. }
  19511. return null;
  19512. };
  19513. /**
  19514. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19515. * @param parsedLight The JSON representation of the light
  19516. * @param scene The scene to create the parsed light in
  19517. * @returns the created light after parsing
  19518. */
  19519. Light.Parse = function (parsedLight, scene) {
  19520. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19521. if (!constructor) {
  19522. return null;
  19523. }
  19524. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19525. // Inclusion / exclusions
  19526. if (parsedLight.excludedMeshesIds) {
  19527. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19528. }
  19529. if (parsedLight.includedOnlyMeshesIds) {
  19530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19531. }
  19532. // Parent
  19533. if (parsedLight.parentId) {
  19534. light._waitingParentId = parsedLight.parentId;
  19535. }
  19536. // Animations
  19537. if (parsedLight.animations) {
  19538. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19539. var parsedAnimation = parsedLight.animations[animationIndex];
  19540. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19541. }
  19542. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19543. }
  19544. if (parsedLight.autoAnimate) {
  19545. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19546. }
  19547. return light;
  19548. };
  19549. Light.prototype._hookArrayForExcluded = function (array) {
  19550. var _this = this;
  19551. var oldPush = array.push;
  19552. array.push = function () {
  19553. var items = [];
  19554. for (var _i = 0; _i < arguments.length; _i++) {
  19555. items[_i] = arguments[_i];
  19556. }
  19557. var result = oldPush.apply(array, items);
  19558. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19559. var item = items_1[_a];
  19560. item._resyncLighSource(_this);
  19561. }
  19562. return result;
  19563. };
  19564. var oldSplice = array.splice;
  19565. array.splice = function (index, deleteCount) {
  19566. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19567. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19568. var item = deleted_1[_i];
  19569. item._resyncLighSource(_this);
  19570. }
  19571. return deleted;
  19572. };
  19573. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19574. var item = array_1[_i];
  19575. item._resyncLighSource(this);
  19576. }
  19577. };
  19578. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19579. var _this = this;
  19580. var oldPush = array.push;
  19581. array.push = function () {
  19582. var items = [];
  19583. for (var _i = 0; _i < arguments.length; _i++) {
  19584. items[_i] = arguments[_i];
  19585. }
  19586. var result = oldPush.apply(array, items);
  19587. _this._resyncMeshes();
  19588. return result;
  19589. };
  19590. var oldSplice = array.splice;
  19591. array.splice = function (index, deleteCount) {
  19592. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19593. _this._resyncMeshes();
  19594. return deleted;
  19595. };
  19596. this._resyncMeshes();
  19597. };
  19598. Light.prototype._resyncMeshes = function () {
  19599. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19600. var mesh = _a[_i];
  19601. mesh._resyncLighSource(this);
  19602. }
  19603. };
  19604. /**
  19605. * Forces the meshes to update their light related information in their rendering used effects
  19606. * @ignore Internal Use Only
  19607. */
  19608. Light.prototype._markMeshesAsLightDirty = function () {
  19609. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19610. var mesh = _a[_i];
  19611. if (mesh._lightSources.indexOf(this) !== -1) {
  19612. mesh._markSubMeshesAsLightDirty();
  19613. }
  19614. }
  19615. };
  19616. /**
  19617. * Recomputes the cached photometric scale if needed.
  19618. */
  19619. Light.prototype._computePhotometricScale = function () {
  19620. this._photometricScale = this._getPhotometricScale();
  19621. this.getScene().resetCachedMaterial();
  19622. };
  19623. /**
  19624. * Returns the Photometric Scale according to the light type and intensity mode.
  19625. */
  19626. Light.prototype._getPhotometricScale = function () {
  19627. var photometricScale = 0.0;
  19628. var lightTypeID = this.getTypeID();
  19629. //get photometric mode
  19630. var photometricMode = this.intensityMode;
  19631. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19632. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19633. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19634. }
  19635. else {
  19636. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19637. }
  19638. }
  19639. //compute photometric scale
  19640. switch (lightTypeID) {
  19641. case Light.LIGHTTYPEID_POINTLIGHT:
  19642. case Light.LIGHTTYPEID_SPOTLIGHT:
  19643. switch (photometricMode) {
  19644. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19645. photometricScale = 1.0 / (4.0 * Math.PI);
  19646. break;
  19647. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19648. photometricScale = 1.0;
  19649. break;
  19650. case Light.INTENSITYMODE_LUMINANCE:
  19651. photometricScale = this.radius * this.radius;
  19652. break;
  19653. }
  19654. break;
  19655. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19656. switch (photometricMode) {
  19657. case Light.INTENSITYMODE_ILLUMINANCE:
  19658. photometricScale = 1.0;
  19659. break;
  19660. case Light.INTENSITYMODE_LUMINANCE:
  19661. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19662. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19663. var apexAngleRadians = this.radius;
  19664. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19665. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19666. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19667. photometricScale = solidAngle;
  19668. break;
  19669. }
  19670. break;
  19671. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19672. // No fall off in hemisperic light.
  19673. photometricScale = 1.0;
  19674. break;
  19675. }
  19676. return photometricScale;
  19677. };
  19678. /**
  19679. * Reorder the light in the scene according to their defined priority.
  19680. * @ignore Internal Use Only
  19681. */
  19682. Light.prototype._reorderLightsInScene = function () {
  19683. var scene = this.getScene();
  19684. if (this._renderPriority != 0) {
  19685. scene.requireLightSorting = true;
  19686. }
  19687. this.getScene().sortLightsByPriority();
  19688. };
  19689. //lightmapMode Consts
  19690. Light._LIGHTMAP_DEFAULT = 0;
  19691. Light._LIGHTMAP_SPECULAR = 1;
  19692. Light._LIGHTMAP_SHADOWSONLY = 2;
  19693. // Intensity Mode Consts
  19694. Light._INTENSITYMODE_AUTOMATIC = 0;
  19695. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19696. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19697. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19698. Light._INTENSITYMODE_LUMINANCE = 4;
  19699. // Light types ids const.
  19700. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19701. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19702. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19703. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19704. __decorate([
  19705. BABYLON.serializeAsColor3()
  19706. ], Light.prototype, "diffuse", void 0);
  19707. __decorate([
  19708. BABYLON.serializeAsColor3()
  19709. ], Light.prototype, "specular", void 0);
  19710. __decorate([
  19711. BABYLON.serialize()
  19712. ], Light.prototype, "intensity", void 0);
  19713. __decorate([
  19714. BABYLON.serialize()
  19715. ], Light.prototype, "range", void 0);
  19716. __decorate([
  19717. BABYLON.serialize()
  19718. ], Light.prototype, "intensityMode", null);
  19719. __decorate([
  19720. BABYLON.serialize()
  19721. ], Light.prototype, "radius", null);
  19722. __decorate([
  19723. BABYLON.serialize()
  19724. ], Light.prototype, "_renderPriority", void 0);
  19725. __decorate([
  19726. BABYLON.expandToProperty("_reorderLightsInScene")
  19727. ], Light.prototype, "renderPriority", void 0);
  19728. __decorate([
  19729. BABYLON.serialize()
  19730. ], Light.prototype, "shadowEnabled", void 0);
  19731. __decorate([
  19732. BABYLON.serialize("excludeWithLayerMask")
  19733. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19734. __decorate([
  19735. BABYLON.serialize("includeOnlyWithLayerMask")
  19736. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19737. __decorate([
  19738. BABYLON.serialize("lightmapMode")
  19739. ], Light.prototype, "_lightmapMode", void 0);
  19740. return Light;
  19741. }(BABYLON.Node));
  19742. BABYLON.Light = Light;
  19743. })(BABYLON || (BABYLON = {}));
  19744. //# sourceMappingURL=babylon.light.js.map
  19745. var BABYLON;
  19746. (function (BABYLON) {
  19747. var Camera = /** @class */ (function (_super) {
  19748. __extends(Camera, _super);
  19749. function Camera(name, position, scene) {
  19750. var _this = _super.call(this, name, scene) || this;
  19751. /**
  19752. * The vector the camera should consider as up.
  19753. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19754. */
  19755. _this.upVector = BABYLON.Vector3.Up();
  19756. _this.orthoLeft = null;
  19757. _this.orthoRight = null;
  19758. _this.orthoBottom = null;
  19759. _this.orthoTop = null;
  19760. /**
  19761. * FOV is set in Radians. (default is 0.8)
  19762. */
  19763. _this.fov = 0.8;
  19764. _this.minZ = 1;
  19765. _this.maxZ = 10000.0;
  19766. _this.inertia = 0.9;
  19767. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19768. _this.isIntermediate = false;
  19769. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19770. /**
  19771. * Restricts the camera to viewing objects with the same layerMask.
  19772. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19773. */
  19774. _this.layerMask = 0x0FFFFFFF;
  19775. /**
  19776. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19777. */
  19778. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19779. // Camera rig members
  19780. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19781. _this._rigCameras = new Array();
  19782. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19783. _this._skipRendering = false;
  19784. _this.customRenderTargets = new Array();
  19785. // Observables
  19786. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19787. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19788. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19789. _this.onRestoreStateObservable = new BABYLON.Observable();
  19790. // Cache
  19791. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19792. _this._projectionMatrix = new BABYLON.Matrix();
  19793. _this._doNotComputeProjectionMatrix = false;
  19794. _this._postProcesses = new Array();
  19795. _this._transformMatrix = BABYLON.Matrix.Zero();
  19796. _this._activeMeshes = new BABYLON.SmartArray(256);
  19797. _this._globalPosition = BABYLON.Vector3.Zero();
  19798. _this._refreshFrustumPlanes = true;
  19799. _this.getScene().addCamera(_this);
  19800. if (!_this.getScene().activeCamera) {
  19801. _this.getScene().activeCamera = _this;
  19802. }
  19803. _this.position = position;
  19804. return _this;
  19805. }
  19806. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19807. get: function () {
  19808. return Camera._PERSPECTIVE_CAMERA;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19814. get: function () {
  19815. return Camera._ORTHOGRAPHIC_CAMERA;
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19821. /**
  19822. * This is the default FOV mode for perspective cameras.
  19823. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19824. *
  19825. */
  19826. get: function () {
  19827. return Camera._FOVMODE_VERTICAL_FIXED;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19833. /**
  19834. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19835. *
  19836. */
  19837. get: function () {
  19838. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19844. get: function () {
  19845. return Camera._RIG_MODE_NONE;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19851. get: function () {
  19852. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19858. get: function () {
  19859. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19865. get: function () {
  19866. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19872. get: function () {
  19873. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19879. get: function () {
  19880. return Camera._RIG_MODE_VR;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19886. get: function () {
  19887. return Camera._RIG_MODE_WEBVR;
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. /**
  19893. * Store current camera state (fov, position, etc..)
  19894. */
  19895. Camera.prototype.storeState = function () {
  19896. this._stateStored = true;
  19897. this._storedFov = this.fov;
  19898. return this;
  19899. };
  19900. /**
  19901. * Restores the camera state values if it has been stored. You must call storeState() first
  19902. */
  19903. Camera.prototype._restoreStateValues = function () {
  19904. if (!this._stateStored) {
  19905. return false;
  19906. }
  19907. this.fov = this._storedFov;
  19908. return true;
  19909. };
  19910. /**
  19911. * Restored camera state. You must call storeState() first
  19912. */
  19913. Camera.prototype.restoreState = function () {
  19914. if (this._restoreStateValues()) {
  19915. this.onRestoreStateObservable.notifyObservers(this);
  19916. return true;
  19917. }
  19918. return false;
  19919. };
  19920. Camera.prototype.getClassName = function () {
  19921. return "Camera";
  19922. };
  19923. /**
  19924. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19925. */
  19926. Camera.prototype.toString = function (fullDetails) {
  19927. var ret = "Name: " + this.name;
  19928. ret += ", type: " + this.getClassName();
  19929. if (this.animations) {
  19930. for (var i = 0; i < this.animations.length; i++) {
  19931. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19932. }
  19933. }
  19934. if (fullDetails) {
  19935. }
  19936. return ret;
  19937. };
  19938. Object.defineProperty(Camera.prototype, "globalPosition", {
  19939. get: function () {
  19940. return this._globalPosition;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Camera.prototype.getActiveMeshes = function () {
  19946. return this._activeMeshes;
  19947. };
  19948. Camera.prototype.isActiveMesh = function (mesh) {
  19949. return (this._activeMeshes.indexOf(mesh) !== -1);
  19950. };
  19951. //Cache
  19952. Camera.prototype._initCache = function () {
  19953. _super.prototype._initCache.call(this);
  19954. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19955. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19956. this._cache.mode = undefined;
  19957. this._cache.minZ = undefined;
  19958. this._cache.maxZ = undefined;
  19959. this._cache.fov = undefined;
  19960. this._cache.fovMode = undefined;
  19961. this._cache.aspectRatio = undefined;
  19962. this._cache.orthoLeft = undefined;
  19963. this._cache.orthoRight = undefined;
  19964. this._cache.orthoBottom = undefined;
  19965. this._cache.orthoTop = undefined;
  19966. this._cache.renderWidth = undefined;
  19967. this._cache.renderHeight = undefined;
  19968. };
  19969. Camera.prototype._updateCache = function (ignoreParentClass) {
  19970. if (!ignoreParentClass) {
  19971. _super.prototype._updateCache.call(this);
  19972. }
  19973. this._cache.position.copyFrom(this.position);
  19974. this._cache.upVector.copyFrom(this.upVector);
  19975. };
  19976. // Synchronized
  19977. Camera.prototype._isSynchronized = function () {
  19978. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19979. };
  19980. Camera.prototype._isSynchronizedViewMatrix = function () {
  19981. if (!_super.prototype._isSynchronized.call(this))
  19982. return false;
  19983. return this._cache.position.equals(this.position)
  19984. && this._cache.upVector.equals(this.upVector)
  19985. && this.isSynchronizedWithParent();
  19986. };
  19987. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19988. var check = this._cache.mode === this.mode
  19989. && this._cache.minZ === this.minZ
  19990. && this._cache.maxZ === this.maxZ;
  19991. if (!check) {
  19992. return false;
  19993. }
  19994. var engine = this.getEngine();
  19995. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19996. check = this._cache.fov === this.fov
  19997. && this._cache.fovMode === this.fovMode
  19998. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19999. }
  20000. else {
  20001. check = this._cache.orthoLeft === this.orthoLeft
  20002. && this._cache.orthoRight === this.orthoRight
  20003. && this._cache.orthoBottom === this.orthoBottom
  20004. && this._cache.orthoTop === this.orthoTop
  20005. && this._cache.renderWidth === engine.getRenderWidth()
  20006. && this._cache.renderHeight === engine.getRenderHeight();
  20007. }
  20008. return check;
  20009. };
  20010. // Controls
  20011. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20012. };
  20013. Camera.prototype.detachControl = function (element) {
  20014. };
  20015. Camera.prototype.update = function () {
  20016. this._checkInputs();
  20017. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20018. this._updateRigCameras();
  20019. }
  20020. };
  20021. Camera.prototype._checkInputs = function () {
  20022. this.onAfterCheckInputsObservable.notifyObservers(this);
  20023. };
  20024. Object.defineProperty(Camera.prototype, "rigCameras", {
  20025. get: function () {
  20026. return this._rigCameras;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20032. get: function () {
  20033. return this._rigPostProcess;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20039. // invalidate framebuffer
  20040. if (this._postProcesses.length > 0) {
  20041. this._postProcesses[0].markTextureDirty();
  20042. }
  20043. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20044. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20045. var cam = this._rigCameras[i];
  20046. var rigPostProcess = cam._rigPostProcess;
  20047. // for VR rig, there does not have to be a post process
  20048. if (rigPostProcess) {
  20049. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20050. if (isPass) {
  20051. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20052. cam.isIntermediate = this._postProcesses.length === 0;
  20053. }
  20054. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20055. rigPostProcess.markTextureDirty();
  20056. }
  20057. else {
  20058. cam._postProcesses = this._postProcesses.slice(0);
  20059. }
  20060. }
  20061. };
  20062. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20063. if (insertAt === void 0) { insertAt = null; }
  20064. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20065. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20066. return 0;
  20067. }
  20068. if (insertAt == null || insertAt < 0) {
  20069. this._postProcesses.push(postProcess);
  20070. }
  20071. else {
  20072. this._postProcesses.splice(insertAt, 0, postProcess);
  20073. }
  20074. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20075. return this._postProcesses.indexOf(postProcess);
  20076. };
  20077. Camera.prototype.detachPostProcess = function (postProcess) {
  20078. var idx = this._postProcesses.indexOf(postProcess);
  20079. if (idx !== -1) {
  20080. this._postProcesses.splice(idx, 1);
  20081. }
  20082. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20083. };
  20084. Camera.prototype.getWorldMatrix = function () {
  20085. if (!this._worldMatrix) {
  20086. this._worldMatrix = BABYLON.Matrix.Identity();
  20087. }
  20088. var viewMatrix = this.getViewMatrix();
  20089. viewMatrix.invertToRef(this._worldMatrix);
  20090. return this._worldMatrix;
  20091. };
  20092. Camera.prototype._getViewMatrix = function () {
  20093. return BABYLON.Matrix.Identity();
  20094. };
  20095. Camera.prototype.getViewMatrix = function (force) {
  20096. if (!force && this._isSynchronizedViewMatrix()) {
  20097. return this._computedViewMatrix;
  20098. }
  20099. this.updateCache();
  20100. this._computedViewMatrix = this._getViewMatrix();
  20101. this._currentRenderId = this.getScene().getRenderId();
  20102. this._refreshFrustumPlanes = true;
  20103. if (!this.parent || !this.parent.getWorldMatrix) {
  20104. this._globalPosition.copyFrom(this.position);
  20105. }
  20106. else {
  20107. if (!this._worldMatrix) {
  20108. this._worldMatrix = BABYLON.Matrix.Identity();
  20109. }
  20110. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20111. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20112. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20113. this._computedViewMatrix.invert();
  20114. this._markSyncedWithParent();
  20115. }
  20116. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20117. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20118. }
  20119. this.onViewMatrixChangedObservable.notifyObservers(this);
  20120. return this._computedViewMatrix;
  20121. };
  20122. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20123. this._doNotComputeProjectionMatrix = true;
  20124. if (projection !== undefined) {
  20125. this._projectionMatrix = projection;
  20126. }
  20127. };
  20128. ;
  20129. Camera.prototype.unfreezeProjectionMatrix = function () {
  20130. this._doNotComputeProjectionMatrix = false;
  20131. };
  20132. ;
  20133. Camera.prototype.getProjectionMatrix = function (force) {
  20134. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20135. return this._projectionMatrix;
  20136. }
  20137. // Cache
  20138. this._cache.mode = this.mode;
  20139. this._cache.minZ = this.minZ;
  20140. this._cache.maxZ = this.maxZ;
  20141. // Matrix
  20142. this._refreshFrustumPlanes = true;
  20143. var engine = this.getEngine();
  20144. var scene = this.getScene();
  20145. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20146. this._cache.fov = this.fov;
  20147. this._cache.fovMode = this.fovMode;
  20148. this._cache.aspectRatio = engine.getAspectRatio(this);
  20149. if (this.minZ <= 0) {
  20150. this.minZ = 0.1;
  20151. }
  20152. if (scene.useRightHandedSystem) {
  20153. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20154. }
  20155. else {
  20156. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20157. }
  20158. }
  20159. else {
  20160. var halfWidth = engine.getRenderWidth() / 2.0;
  20161. var halfHeight = engine.getRenderHeight() / 2.0;
  20162. if (scene.useRightHandedSystem) {
  20163. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20164. }
  20165. else {
  20166. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20167. }
  20168. this._cache.orthoLeft = this.orthoLeft;
  20169. this._cache.orthoRight = this.orthoRight;
  20170. this._cache.orthoBottom = this.orthoBottom;
  20171. this._cache.orthoTop = this.orthoTop;
  20172. this._cache.renderWidth = engine.getRenderWidth();
  20173. this._cache.renderHeight = engine.getRenderHeight();
  20174. }
  20175. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20176. return this._projectionMatrix;
  20177. };
  20178. Camera.prototype.getTranformationMatrix = function () {
  20179. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20180. return this._transformMatrix;
  20181. };
  20182. Camera.prototype.updateFrustumPlanes = function () {
  20183. if (!this._refreshFrustumPlanes) {
  20184. return;
  20185. }
  20186. this.getTranformationMatrix();
  20187. if (!this._frustumPlanes) {
  20188. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20189. }
  20190. else {
  20191. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20192. }
  20193. this._refreshFrustumPlanes = false;
  20194. };
  20195. Camera.prototype.isInFrustum = function (target) {
  20196. this.updateFrustumPlanes();
  20197. return target.isInFrustum(this._frustumPlanes);
  20198. };
  20199. Camera.prototype.isCompletelyInFrustum = function (target) {
  20200. this.updateFrustumPlanes();
  20201. return target.isCompletelyInFrustum(this._frustumPlanes);
  20202. };
  20203. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20204. if (length === void 0) { length = 100; }
  20205. if (!transform) {
  20206. transform = this.getWorldMatrix();
  20207. }
  20208. if (!origin) {
  20209. origin = this.position;
  20210. }
  20211. var forward = new BABYLON.Vector3(0, 0, 1);
  20212. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20213. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20214. return new BABYLON.Ray(origin, direction, length);
  20215. };
  20216. /**
  20217. * Releases resources associated with this node.
  20218. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20219. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20220. */
  20221. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20222. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20223. // Observables
  20224. this.onViewMatrixChangedObservable.clear();
  20225. this.onProjectionMatrixChangedObservable.clear();
  20226. this.onAfterCheckInputsObservable.clear();
  20227. this.onRestoreStateObservable.clear();
  20228. // Inputs
  20229. if (this.inputs) {
  20230. this.inputs.clear();
  20231. }
  20232. // Animations
  20233. this.getScene().stopAnimation(this);
  20234. // Remove from scene
  20235. this.getScene().removeCamera(this);
  20236. while (this._rigCameras.length > 0) {
  20237. var camera = this._rigCameras.pop();
  20238. if (camera) {
  20239. camera.dispose();
  20240. }
  20241. }
  20242. // Postprocesses
  20243. if (this._rigPostProcess) {
  20244. this._rigPostProcess.dispose(this);
  20245. this._rigPostProcess = null;
  20246. this._postProcesses = [];
  20247. }
  20248. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20249. this._rigPostProcess = null;
  20250. this._postProcesses = [];
  20251. }
  20252. else {
  20253. var i = this._postProcesses.length;
  20254. while (--i >= 0) {
  20255. this._postProcesses[i].dispose(this);
  20256. }
  20257. }
  20258. // Render targets
  20259. var i = this.customRenderTargets.length;
  20260. while (--i >= 0) {
  20261. this.customRenderTargets[i].dispose();
  20262. }
  20263. this.customRenderTargets = [];
  20264. // Active Meshes
  20265. this._activeMeshes.dispose();
  20266. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20267. };
  20268. Object.defineProperty(Camera.prototype, "leftCamera", {
  20269. // ---- Camera rigs section ----
  20270. get: function () {
  20271. if (this._rigCameras.length < 1) {
  20272. return null;
  20273. }
  20274. return this._rigCameras[0];
  20275. },
  20276. enumerable: true,
  20277. configurable: true
  20278. });
  20279. Object.defineProperty(Camera.prototype, "rightCamera", {
  20280. get: function () {
  20281. if (this._rigCameras.length < 2) {
  20282. return null;
  20283. }
  20284. return this._rigCameras[1];
  20285. },
  20286. enumerable: true,
  20287. configurable: true
  20288. });
  20289. Camera.prototype.getLeftTarget = function () {
  20290. if (this._rigCameras.length < 1) {
  20291. return null;
  20292. }
  20293. return this._rigCameras[0].getTarget();
  20294. };
  20295. Camera.prototype.getRightTarget = function () {
  20296. if (this._rigCameras.length < 2) {
  20297. return null;
  20298. }
  20299. return this._rigCameras[1].getTarget();
  20300. };
  20301. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20302. if (this.cameraRigMode === mode) {
  20303. return;
  20304. }
  20305. while (this._rigCameras.length > 0) {
  20306. var camera = this._rigCameras.pop();
  20307. if (camera) {
  20308. camera.dispose();
  20309. }
  20310. }
  20311. this.cameraRigMode = mode;
  20312. this._cameraRigParams = {};
  20313. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20314. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20315. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20316. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20317. // create the rig cameras, unless none
  20318. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20319. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20320. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20321. if (leftCamera && rightCamera) {
  20322. this._rigCameras.push(leftCamera);
  20323. this._rigCameras.push(rightCamera);
  20324. }
  20325. }
  20326. switch (this.cameraRigMode) {
  20327. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20328. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20329. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20330. break;
  20331. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20332. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20333. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20334. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20335. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20336. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20337. break;
  20338. case Camera.RIG_MODE_VR:
  20339. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20340. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20341. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20342. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20343. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20344. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20345. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20346. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20347. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20348. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20349. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20350. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20351. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20352. if (metrics.compensateDistortion) {
  20353. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20354. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20355. }
  20356. break;
  20357. case Camera.RIG_MODE_WEBVR:
  20358. if (rigParams.vrDisplay) {
  20359. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20360. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20361. //Left eye
  20362. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20363. this._rigCameras[0].setCameraRigParameter("left", true);
  20364. //leaving this for future reference
  20365. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20366. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20367. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20368. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20369. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20370. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20371. this._rigCameras[0].parent = this;
  20372. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20373. //Right eye
  20374. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20375. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20376. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20377. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20378. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20379. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20380. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20381. this._rigCameras[1].parent = this;
  20382. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20383. if (Camera.UseAlternateWebVRRendering) {
  20384. this._rigCameras[1]._skipRendering = true;
  20385. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20386. }
  20387. }
  20388. break;
  20389. }
  20390. this._cascadePostProcessesToRigCams();
  20391. this.update();
  20392. };
  20393. Camera.prototype._getVRProjectionMatrix = function () {
  20394. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20395. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20396. return this._projectionMatrix;
  20397. };
  20398. Camera.prototype._updateCameraRotationMatrix = function () {
  20399. //Here for WebVR
  20400. };
  20401. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20402. //Here for WebVR
  20403. };
  20404. /**
  20405. * This function MUST be overwritten by the different WebVR cameras available.
  20406. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20407. */
  20408. Camera.prototype._getWebVRProjectionMatrix = function () {
  20409. return BABYLON.Matrix.Identity();
  20410. };
  20411. /**
  20412. * This function MUST be overwritten by the different WebVR cameras available.
  20413. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20414. */
  20415. Camera.prototype._getWebVRViewMatrix = function () {
  20416. return BABYLON.Matrix.Identity();
  20417. };
  20418. Camera.prototype.setCameraRigParameter = function (name, value) {
  20419. if (!this._cameraRigParams) {
  20420. this._cameraRigParams = {};
  20421. }
  20422. this._cameraRigParams[name] = value;
  20423. //provisionnally:
  20424. if (name === "interaxialDistance") {
  20425. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20426. }
  20427. };
  20428. /**
  20429. * needs to be overridden by children so sub has required properties to be copied
  20430. */
  20431. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20432. return null;
  20433. };
  20434. /**
  20435. * May need to be overridden by children
  20436. */
  20437. Camera.prototype._updateRigCameras = function () {
  20438. for (var i = 0; i < this._rigCameras.length; i++) {
  20439. this._rigCameras[i].minZ = this.minZ;
  20440. this._rigCameras[i].maxZ = this.maxZ;
  20441. this._rigCameras[i].fov = this.fov;
  20442. }
  20443. // only update viewport when ANAGLYPH
  20444. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20445. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20446. }
  20447. };
  20448. Camera.prototype._setupInputs = function () {
  20449. };
  20450. Camera.prototype.serialize = function () {
  20451. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20452. // Type
  20453. serializationObject.type = this.getClassName();
  20454. // Parent
  20455. if (this.parent) {
  20456. serializationObject.parentId = this.parent.id;
  20457. }
  20458. if (this.inputs) {
  20459. this.inputs.serialize(serializationObject);
  20460. }
  20461. // Animations
  20462. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20463. serializationObject.ranges = this.serializeAnimationRanges();
  20464. return serializationObject;
  20465. };
  20466. Camera.prototype.clone = function (name) {
  20467. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20468. };
  20469. Camera.prototype.getDirection = function (localAxis) {
  20470. var result = BABYLON.Vector3.Zero();
  20471. this.getDirectionToRef(localAxis, result);
  20472. return result;
  20473. };
  20474. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20475. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20476. };
  20477. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20478. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20479. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20480. switch (type) {
  20481. case "ArcRotateCamera":
  20482. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20483. case "DeviceOrientationCamera":
  20484. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20485. case "FollowCamera":
  20486. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20487. case "ArcFollowCamera":
  20488. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20489. case "GamepadCamera":
  20490. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20491. case "TouchCamera":
  20492. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20493. case "VirtualJoysticksCamera":
  20494. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20495. case "WebVRFreeCamera":
  20496. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20497. case "WebVRGamepadCamera":
  20498. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20499. case "VRDeviceOrientationFreeCamera":
  20500. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20501. case "VRDeviceOrientationGamepadCamera":
  20502. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20503. case "AnaglyphArcRotateCamera":
  20504. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20505. case "AnaglyphFreeCamera":
  20506. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20507. case "AnaglyphGamepadCamera":
  20508. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20509. case "AnaglyphUniversalCamera":
  20510. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20511. case "StereoscopicArcRotateCamera":
  20512. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20513. case "StereoscopicFreeCamera":
  20514. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20515. case "StereoscopicGamepadCamera":
  20516. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20517. case "StereoscopicUniversalCamera":
  20518. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20519. case "FreeCamera":// Forcing Universal here
  20520. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20521. default:// Universal Camera is the default value
  20522. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20523. }
  20524. };
  20525. Camera.prototype.computeWorldMatrix = function () {
  20526. return this.getWorldMatrix();
  20527. };
  20528. Camera.Parse = function (parsedCamera, scene) {
  20529. var type = parsedCamera.type;
  20530. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20531. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20532. // Parent
  20533. if (parsedCamera.parentId) {
  20534. camera._waitingParentId = parsedCamera.parentId;
  20535. }
  20536. //If camera has an input manager, let it parse inputs settings
  20537. if (camera.inputs) {
  20538. camera.inputs.parse(parsedCamera);
  20539. camera._setupInputs();
  20540. }
  20541. if (camera.setPosition) {
  20542. camera.position.copyFromFloats(0, 0, 0);
  20543. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20544. }
  20545. // Target
  20546. if (parsedCamera.target) {
  20547. if (camera.setTarget) {
  20548. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20549. }
  20550. }
  20551. // Apply 3d rig, when found
  20552. if (parsedCamera.cameraRigMode) {
  20553. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20554. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20555. }
  20556. // Animations
  20557. if (parsedCamera.animations) {
  20558. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20559. var parsedAnimation = parsedCamera.animations[animationIndex];
  20560. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20561. }
  20562. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20563. }
  20564. if (parsedCamera.autoAnimate) {
  20565. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20566. }
  20567. return camera;
  20568. };
  20569. // Statics
  20570. Camera._PERSPECTIVE_CAMERA = 0;
  20571. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20572. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20573. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20574. Camera._RIG_MODE_NONE = 0;
  20575. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20576. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20577. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20578. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20579. Camera._RIG_MODE_VR = 20;
  20580. Camera._RIG_MODE_WEBVR = 21;
  20581. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20582. Camera.UseAlternateWebVRRendering = false;
  20583. __decorate([
  20584. BABYLON.serializeAsVector3()
  20585. ], Camera.prototype, "position", void 0);
  20586. __decorate([
  20587. BABYLON.serializeAsVector3()
  20588. ], Camera.prototype, "upVector", void 0);
  20589. __decorate([
  20590. BABYLON.serialize()
  20591. ], Camera.prototype, "orthoLeft", void 0);
  20592. __decorate([
  20593. BABYLON.serialize()
  20594. ], Camera.prototype, "orthoRight", void 0);
  20595. __decorate([
  20596. BABYLON.serialize()
  20597. ], Camera.prototype, "orthoBottom", void 0);
  20598. __decorate([
  20599. BABYLON.serialize()
  20600. ], Camera.prototype, "orthoTop", void 0);
  20601. __decorate([
  20602. BABYLON.serialize()
  20603. ], Camera.prototype, "fov", void 0);
  20604. __decorate([
  20605. BABYLON.serialize()
  20606. ], Camera.prototype, "minZ", void 0);
  20607. __decorate([
  20608. BABYLON.serialize()
  20609. ], Camera.prototype, "maxZ", void 0);
  20610. __decorate([
  20611. BABYLON.serialize()
  20612. ], Camera.prototype, "inertia", void 0);
  20613. __decorate([
  20614. BABYLON.serialize()
  20615. ], Camera.prototype, "mode", void 0);
  20616. __decorate([
  20617. BABYLON.serialize()
  20618. ], Camera.prototype, "layerMask", void 0);
  20619. __decorate([
  20620. BABYLON.serialize()
  20621. ], Camera.prototype, "fovMode", void 0);
  20622. __decorate([
  20623. BABYLON.serialize()
  20624. ], Camera.prototype, "cameraRigMode", void 0);
  20625. __decorate([
  20626. BABYLON.serialize()
  20627. ], Camera.prototype, "interaxialDistance", void 0);
  20628. __decorate([
  20629. BABYLON.serialize()
  20630. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20631. return Camera;
  20632. }(BABYLON.Node));
  20633. BABYLON.Camera = Camera;
  20634. })(BABYLON || (BABYLON = {}));
  20635. //# sourceMappingURL=babylon.camera.js.map
  20636. var BABYLON;
  20637. (function (BABYLON) {
  20638. var RenderingManager = /** @class */ (function () {
  20639. function RenderingManager(scene) {
  20640. this._renderingGroups = new Array();
  20641. this._autoClearDepthStencil = {};
  20642. this._customOpaqueSortCompareFn = {};
  20643. this._customAlphaTestSortCompareFn = {};
  20644. this._customTransparentSortCompareFn = {};
  20645. this._renderinGroupInfo = null;
  20646. this._scene = scene;
  20647. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20648. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20649. }
  20650. }
  20651. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20652. if (depth === void 0) { depth = true; }
  20653. if (stencil === void 0) { stencil = true; }
  20654. if (this._depthStencilBufferAlreadyCleaned) {
  20655. return;
  20656. }
  20657. this._scene.getEngine().clear(null, false, depth, stencil);
  20658. this._depthStencilBufferAlreadyCleaned = true;
  20659. };
  20660. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20661. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20662. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20663. var info = null;
  20664. if (observable) {
  20665. if (!this._renderinGroupInfo) {
  20666. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20667. }
  20668. info = this._renderinGroupInfo;
  20669. info.scene = this._scene;
  20670. info.camera = this._scene.activeCamera;
  20671. }
  20672. // Dispatch sprites
  20673. if (renderSprites) {
  20674. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20675. var manager = this._scene.spriteManagers[index];
  20676. this.dispatchSprites(manager);
  20677. }
  20678. }
  20679. // Render
  20680. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20681. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20682. var renderingGroup = this._renderingGroups[index];
  20683. if (!renderingGroup && !observable)
  20684. continue;
  20685. var renderingGroupMask = 0;
  20686. // Fire PRECLEAR stage
  20687. if (observable && info) {
  20688. renderingGroupMask = Math.pow(2, index);
  20689. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20690. info.renderingGroupId = index;
  20691. observable.notifyObservers(info, renderingGroupMask);
  20692. }
  20693. // Clear depth/stencil if needed
  20694. if (RenderingManager.AUTOCLEAR) {
  20695. var autoClear = this._autoClearDepthStencil[index];
  20696. if (autoClear && autoClear.autoClear) {
  20697. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20698. }
  20699. }
  20700. if (observable && info) {
  20701. // Fire PREOPAQUE stage
  20702. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20703. observable.notifyObservers(info, renderingGroupMask);
  20704. // Fire PRETRANSPARENT stage
  20705. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20706. observable.notifyObservers(info, renderingGroupMask);
  20707. }
  20708. if (renderingGroup)
  20709. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20710. // Fire POSTTRANSPARENT stage
  20711. if (observable && info) {
  20712. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20713. observable.notifyObservers(info, renderingGroupMask);
  20714. }
  20715. }
  20716. };
  20717. RenderingManager.prototype.reset = function () {
  20718. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20719. var renderingGroup = this._renderingGroups[index];
  20720. if (renderingGroup) {
  20721. renderingGroup.prepare();
  20722. }
  20723. }
  20724. };
  20725. RenderingManager.prototype.dispose = function () {
  20726. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20727. var renderingGroup = this._renderingGroups[index];
  20728. if (renderingGroup) {
  20729. renderingGroup.dispose();
  20730. }
  20731. }
  20732. this._renderingGroups.length = 0;
  20733. };
  20734. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20735. if (this._renderingGroups[renderingGroupId] === undefined) {
  20736. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20737. }
  20738. };
  20739. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20740. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20741. this._prepareRenderingGroup(renderingGroupId);
  20742. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20743. };
  20744. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20745. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20746. this._prepareRenderingGroup(renderingGroupId);
  20747. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20748. };
  20749. /**
  20750. * @param subMesh The submesh to dispatch
  20751. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20752. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20753. */
  20754. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20755. if (mesh === undefined) {
  20756. mesh = subMesh.getMesh();
  20757. }
  20758. var renderingGroupId = mesh.renderingGroupId || 0;
  20759. this._prepareRenderingGroup(renderingGroupId);
  20760. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20761. };
  20762. /**
  20763. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20764. * This allowed control for front to back rendering or reversly depending of the special needs.
  20765. *
  20766. * @param renderingGroupId The rendering group id corresponding to its index
  20767. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20768. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20769. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20770. */
  20771. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20772. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20773. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20774. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20775. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20776. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20777. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20778. if (this._renderingGroups[renderingGroupId]) {
  20779. var group = this._renderingGroups[renderingGroupId];
  20780. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20781. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20782. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20783. }
  20784. };
  20785. /**
  20786. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20787. *
  20788. * @param renderingGroupId The rendering group id corresponding to its index
  20789. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20790. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20791. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20792. */
  20793. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20794. if (depth === void 0) { depth = true; }
  20795. if (stencil === void 0) { stencil = true; }
  20796. this._autoClearDepthStencil[renderingGroupId] = {
  20797. autoClear: autoClearDepthStencil,
  20798. depth: depth,
  20799. stencil: stencil
  20800. };
  20801. };
  20802. /**
  20803. * The max id used for rendering groups (not included)
  20804. */
  20805. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20806. /**
  20807. * The min id used for rendering groups (included)
  20808. */
  20809. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20810. /**
  20811. * Used to globally prevent autoclearing scenes.
  20812. */
  20813. RenderingManager.AUTOCLEAR = true;
  20814. return RenderingManager;
  20815. }());
  20816. BABYLON.RenderingManager = RenderingManager;
  20817. })(BABYLON || (BABYLON = {}));
  20818. //# sourceMappingURL=babylon.renderingManager.js.map
  20819. var BABYLON;
  20820. (function (BABYLON) {
  20821. var RenderingGroup = /** @class */ (function () {
  20822. /**
  20823. * Creates a new rendering group.
  20824. * @param index The rendering group index
  20825. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20826. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20827. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20828. */
  20829. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20830. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20831. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20832. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20833. this.index = index;
  20834. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20835. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20836. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20837. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20838. this._particleSystems = new BABYLON.SmartArray(256);
  20839. this._spriteManagers = new BABYLON.SmartArray(256);
  20840. this._edgesRenderers = new BABYLON.SmartArray(16);
  20841. this._scene = scene;
  20842. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20843. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20844. this.transparentSortCompareFn = transparentSortCompareFn;
  20845. }
  20846. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20847. /**
  20848. * Set the opaque sort comparison function.
  20849. * If null the sub meshes will be render in the order they were created
  20850. */
  20851. set: function (value) {
  20852. this._opaqueSortCompareFn = value;
  20853. if (value) {
  20854. this._renderOpaque = this.renderOpaqueSorted;
  20855. }
  20856. else {
  20857. this._renderOpaque = RenderingGroup.renderUnsorted;
  20858. }
  20859. },
  20860. enumerable: true,
  20861. configurable: true
  20862. });
  20863. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20864. /**
  20865. * Set the alpha test sort comparison function.
  20866. * If null the sub meshes will be render in the order they were created
  20867. */
  20868. set: function (value) {
  20869. this._alphaTestSortCompareFn = value;
  20870. if (value) {
  20871. this._renderAlphaTest = this.renderAlphaTestSorted;
  20872. }
  20873. else {
  20874. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20875. }
  20876. },
  20877. enumerable: true,
  20878. configurable: true
  20879. });
  20880. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20881. /**
  20882. * Set the transparent sort comparison function.
  20883. * If null the sub meshes will be render in the order they were created
  20884. */
  20885. set: function (value) {
  20886. if (value) {
  20887. this._transparentSortCompareFn = value;
  20888. }
  20889. else {
  20890. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20891. }
  20892. this._renderTransparent = this.renderTransparentSorted;
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. /**
  20898. * Render all the sub meshes contained in the group.
  20899. * @param customRenderFunction Used to override the default render behaviour of the group.
  20900. * @returns true if rendered some submeshes.
  20901. */
  20902. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20903. if (customRenderFunction) {
  20904. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20905. return;
  20906. }
  20907. var engine = this._scene.getEngine();
  20908. // Depth only
  20909. if (this._depthOnlySubMeshes.length !== 0) {
  20910. engine.setColorWrite(false);
  20911. this._renderAlphaTest(this._depthOnlySubMeshes);
  20912. engine.setColorWrite(true);
  20913. }
  20914. // Opaque
  20915. if (this._opaqueSubMeshes.length !== 0) {
  20916. this._renderOpaque(this._opaqueSubMeshes);
  20917. }
  20918. // Alpha test
  20919. if (this._alphaTestSubMeshes.length !== 0) {
  20920. this._renderAlphaTest(this._alphaTestSubMeshes);
  20921. }
  20922. var stencilState = engine.getStencilBuffer();
  20923. engine.setStencilBuffer(false);
  20924. // Sprites
  20925. if (renderSprites) {
  20926. this._renderSprites();
  20927. }
  20928. // Particles
  20929. if (renderParticles) {
  20930. this._renderParticles(activeMeshes);
  20931. }
  20932. if (this.onBeforeTransparentRendering) {
  20933. this.onBeforeTransparentRendering();
  20934. }
  20935. // Transparent
  20936. if (this._transparentSubMeshes.length !== 0) {
  20937. this._renderTransparent(this._transparentSubMeshes);
  20938. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20939. }
  20940. // Set back stencil to false in case it changes before the edge renderer.
  20941. engine.setStencilBuffer(false);
  20942. // Edges
  20943. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20944. this._edgesRenderers.data[edgesRendererIndex].render();
  20945. }
  20946. // Restore Stencil state.
  20947. engine.setStencilBuffer(stencilState);
  20948. };
  20949. /**
  20950. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20951. * @param subMeshes The submeshes to render
  20952. */
  20953. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20954. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20955. };
  20956. /**
  20957. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20958. * @param subMeshes The submeshes to render
  20959. */
  20960. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20961. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20962. };
  20963. /**
  20964. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20965. * @param subMeshes The submeshes to render
  20966. */
  20967. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20968. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20969. };
  20970. /**
  20971. * Renders the submeshes in a specified order.
  20972. * @param subMeshes The submeshes to sort before render
  20973. * @param sortCompareFn The comparison function use to sort
  20974. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20975. * @param transparent Specifies to activate blending if true
  20976. */
  20977. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20978. var subIndex = 0;
  20979. var subMesh;
  20980. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20981. for (; subIndex < subMeshes.length; subIndex++) {
  20982. subMesh = subMeshes.data[subIndex];
  20983. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20984. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20985. }
  20986. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20987. if (sortCompareFn) {
  20988. sortedArray.sort(sortCompareFn);
  20989. }
  20990. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20991. subMesh = sortedArray[subIndex];
  20992. if (transparent) {
  20993. var material = subMesh.getMaterial();
  20994. if (material && material.needDepthPrePass) {
  20995. var engine = material.getScene().getEngine();
  20996. engine.setColorWrite(false);
  20997. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20998. subMesh.render(false);
  20999. engine.setColorWrite(true);
  21000. }
  21001. }
  21002. subMesh.render(transparent);
  21003. }
  21004. };
  21005. /**
  21006. * Renders the submeshes in the order they were dispatched (no sort applied).
  21007. * @param subMeshes The submeshes to render
  21008. */
  21009. RenderingGroup.renderUnsorted = function (subMeshes) {
  21010. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21011. var submesh = subMeshes.data[subIndex];
  21012. submesh.render(false);
  21013. }
  21014. };
  21015. /**
  21016. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21017. * are rendered back to front if in the same alpha index.
  21018. *
  21019. * @param a The first submesh
  21020. * @param b The second submesh
  21021. * @returns The result of the comparison
  21022. */
  21023. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21024. // Alpha index first
  21025. if (a._alphaIndex > b._alphaIndex) {
  21026. return 1;
  21027. }
  21028. if (a._alphaIndex < b._alphaIndex) {
  21029. return -1;
  21030. }
  21031. // Then distance to camera
  21032. return RenderingGroup.backToFrontSortCompare(a, b);
  21033. };
  21034. /**
  21035. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21036. * are rendered back to front.
  21037. *
  21038. * @param a The first submesh
  21039. * @param b The second submesh
  21040. * @returns The result of the comparison
  21041. */
  21042. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21043. // Then distance to camera
  21044. if (a._distanceToCamera < b._distanceToCamera) {
  21045. return 1;
  21046. }
  21047. if (a._distanceToCamera > b._distanceToCamera) {
  21048. return -1;
  21049. }
  21050. return 0;
  21051. };
  21052. /**
  21053. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21054. * are rendered front to back (prevent overdraw).
  21055. *
  21056. * @param a The first submesh
  21057. * @param b The second submesh
  21058. * @returns The result of the comparison
  21059. */
  21060. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21061. // Then distance to camera
  21062. if (a._distanceToCamera < b._distanceToCamera) {
  21063. return -1;
  21064. }
  21065. if (a._distanceToCamera > b._distanceToCamera) {
  21066. return 1;
  21067. }
  21068. return 0;
  21069. };
  21070. /**
  21071. * Resets the different lists of submeshes to prepare a new frame.
  21072. */
  21073. RenderingGroup.prototype.prepare = function () {
  21074. this._opaqueSubMeshes.reset();
  21075. this._transparentSubMeshes.reset();
  21076. this._alphaTestSubMeshes.reset();
  21077. this._depthOnlySubMeshes.reset();
  21078. this._particleSystems.reset();
  21079. this._spriteManagers.reset();
  21080. this._edgesRenderers.reset();
  21081. };
  21082. RenderingGroup.prototype.dispose = function () {
  21083. this._opaqueSubMeshes.dispose();
  21084. this._transparentSubMeshes.dispose();
  21085. this._alphaTestSubMeshes.dispose();
  21086. this._depthOnlySubMeshes.dispose();
  21087. this._particleSystems.dispose();
  21088. this._spriteManagers.dispose();
  21089. this._edgesRenderers.dispose();
  21090. };
  21091. /**
  21092. * Inserts the submesh in its correct queue depending on its material.
  21093. * @param subMesh The submesh to dispatch
  21094. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21095. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21096. */
  21097. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21098. // Get mesh and materials if not provided
  21099. if (mesh === undefined) {
  21100. mesh = subMesh.getMesh();
  21101. }
  21102. if (material === undefined) {
  21103. material = subMesh.getMaterial();
  21104. }
  21105. if (material === null || material === undefined) {
  21106. return;
  21107. }
  21108. if (material.needAlphaBlendingForMesh(mesh)) {
  21109. this._transparentSubMeshes.push(subMesh);
  21110. }
  21111. else if (material.needAlphaTesting()) {
  21112. if (material.needDepthPrePass) {
  21113. this._depthOnlySubMeshes.push(subMesh);
  21114. }
  21115. this._alphaTestSubMeshes.push(subMesh);
  21116. }
  21117. else {
  21118. if (material.needDepthPrePass) {
  21119. this._depthOnlySubMeshes.push(subMesh);
  21120. }
  21121. this._opaqueSubMeshes.push(subMesh); // Opaque
  21122. }
  21123. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21124. this._edgesRenderers.push(mesh._edgesRenderer);
  21125. }
  21126. };
  21127. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21128. this._spriteManagers.push(spriteManager);
  21129. };
  21130. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21131. this._particleSystems.push(particleSystem);
  21132. };
  21133. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21134. if (this._particleSystems.length === 0) {
  21135. return;
  21136. }
  21137. // Particles
  21138. var activeCamera = this._scene.activeCamera;
  21139. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21140. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21141. var particleSystem = this._particleSystems.data[particleIndex];
  21142. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21143. continue;
  21144. }
  21145. var emitter = particleSystem.emitter;
  21146. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21147. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21148. }
  21149. }
  21150. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21151. };
  21152. RenderingGroup.prototype._renderSprites = function () {
  21153. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21154. return;
  21155. }
  21156. // Sprites
  21157. var activeCamera = this._scene.activeCamera;
  21158. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21159. for (var id = 0; id < this._spriteManagers.length; id++) {
  21160. var spriteManager = this._spriteManagers.data[id];
  21161. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21162. spriteManager.render();
  21163. }
  21164. }
  21165. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21166. };
  21167. return RenderingGroup;
  21168. }());
  21169. BABYLON.RenderingGroup = RenderingGroup;
  21170. })(BABYLON || (BABYLON = {}));
  21171. //# sourceMappingURL=babylon.renderingGroup.js.map
  21172. var BABYLON;
  21173. (function (BABYLON) {
  21174. var ClickInfo = /** @class */ (function () {
  21175. function ClickInfo() {
  21176. this._singleClick = false;
  21177. this._doubleClick = false;
  21178. this._hasSwiped = false;
  21179. this._ignore = false;
  21180. }
  21181. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21182. get: function () {
  21183. return this._singleClick;
  21184. },
  21185. set: function (b) {
  21186. this._singleClick = b;
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21192. get: function () {
  21193. return this._doubleClick;
  21194. },
  21195. set: function (b) {
  21196. this._doubleClick = b;
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21202. get: function () {
  21203. return this._hasSwiped;
  21204. },
  21205. set: function (b) {
  21206. this._hasSwiped = b;
  21207. },
  21208. enumerable: true,
  21209. configurable: true
  21210. });
  21211. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21212. get: function () {
  21213. return this._ignore;
  21214. },
  21215. set: function (b) {
  21216. this._ignore = b;
  21217. },
  21218. enumerable: true,
  21219. configurable: true
  21220. });
  21221. return ClickInfo;
  21222. }());
  21223. /**
  21224. * This class is used by the onRenderingGroupObservable
  21225. */
  21226. var RenderingGroupInfo = /** @class */ (function () {
  21227. function RenderingGroupInfo() {
  21228. }
  21229. /**
  21230. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21231. * This stage will be fired no matter what
  21232. */
  21233. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21234. /**
  21235. * Called before opaque object are rendered.
  21236. * This stage will be fired only if there's 3D Opaque content to render
  21237. */
  21238. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21239. /**
  21240. * Called after the opaque objects are rendered and before the transparent ones
  21241. * This stage will be fired only if there's 3D transparent content to render
  21242. */
  21243. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21244. /**
  21245. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21246. * This stage will be fired no matter what
  21247. */
  21248. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21249. return RenderingGroupInfo;
  21250. }());
  21251. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21252. /**
  21253. * Represents a scene to be rendered by the engine.
  21254. * @see http://doc.babylonjs.com/page.php?p=21911
  21255. */
  21256. var Scene = /** @class */ (function () {
  21257. /**
  21258. * @constructor
  21259. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21260. */
  21261. function Scene(engine) {
  21262. // Members
  21263. this.autoClear = true;
  21264. this.autoClearDepthAndStencil = true;
  21265. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21266. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21267. this.forceWireframe = false;
  21268. this._forcePointsCloud = false;
  21269. this.forceShowBoundingBoxes = false;
  21270. this.animationsEnabled = true;
  21271. this.useConstantAnimationDeltaTime = false;
  21272. this.constantlyUpdateMeshUnderPointer = false;
  21273. this.hoverCursor = "pointer";
  21274. this.defaultCursor = "";
  21275. /**
  21276. * This is used to call preventDefault() on pointer down
  21277. * in order to block unwanted artifacts like system double clicks
  21278. */
  21279. this.preventDefaultOnPointerDown = true;
  21280. // Metadata
  21281. this.metadata = null;
  21282. /**
  21283. * An event triggered when the scene is disposed.
  21284. * @type {BABYLON.Observable}
  21285. */
  21286. this.onDisposeObservable = new BABYLON.Observable();
  21287. /**
  21288. * An event triggered before rendering the scene (right after animations and physics)
  21289. * @type {BABYLON.Observable}
  21290. */
  21291. this.onBeforeRenderObservable = new BABYLON.Observable();
  21292. /**
  21293. * An event triggered after rendering the scene
  21294. * @type {BABYLON.Observable}
  21295. */
  21296. this.onAfterRenderObservable = new BABYLON.Observable();
  21297. /**
  21298. * An event triggered before animating the scene
  21299. * @type {BABYLON.Observable}
  21300. */
  21301. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21302. /**
  21303. * An event triggered after animations processing
  21304. * @type {BABYLON.Observable}
  21305. */
  21306. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21307. /**
  21308. * An event triggered before draw calls are ready to be sent
  21309. * @type {BABYLON.Observable}
  21310. */
  21311. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21312. /**
  21313. * An event triggered after draw calls have been sent
  21314. * @type {BABYLON.Observable}
  21315. */
  21316. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21317. /**
  21318. * An event triggered when physic simulation is about to be run
  21319. * @type {BABYLON.Observable}
  21320. */
  21321. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21322. /**
  21323. * An event triggered when physic simulation has been done
  21324. * @type {BABYLON.Observable}
  21325. */
  21326. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21327. /**
  21328. * An event triggered when the scene is ready
  21329. * @type {BABYLON.Observable}
  21330. */
  21331. this.onReadyObservable = new BABYLON.Observable();
  21332. /**
  21333. * An event triggered before rendering a camera
  21334. * @type {BABYLON.Observable}
  21335. */
  21336. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21337. /**
  21338. * An event triggered after rendering a camera
  21339. * @type {BABYLON.Observable}
  21340. */
  21341. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21342. /**
  21343. * An event triggered when active meshes evaluation is about to start
  21344. * @type {BABYLON.Observable}
  21345. */
  21346. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21347. /**
  21348. * An event triggered when active meshes evaluation is done
  21349. * @type {BABYLON.Observable}
  21350. */
  21351. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21352. /**
  21353. * An event triggered when particles rendering is about to start
  21354. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21355. * @type {BABYLON.Observable}
  21356. */
  21357. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21358. /**
  21359. * An event triggered when particles rendering is done
  21360. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21361. * @type {BABYLON.Observable}
  21362. */
  21363. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21364. /**
  21365. * An event triggered when sprites rendering is about to start
  21366. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21367. * @type {BABYLON.Observable}
  21368. */
  21369. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21370. /**
  21371. * An event triggered when sprites rendering is done
  21372. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21373. * @type {BABYLON.Observable}
  21374. */
  21375. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21376. /**
  21377. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21378. * @type {BABYLON.Observable}
  21379. */
  21380. this.onDataLoadedObservable = new BABYLON.Observable();
  21381. /**
  21382. * An event triggered when a camera is created
  21383. * @type {BABYLON.Observable}
  21384. */
  21385. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21386. /**
  21387. * An event triggered when a camera is removed
  21388. * @type {BABYLON.Observable}
  21389. */
  21390. this.onCameraRemovedObservable = new BABYLON.Observable();
  21391. /**
  21392. * An event triggered when a light is created
  21393. * @type {BABYLON.Observable}
  21394. */
  21395. this.onNewLightAddedObservable = new BABYLON.Observable();
  21396. /**
  21397. * An event triggered when a light is removed
  21398. * @type {BABYLON.Observable}
  21399. */
  21400. this.onLightRemovedObservable = new BABYLON.Observable();
  21401. /**
  21402. * An event triggered when a geometry is created
  21403. * @type {BABYLON.Observable}
  21404. */
  21405. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21406. /**
  21407. * An event triggered when a geometry is removed
  21408. * @type {BABYLON.Observable}
  21409. */
  21410. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21411. /**
  21412. * An event triggered when a transform node is created
  21413. * @type {BABYLON.Observable}
  21414. */
  21415. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21416. /**
  21417. * An event triggered when a transform node is removed
  21418. * @type {BABYLON.Observable}
  21419. */
  21420. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21421. /**
  21422. * An event triggered when a mesh is created
  21423. * @type {BABYLON.Observable}
  21424. */
  21425. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21426. /**
  21427. * An event triggered when a mesh is removed
  21428. * @type {BABYLON.Observable}
  21429. */
  21430. this.onMeshRemovedObservable = new BABYLON.Observable();
  21431. /**
  21432. * An event triggered when render targets are about to be rendered
  21433. * Can happen multiple times per frame.
  21434. * @type {BABYLON.Observable}
  21435. */
  21436. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21437. /**
  21438. * An event triggered when render targets were rendered.
  21439. * Can happen multiple times per frame.
  21440. * @type {BABYLON.Observable}
  21441. */
  21442. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21443. /**
  21444. * An event triggered before calculating deterministic simulation step
  21445. * @type {BABYLON.Observable}
  21446. */
  21447. this.onBeforeStepObservable = new BABYLON.Observable();
  21448. /**
  21449. * An event triggered after calculating deterministic simulation step
  21450. * @type {BABYLON.Observable}
  21451. */
  21452. this.onAfterStepObservable = new BABYLON.Observable();
  21453. /**
  21454. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21455. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21456. * 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)
  21457. */
  21458. this.onRenderingGroupObservable = new BABYLON.Observable();
  21459. // Animations
  21460. this.animations = [];
  21461. /**
  21462. * 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).
  21463. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21464. */
  21465. this.onPrePointerObservable = new BABYLON.Observable();
  21466. /**
  21467. * Observable event triggered each time an input event is received from the rendering canvas
  21468. */
  21469. this.onPointerObservable = new BABYLON.Observable();
  21470. this._meshPickProceed = false;
  21471. this._currentPickResult = null;
  21472. this._previousPickResult = null;
  21473. this._totalPointersPressed = 0;
  21474. this._doubleClickOccured = false;
  21475. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21476. this.cameraToUseForPointers = null;
  21477. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21478. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21479. this._startingPointerTime = 0;
  21480. this._previousStartingPointerTime = 0;
  21481. // Deterministic lockstep
  21482. this._timeAccumulator = 0;
  21483. this._currentStepId = 0;
  21484. this._currentInternalStep = 0;
  21485. // Keyboard
  21486. /**
  21487. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21488. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21489. */
  21490. this.onPreKeyboardObservable = new BABYLON.Observable();
  21491. /**
  21492. * Observable event triggered each time an keyboard event is received from the hosting window
  21493. */
  21494. this.onKeyboardObservable = new BABYLON.Observable();
  21495. // Coordinate system
  21496. /**
  21497. * use right-handed coordinate system on this scene.
  21498. * @type {boolean}
  21499. */
  21500. this._useRightHandedSystem = false;
  21501. // Fog
  21502. this._fogEnabled = true;
  21503. this._fogMode = Scene.FOGMODE_NONE;
  21504. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21505. this.fogDensity = 0.1;
  21506. this.fogStart = 0;
  21507. this.fogEnd = 1000.0;
  21508. // Lights
  21509. /**
  21510. * is shadow enabled on this scene.
  21511. * @type {boolean}
  21512. */
  21513. this._shadowsEnabled = true;
  21514. /**
  21515. * is light enabled on this scene.
  21516. * @type {boolean}
  21517. */
  21518. this._lightsEnabled = true;
  21519. /**
  21520. * All of the lights added to this scene.
  21521. * @see BABYLON.Light
  21522. * @type {BABYLON.Light[]}
  21523. */
  21524. this.lights = new Array();
  21525. // Cameras
  21526. /** All of the cameras added to this scene. */
  21527. this.cameras = new Array();
  21528. /** All of the active cameras added to this scene. */
  21529. this.activeCameras = new Array();
  21530. // Meshes
  21531. /**
  21532. * All of the tranform nodes added to this scene.
  21533. * @see BABYLON.TransformNode
  21534. * @type {BABYLON.TransformNode[]}
  21535. */
  21536. this.transformNodes = new Array();
  21537. /**
  21538. * All of the (abstract) meshes added to this scene.
  21539. * @see BABYLON.AbstractMesh
  21540. * @type {BABYLON.AbstractMesh[]}
  21541. */
  21542. this.meshes = new Array();
  21543. /**
  21544. * All of the animation groups added to this scene.
  21545. * @see BABYLON.AnimationGroup
  21546. * @type {BABYLON.AnimationGroup[]}
  21547. */
  21548. this.animationGroups = new Array();
  21549. // Geometries
  21550. this._geometries = new Array();
  21551. this.materials = new Array();
  21552. this.multiMaterials = new Array();
  21553. // Textures
  21554. this._texturesEnabled = true;
  21555. this.textures = new Array();
  21556. // Particles
  21557. this.particlesEnabled = true;
  21558. this.particleSystems = new Array();
  21559. // Sprites
  21560. this.spritesEnabled = true;
  21561. this.spriteManagers = new Array();
  21562. /**
  21563. * The list of layers (background and foreground) of the scene.
  21564. */
  21565. this.layers = new Array();
  21566. /**
  21567. * The list of effect layers (highlights/glow) contained in the scene.
  21568. */
  21569. this.effectLayers = new Array();
  21570. // Skeletons
  21571. this._skeletonsEnabled = true;
  21572. this.skeletons = new Array();
  21573. // Morph targets
  21574. this.morphTargetManagers = new Array();
  21575. // Lens flares
  21576. this.lensFlaresEnabled = true;
  21577. this.lensFlareSystems = new Array();
  21578. // Collisions
  21579. this.collisionsEnabled = true;
  21580. /** Defines the gravity applied to this scene */
  21581. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21582. // Postprocesses
  21583. this.postProcesses = new Array();
  21584. this.postProcessesEnabled = true;
  21585. // Customs render targets
  21586. this.renderTargetsEnabled = true;
  21587. this.dumpNextRenderTargets = false;
  21588. this.customRenderTargets = new Array();
  21589. // Imported meshes
  21590. this.importedMeshesFiles = new Array();
  21591. // Probes
  21592. this.probesEnabled = true;
  21593. this.reflectionProbes = new Array();
  21594. this._actionManagers = new Array();
  21595. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21596. // Procedural textures
  21597. this.proceduralTexturesEnabled = true;
  21598. this._proceduralTextures = new Array();
  21599. this.soundTracks = new Array();
  21600. this._audioEnabled = true;
  21601. this._headphone = false;
  21602. // Performance counters
  21603. this._totalVertices = new BABYLON.PerfCounter();
  21604. this._activeIndices = new BABYLON.PerfCounter();
  21605. this._activeParticles = new BABYLON.PerfCounter();
  21606. this._activeBones = new BABYLON.PerfCounter();
  21607. this._animationTime = 0;
  21608. this.animationTimeScale = 1;
  21609. this._renderId = 0;
  21610. this._executeWhenReadyTimeoutId = -1;
  21611. this._intermediateRendering = false;
  21612. this._viewUpdateFlag = -1;
  21613. this._projectionUpdateFlag = -1;
  21614. this._alternateViewUpdateFlag = -1;
  21615. this._alternateProjectionUpdateFlag = -1;
  21616. this._toBeDisposed = new BABYLON.SmartArray(256);
  21617. this._activeRequests = new Array();
  21618. this._pendingData = new Array();
  21619. this._isDisposed = false;
  21620. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21621. this._activeMeshes = new BABYLON.SmartArray(256);
  21622. this._processedMaterials = new BABYLON.SmartArray(256);
  21623. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21624. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21625. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21626. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21627. this._activeAnimatables = new Array();
  21628. this._transformMatrix = BABYLON.Matrix.Zero();
  21629. this._useAlternateCameraConfiguration = false;
  21630. this._alternateRendering = false;
  21631. this.requireLightSorting = false;
  21632. this._depthRenderer = {};
  21633. this._activeMeshesFrozen = false;
  21634. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21635. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21636. this._engine.scenes.push(this);
  21637. this._uid = null;
  21638. this._renderingManager = new BABYLON.RenderingManager(this);
  21639. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21640. if (BABYLON.OutlineRenderer) {
  21641. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21642. }
  21643. if (BABYLON.Tools.IsWindowObjectExist()) {
  21644. this.attachControl();
  21645. }
  21646. //simplification queue
  21647. if (BABYLON.SimplificationQueue) {
  21648. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21649. }
  21650. //collision coordinator initialization. For now legacy per default.
  21651. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21652. // Uniform Buffer
  21653. this._createUbo();
  21654. // Default Image processing definition.
  21655. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21656. }
  21657. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21658. /** The fog is deactivated */
  21659. get: function () {
  21660. return Scene._FOGMODE_NONE;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21666. /** The fog density is following an exponential function */
  21667. get: function () {
  21668. return Scene._FOGMODE_EXP;
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21674. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21675. get: function () {
  21676. return Scene._FOGMODE_EXP2;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21682. /** The fog density is following a linear function. */
  21683. get: function () {
  21684. return Scene._FOGMODE_LINEAR;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21690. /**
  21691. * Texture used in all pbr material as the reflection texture.
  21692. * As in the majority of the scene they are the same (exception for multi room and so on),
  21693. * this is easier to reference from here than from all the materials.
  21694. */
  21695. get: function () {
  21696. return this._environmentTexture;
  21697. },
  21698. /**
  21699. * Texture used in all pbr material as the reflection texture.
  21700. * As in the majority of the scene they are the same (exception for multi room and so on),
  21701. * this is easier to set here than in all the materials.
  21702. */
  21703. set: function (value) {
  21704. if (this._environmentTexture === value) {
  21705. return;
  21706. }
  21707. this._environmentTexture = value;
  21708. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21709. },
  21710. enumerable: true,
  21711. configurable: true
  21712. });
  21713. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21714. /**
  21715. * Default image processing configuration used either in the rendering
  21716. * Forward main pass or through the imageProcessingPostProcess if present.
  21717. * As in the majority of the scene they are the same (exception for multi camera),
  21718. * this is easier to reference from here than from all the materials and post process.
  21719. *
  21720. * No setter as we it is a shared configuration, you can set the values instead.
  21721. */
  21722. get: function () {
  21723. return this._imageProcessingConfiguration;
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21729. get: function () {
  21730. return this._forcePointsCloud;
  21731. },
  21732. set: function (value) {
  21733. if (this._forcePointsCloud === value) {
  21734. return;
  21735. }
  21736. this._forcePointsCloud = value;
  21737. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Scene.prototype, "onDispose", {
  21743. /** A function to be executed when this scene is disposed. */
  21744. set: function (callback) {
  21745. if (this._onDisposeObserver) {
  21746. this.onDisposeObservable.remove(this._onDisposeObserver);
  21747. }
  21748. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. Object.defineProperty(Scene.prototype, "beforeRender", {
  21754. /** A function to be executed before rendering this scene */
  21755. set: function (callback) {
  21756. if (this._onBeforeRenderObserver) {
  21757. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21758. }
  21759. if (callback) {
  21760. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21761. }
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Object.defineProperty(Scene.prototype, "afterRender", {
  21767. /** A function to be executed after rendering this scene */
  21768. set: function (callback) {
  21769. if (this._onAfterRenderObserver) {
  21770. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21771. }
  21772. if (callback) {
  21773. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21774. }
  21775. },
  21776. enumerable: true,
  21777. configurable: true
  21778. });
  21779. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21780. set: function (callback) {
  21781. if (this._onBeforeCameraRenderObserver) {
  21782. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21783. }
  21784. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21790. set: function (callback) {
  21791. if (this._onAfterCameraRenderObserver) {
  21792. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21793. }
  21794. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21795. },
  21796. enumerable: true,
  21797. configurable: true
  21798. });
  21799. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21800. get: function () {
  21801. if (!this._gamepadManager) {
  21802. this._gamepadManager = new BABYLON.GamepadManager(this);
  21803. }
  21804. return this._gamepadManager;
  21805. },
  21806. enumerable: true,
  21807. configurable: true
  21808. });
  21809. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21810. get: function () {
  21811. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21817. get: function () {
  21818. return this._useRightHandedSystem;
  21819. },
  21820. set: function (value) {
  21821. if (this._useRightHandedSystem === value) {
  21822. return;
  21823. }
  21824. this._useRightHandedSystem = value;
  21825. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Scene.prototype.setStepId = function (newStepId) {
  21831. this._currentStepId = newStepId;
  21832. };
  21833. ;
  21834. Scene.prototype.getStepId = function () {
  21835. return this._currentStepId;
  21836. };
  21837. ;
  21838. Scene.prototype.getInternalStep = function () {
  21839. return this._currentInternalStep;
  21840. };
  21841. ;
  21842. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21843. get: function () {
  21844. return this._fogEnabled;
  21845. },
  21846. /**
  21847. * is fog enabled on this scene.
  21848. */
  21849. set: function (value) {
  21850. if (this._fogEnabled === value) {
  21851. return;
  21852. }
  21853. this._fogEnabled = value;
  21854. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(Scene.prototype, "fogMode", {
  21860. get: function () {
  21861. return this._fogMode;
  21862. },
  21863. set: function (value) {
  21864. if (this._fogMode === value) {
  21865. return;
  21866. }
  21867. this._fogMode = value;
  21868. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21874. get: function () {
  21875. return this._shadowsEnabled;
  21876. },
  21877. set: function (value) {
  21878. if (this._shadowsEnabled === value) {
  21879. return;
  21880. }
  21881. this._shadowsEnabled = value;
  21882. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21888. get: function () {
  21889. return this._lightsEnabled;
  21890. },
  21891. set: function (value) {
  21892. if (this._lightsEnabled === value) {
  21893. return;
  21894. }
  21895. this._lightsEnabled = value;
  21896. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21902. /** The default material used on meshes when no material is affected */
  21903. get: function () {
  21904. if (!this._defaultMaterial) {
  21905. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21906. }
  21907. return this._defaultMaterial;
  21908. },
  21909. /** The default material used on meshes when no material is affected */
  21910. set: function (value) {
  21911. this._defaultMaterial = value;
  21912. },
  21913. enumerable: true,
  21914. configurable: true
  21915. });
  21916. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21917. get: function () {
  21918. return this._texturesEnabled;
  21919. },
  21920. set: function (value) {
  21921. if (this._texturesEnabled === value) {
  21922. return;
  21923. }
  21924. this._texturesEnabled = value;
  21925. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21931. get: function () {
  21932. return this._skeletonsEnabled;
  21933. },
  21934. set: function (value) {
  21935. if (this._skeletonsEnabled === value) {
  21936. return;
  21937. }
  21938. this._skeletonsEnabled = value;
  21939. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21945. get: function () {
  21946. if (!this._postProcessRenderPipelineManager) {
  21947. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21948. }
  21949. return this._postProcessRenderPipelineManager;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21955. get: function () {
  21956. if (!this._mainSoundTrack) {
  21957. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21958. }
  21959. return this._mainSoundTrack;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21965. get: function () {
  21966. return this._alternateRendering;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21972. get: function () {
  21973. return this._frustumPlanes;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21979. /**
  21980. * Gets the current geometry buffer associated to the scene.
  21981. */
  21982. get: function () {
  21983. return this._geometryBufferRenderer;
  21984. },
  21985. /**
  21986. * Sets the current geometry buffer for the scene.
  21987. */
  21988. set: function (geometryBufferRenderer) {
  21989. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21990. this._geometryBufferRenderer = geometryBufferRenderer;
  21991. }
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. Object.defineProperty(Scene.prototype, "debugLayer", {
  21997. // Properties
  21998. get: function () {
  21999. if (!this._debugLayer) {
  22000. this._debugLayer = new BABYLON.DebugLayer(this);
  22001. }
  22002. return this._debugLayer;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22008. get: function () {
  22009. return this._workerCollisions;
  22010. },
  22011. set: function (enabled) {
  22012. if (!BABYLON.CollisionCoordinatorLegacy) {
  22013. return;
  22014. }
  22015. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22016. this._workerCollisions = enabled;
  22017. if (this.collisionCoordinator) {
  22018. this.collisionCoordinator.destroy();
  22019. }
  22020. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22021. this.collisionCoordinator.init(this);
  22022. },
  22023. enumerable: true,
  22024. configurable: true
  22025. });
  22026. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22027. get: function () {
  22028. return this._selectionOctree;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22034. /**
  22035. * The mesh that is currently under the pointer.
  22036. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22037. */
  22038. get: function () {
  22039. return this._pointerOverMesh;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Scene.prototype, "pointerX", {
  22045. /**
  22046. * Current on-screen X position of the pointer
  22047. * @return {number} X position of the pointer
  22048. */
  22049. get: function () {
  22050. return this._pointerX;
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Object.defineProperty(Scene.prototype, "pointerY", {
  22056. /**
  22057. * Current on-screen Y position of the pointer
  22058. * @return {number} Y position of the pointer
  22059. */
  22060. get: function () {
  22061. return this._pointerY;
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Scene.prototype.getCachedMaterial = function () {
  22067. return this._cachedMaterial;
  22068. };
  22069. Scene.prototype.getCachedEffect = function () {
  22070. return this._cachedEffect;
  22071. };
  22072. Scene.prototype.getCachedVisibility = function () {
  22073. return this._cachedVisibility;
  22074. };
  22075. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22076. if (visibility === void 0) { visibility = 1; }
  22077. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22078. };
  22079. Scene.prototype.getBoundingBoxRenderer = function () {
  22080. if (!this._boundingBoxRenderer) {
  22081. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22082. }
  22083. return this._boundingBoxRenderer;
  22084. };
  22085. Scene.prototype.getOutlineRenderer = function () {
  22086. return this._outlineRenderer;
  22087. };
  22088. Scene.prototype.getEngine = function () {
  22089. return this._engine;
  22090. };
  22091. Scene.prototype.getTotalVertices = function () {
  22092. return this._totalVertices.current;
  22093. };
  22094. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22095. get: function () {
  22096. return this._totalVertices;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Scene.prototype.getActiveIndices = function () {
  22102. return this._activeIndices.current;
  22103. };
  22104. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22105. get: function () {
  22106. return this._activeIndices;
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. Scene.prototype.getActiveParticles = function () {
  22112. return this._activeParticles.current;
  22113. };
  22114. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22115. get: function () {
  22116. return this._activeParticles;
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. Scene.prototype.getActiveBones = function () {
  22122. return this._activeBones.current;
  22123. };
  22124. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22125. get: function () {
  22126. return this._activeBones;
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. // Stats
  22132. Scene.prototype.getInterFramePerfCounter = function () {
  22133. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22134. return 0;
  22135. };
  22136. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22137. get: function () {
  22138. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22139. return null;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Scene.prototype.getLastFrameDuration = function () {
  22145. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22146. return 0;
  22147. };
  22148. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22149. get: function () {
  22150. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22151. return null;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22157. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22158. return 0;
  22159. };
  22160. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22161. get: function () {
  22162. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22163. return null;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Scene.prototype.getActiveMeshes = function () {
  22169. return this._activeMeshes;
  22170. };
  22171. Scene.prototype.getRenderTargetsDuration = function () {
  22172. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22173. return 0;
  22174. };
  22175. Scene.prototype.getRenderDuration = function () {
  22176. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22177. return 0;
  22178. };
  22179. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22180. get: function () {
  22181. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22182. return null;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Scene.prototype.getParticlesDuration = function () {
  22188. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22189. return 0;
  22190. };
  22191. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22192. get: function () {
  22193. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22194. return null;
  22195. },
  22196. enumerable: true,
  22197. configurable: true
  22198. });
  22199. Scene.prototype.getSpritesDuration = function () {
  22200. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22201. return 0;
  22202. };
  22203. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22204. get: function () {
  22205. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22206. return null;
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. Scene.prototype.getAnimationRatio = function () {
  22212. return this._animationRatio;
  22213. };
  22214. Scene.prototype.getRenderId = function () {
  22215. return this._renderId;
  22216. };
  22217. Scene.prototype.incrementRenderId = function () {
  22218. this._renderId++;
  22219. };
  22220. Scene.prototype._updatePointerPosition = function (evt) {
  22221. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22222. if (!canvasRect) {
  22223. return;
  22224. }
  22225. this._pointerX = evt.clientX - canvasRect.left;
  22226. this._pointerY = evt.clientY - canvasRect.top;
  22227. this._unTranslatedPointerX = this._pointerX;
  22228. this._unTranslatedPointerY = this._pointerY;
  22229. };
  22230. Scene.prototype._createUbo = function () {
  22231. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22232. this._sceneUbo.addUniform("viewProjection", 16);
  22233. this._sceneUbo.addUniform("view", 16);
  22234. };
  22235. Scene.prototype._createAlternateUbo = function () {
  22236. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22237. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22238. this._alternateSceneUbo.addUniform("view", 16);
  22239. };
  22240. // Pointers handling
  22241. /**
  22242. * Use this method to simulate a pointer move on a mesh
  22243. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22244. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22245. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22246. */
  22247. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22248. var evt = new PointerEvent("pointermove", pointerEventInit);
  22249. return this._processPointerMove(pickResult, evt);
  22250. };
  22251. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22252. var canvas = this._engine.getRenderingCanvas();
  22253. if (!canvas) {
  22254. return this;
  22255. }
  22256. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22257. this.setPointerOverSprite(null);
  22258. this.setPointerOverMesh(pickResult.pickedMesh);
  22259. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22260. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22261. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22262. }
  22263. else {
  22264. canvas.style.cursor = this.hoverCursor;
  22265. }
  22266. }
  22267. else {
  22268. canvas.style.cursor = this.defaultCursor;
  22269. }
  22270. }
  22271. else {
  22272. this.setPointerOverMesh(null);
  22273. // Sprites
  22274. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22275. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22276. this.setPointerOverSprite(pickResult.pickedSprite);
  22277. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22278. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22279. }
  22280. else {
  22281. canvas.style.cursor = this.hoverCursor;
  22282. }
  22283. }
  22284. else {
  22285. this.setPointerOverSprite(null);
  22286. // Restore pointer
  22287. canvas.style.cursor = this.defaultCursor;
  22288. }
  22289. }
  22290. if (pickResult) {
  22291. if (this.onPointerMove) {
  22292. this.onPointerMove(evt, pickResult);
  22293. }
  22294. if (this.onPointerObservable.hasObservers()) {
  22295. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22296. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22297. this.onPointerObservable.notifyObservers(pi, type);
  22298. }
  22299. }
  22300. return this;
  22301. };
  22302. /**
  22303. * Use this method to simulate a pointer down on a mesh
  22304. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22305. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22306. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22307. */
  22308. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22309. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22310. return this._processPointerDown(pickResult, evt);
  22311. };
  22312. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22313. var _this = this;
  22314. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22315. this._pickedDownMesh = pickResult.pickedMesh;
  22316. var actionManager = pickResult.pickedMesh.actionManager;
  22317. if (actionManager) {
  22318. if (actionManager.hasPickTriggers) {
  22319. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22320. switch (evt.button) {
  22321. case 0:
  22322. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22323. break;
  22324. case 1:
  22325. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22326. break;
  22327. case 2:
  22328. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22329. break;
  22330. }
  22331. }
  22332. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22333. window.setTimeout(function () {
  22334. 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);
  22335. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22336. if (_this._totalPointersPressed !== 0 &&
  22337. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22338. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22339. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22340. _this._startingPointerTime = 0;
  22341. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22342. }
  22343. }
  22344. }, Scene.LongPressDelay);
  22345. }
  22346. }
  22347. }
  22348. if (pickResult) {
  22349. if (this.onPointerDown) {
  22350. this.onPointerDown(evt, pickResult);
  22351. }
  22352. if (this.onPointerObservable.hasObservers()) {
  22353. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22354. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22355. this.onPointerObservable.notifyObservers(pi, type);
  22356. }
  22357. }
  22358. return this;
  22359. };
  22360. /**
  22361. * Use this method to simulate a pointer up on a mesh
  22362. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22363. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22364. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22365. */
  22366. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22367. var evt = new PointerEvent("pointerup", pointerEventInit);
  22368. var clickInfo = new ClickInfo();
  22369. clickInfo.singleClick = true;
  22370. clickInfo.ignore = true;
  22371. return this._processPointerUp(pickResult, evt, clickInfo);
  22372. };
  22373. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22374. if (pickResult && pickResult && pickResult.pickedMesh) {
  22375. this._pickedUpMesh = pickResult.pickedMesh;
  22376. if (this._pickedDownMesh === this._pickedUpMesh) {
  22377. if (this.onPointerPick) {
  22378. this.onPointerPick(evt, pickResult);
  22379. }
  22380. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22381. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22383. this.onPointerObservable.notifyObservers(pi, type);
  22384. }
  22385. }
  22386. if (pickResult.pickedMesh.actionManager) {
  22387. if (clickInfo.ignore) {
  22388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22389. }
  22390. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22391. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22392. }
  22393. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22395. }
  22396. }
  22397. }
  22398. if (this._pickedDownMesh &&
  22399. this._pickedDownMesh.actionManager &&
  22400. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22401. this._pickedDownMesh !== this._pickedUpMesh) {
  22402. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22403. }
  22404. if (this.onPointerUp) {
  22405. this.onPointerUp(evt, pickResult);
  22406. }
  22407. if (this.onPointerObservable.hasObservers()) {
  22408. if (!clickInfo.ignore) {
  22409. if (!clickInfo.hasSwiped) {
  22410. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22411. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22412. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22413. this.onPointerObservable.notifyObservers(pi, type);
  22414. }
  22415. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22416. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22417. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22418. this.onPointerObservable.notifyObservers(pi, type);
  22419. }
  22420. }
  22421. }
  22422. else {
  22423. var type = BABYLON.PointerEventTypes.POINTERUP;
  22424. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22425. this.onPointerObservable.notifyObservers(pi, type);
  22426. }
  22427. }
  22428. return this;
  22429. };
  22430. /**
  22431. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22432. * @param attachUp defines if you want to attach events to pointerup
  22433. * @param attachDown defines if you want to attach events to pointerdown
  22434. * @param attachMove defines if you want to attach events to pointermove
  22435. */
  22436. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22437. var _this = this;
  22438. if (attachUp === void 0) { attachUp = true; }
  22439. if (attachDown === void 0) { attachDown = true; }
  22440. if (attachMove === void 0) { attachMove = true; }
  22441. this._initActionManager = function (act, clickInfo) {
  22442. if (!_this._meshPickProceed) {
  22443. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22444. _this._currentPickResult = pickResult;
  22445. if (pickResult) {
  22446. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22447. }
  22448. _this._meshPickProceed = true;
  22449. }
  22450. return act;
  22451. };
  22452. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22453. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22454. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22455. btn !== _this._previousButtonPressed) {
  22456. _this._doubleClickOccured = false;
  22457. clickInfo.singleClick = true;
  22458. clickInfo.ignore = false;
  22459. cb(clickInfo, _this._currentPickResult);
  22460. }
  22461. };
  22462. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22463. var clickInfo = new ClickInfo();
  22464. _this._currentPickResult = null;
  22465. var act = null;
  22466. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22467. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22468. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22469. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22470. act = _this._initActionManager(act, clickInfo);
  22471. if (act)
  22472. checkPicking = act.hasPickTriggers;
  22473. }
  22474. if (checkPicking) {
  22475. var btn = evt.button;
  22476. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22477. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22478. if (!clickInfo.hasSwiped) {
  22479. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22480. if (!checkSingleClickImmediately) {
  22481. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22482. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22483. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22484. act = _this._initActionManager(act, clickInfo);
  22485. if (act)
  22486. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22487. }
  22488. }
  22489. if (checkSingleClickImmediately) {
  22490. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22491. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22492. btn !== _this._previousButtonPressed) {
  22493. clickInfo.singleClick = true;
  22494. cb(clickInfo, _this._currentPickResult);
  22495. }
  22496. }
  22497. else {
  22498. // wait that no double click has been raised during the double click delay
  22499. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22500. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22501. }
  22502. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22503. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22504. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22505. act = _this._initActionManager(act, clickInfo);
  22506. if (act)
  22507. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22508. }
  22509. if (checkDoubleClick) {
  22510. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22511. if (btn === _this._previousButtonPressed &&
  22512. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22513. !_this._doubleClickOccured) {
  22514. // pointer has not moved for 2 clicks, it's a double click
  22515. if (!clickInfo.hasSwiped &&
  22516. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22517. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22518. _this._previousStartingPointerTime = 0;
  22519. _this._doubleClickOccured = true;
  22520. clickInfo.doubleClick = true;
  22521. clickInfo.ignore = false;
  22522. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22523. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22524. }
  22525. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22526. cb(clickInfo, _this._currentPickResult);
  22527. }
  22528. else {
  22529. _this._doubleClickOccured = false;
  22530. _this._previousStartingPointerTime = _this._startingPointerTime;
  22531. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22532. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22533. _this._previousButtonPressed = btn;
  22534. if (Scene.ExclusiveDoubleClickMode) {
  22535. if (_this._previousDelayedSimpleClickTimeout) {
  22536. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22537. }
  22538. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22539. cb(clickInfo, _this._previousPickResult);
  22540. }
  22541. else {
  22542. cb(clickInfo, _this._currentPickResult);
  22543. }
  22544. }
  22545. }
  22546. else {
  22547. _this._doubleClickOccured = false;
  22548. _this._previousStartingPointerTime = _this._startingPointerTime;
  22549. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22550. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22551. _this._previousButtonPressed = btn;
  22552. }
  22553. }
  22554. }
  22555. }
  22556. clickInfo.ignore = true;
  22557. cb(clickInfo, _this._currentPickResult);
  22558. };
  22559. this._spritePredicate = function (sprite) {
  22560. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22561. };
  22562. this._onPointerMove = function (evt) {
  22563. _this._updatePointerPosition(evt);
  22564. // PreObservable support
  22565. if (_this.onPrePointerObservable.hasObservers()) {
  22566. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22567. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22568. _this.onPrePointerObservable.notifyObservers(pi, type);
  22569. if (pi.skipOnPointerObservable) {
  22570. return;
  22571. }
  22572. }
  22573. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22574. return;
  22575. }
  22576. if (!_this.pointerMovePredicate) {
  22577. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22578. }
  22579. // Meshes
  22580. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22581. _this._processPointerMove(pickResult, evt);
  22582. };
  22583. this._onPointerDown = function (evt) {
  22584. _this._totalPointersPressed++;
  22585. _this._pickedDownMesh = null;
  22586. _this._meshPickProceed = false;
  22587. _this._updatePointerPosition(evt);
  22588. if (_this.preventDefaultOnPointerDown && canvas) {
  22589. evt.preventDefault();
  22590. canvas.focus();
  22591. }
  22592. // PreObservable support
  22593. if (_this.onPrePointerObservable.hasObservers()) {
  22594. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  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. _this._startingPointerPosition.x = _this._pointerX;
  22605. _this._startingPointerPosition.y = _this._pointerY;
  22606. _this._startingPointerTime = new Date().getTime();
  22607. if (!_this.pointerDownPredicate) {
  22608. _this.pointerDownPredicate = function (mesh) {
  22609. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22610. };
  22611. }
  22612. // Meshes
  22613. _this._pickedDownMesh = null;
  22614. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22615. _this._processPointerDown(pickResult, evt);
  22616. // Sprites
  22617. _this._pickedDownSprite = null;
  22618. if (_this.spriteManagers.length > 0) {
  22619. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22620. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22621. if (pickResult.pickedSprite.actionManager) {
  22622. _this._pickedDownSprite = pickResult.pickedSprite;
  22623. switch (evt.button) {
  22624. case 0:
  22625. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22626. break;
  22627. case 1:
  22628. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22629. break;
  22630. case 2:
  22631. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22632. break;
  22633. }
  22634. if (pickResult.pickedSprite.actionManager) {
  22635. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22636. }
  22637. }
  22638. }
  22639. }
  22640. };
  22641. this._onPointerUp = function (evt) {
  22642. if (_this._totalPointersPressed === 0) {
  22643. return; // So we need to test it the pointer down was pressed before.
  22644. }
  22645. _this._totalPointersPressed--;
  22646. _this._pickedUpMesh = null;
  22647. _this._meshPickProceed = false;
  22648. _this._updatePointerPosition(evt);
  22649. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22650. // PreObservable support
  22651. if (_this.onPrePointerObservable.hasObservers()) {
  22652. if (!clickInfo.ignore) {
  22653. if (!clickInfo.hasSwiped) {
  22654. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22655. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22656. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22657. _this.onPrePointerObservable.notifyObservers(pi, type);
  22658. if (pi.skipOnPointerObservable) {
  22659. return;
  22660. }
  22661. }
  22662. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22663. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22664. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22665. _this.onPrePointerObservable.notifyObservers(pi, type);
  22666. if (pi.skipOnPointerObservable) {
  22667. return;
  22668. }
  22669. }
  22670. }
  22671. }
  22672. else {
  22673. var type = BABYLON.PointerEventTypes.POINTERUP;
  22674. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22675. _this.onPrePointerObservable.notifyObservers(pi, type);
  22676. if (pi.skipOnPointerObservable) {
  22677. return;
  22678. }
  22679. }
  22680. }
  22681. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22682. return;
  22683. }
  22684. if (!_this.pointerUpPredicate) {
  22685. _this.pointerUpPredicate = function (mesh) {
  22686. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22687. };
  22688. }
  22689. // Meshes
  22690. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22691. _this._initActionManager(null, clickInfo);
  22692. }
  22693. if (!pickResult) {
  22694. pickResult = _this._currentPickResult;
  22695. }
  22696. _this._processPointerUp(pickResult, evt, clickInfo);
  22697. // Sprites
  22698. if (_this.spriteManagers.length > 0) {
  22699. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22700. if (spritePickResult) {
  22701. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22702. if (spritePickResult.pickedSprite.actionManager) {
  22703. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22704. if (spritePickResult.pickedSprite.actionManager) {
  22705. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22706. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22707. }
  22708. }
  22709. }
  22710. }
  22711. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22712. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22713. }
  22714. }
  22715. }
  22716. _this._previousPickResult = _this._currentPickResult;
  22717. });
  22718. };
  22719. this._onKeyDown = function (evt) {
  22720. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22721. if (_this.onPreKeyboardObservable.hasObservers()) {
  22722. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22723. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22724. if (pi.skipOnPointerObservable) {
  22725. return;
  22726. }
  22727. }
  22728. if (_this.onKeyboardObservable.hasObservers()) {
  22729. var pi = new BABYLON.KeyboardInfo(type, evt);
  22730. _this.onKeyboardObservable.notifyObservers(pi, type);
  22731. }
  22732. if (_this.actionManager) {
  22733. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22734. }
  22735. };
  22736. this._onKeyUp = function (evt) {
  22737. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22738. if (_this.onPreKeyboardObservable.hasObservers()) {
  22739. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22740. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22741. if (pi.skipOnPointerObservable) {
  22742. return;
  22743. }
  22744. }
  22745. if (_this.onKeyboardObservable.hasObservers()) {
  22746. var pi = new BABYLON.KeyboardInfo(type, evt);
  22747. _this.onKeyboardObservable.notifyObservers(pi, type);
  22748. }
  22749. if (_this.actionManager) {
  22750. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22751. }
  22752. };
  22753. var engine = this.getEngine();
  22754. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22755. if (!canvas) {
  22756. return;
  22757. }
  22758. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22759. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22760. });
  22761. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22762. if (!canvas) {
  22763. return;
  22764. }
  22765. canvas.removeEventListener("keydown", _this._onKeyDown);
  22766. canvas.removeEventListener("keyup", _this._onKeyUp);
  22767. });
  22768. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22769. var canvas = this._engine.getRenderingCanvas();
  22770. if (!canvas) {
  22771. return;
  22772. }
  22773. if (attachMove) {
  22774. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22775. // Wheel
  22776. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22777. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22778. }
  22779. if (attachDown) {
  22780. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22781. }
  22782. if (attachUp) {
  22783. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22784. }
  22785. canvas.tabIndex = 1;
  22786. };
  22787. Scene.prototype.detachControl = function () {
  22788. var engine = this.getEngine();
  22789. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22790. var canvas = engine.getRenderingCanvas();
  22791. if (!canvas) {
  22792. return;
  22793. }
  22794. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22795. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22796. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22797. if (this._onCanvasBlurObserver) {
  22798. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22799. }
  22800. if (this._onCanvasFocusObserver) {
  22801. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22802. }
  22803. // Wheel
  22804. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22805. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22806. // Keyboard
  22807. canvas.removeEventListener("keydown", this._onKeyDown);
  22808. canvas.removeEventListener("keyup", this._onKeyUp);
  22809. // Observables
  22810. this.onKeyboardObservable.clear();
  22811. this.onPreKeyboardObservable.clear();
  22812. this.onPointerObservable.clear();
  22813. this.onPrePointerObservable.clear();
  22814. };
  22815. /**
  22816. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22817. * Delay loaded resources are not taking in account
  22818. * @return true if all required resources are ready
  22819. */
  22820. Scene.prototype.isReady = function () {
  22821. if (this._isDisposed) {
  22822. return false;
  22823. }
  22824. if (this._pendingData.length > 0) {
  22825. return false;
  22826. }
  22827. var index;
  22828. var engine = this.getEngine();
  22829. // Geometries
  22830. for (index = 0; index < this._geometries.length; index++) {
  22831. var geometry = this._geometries[index];
  22832. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22833. return false;
  22834. }
  22835. }
  22836. // Meshes
  22837. for (index = 0; index < this.meshes.length; index++) {
  22838. var mesh = this.meshes[index];
  22839. if (!mesh.isEnabled()) {
  22840. continue;
  22841. }
  22842. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22843. continue;
  22844. }
  22845. if (!mesh.isReady(true)) {
  22846. return false;
  22847. }
  22848. // Effect layers
  22849. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22850. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22851. var layer = _a[_i];
  22852. if (!layer.hasMesh(mesh)) {
  22853. continue;
  22854. }
  22855. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22856. var subMesh = _c[_b];
  22857. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22858. return false;
  22859. }
  22860. }
  22861. }
  22862. }
  22863. return true;
  22864. };
  22865. Scene.prototype.resetCachedMaterial = function () {
  22866. this._cachedMaterial = null;
  22867. this._cachedEffect = null;
  22868. this._cachedVisibility = null;
  22869. };
  22870. Scene.prototype.registerBeforeRender = function (func) {
  22871. this.onBeforeRenderObservable.add(func);
  22872. };
  22873. Scene.prototype.unregisterBeforeRender = function (func) {
  22874. this.onBeforeRenderObservable.removeCallback(func);
  22875. };
  22876. Scene.prototype.registerAfterRender = function (func) {
  22877. this.onAfterRenderObservable.add(func);
  22878. };
  22879. Scene.prototype.unregisterAfterRender = function (func) {
  22880. this.onAfterRenderObservable.removeCallback(func);
  22881. };
  22882. Scene.prototype._executeOnceBeforeRender = function (func) {
  22883. var _this = this;
  22884. var execFunc = function () {
  22885. func();
  22886. setTimeout(function () {
  22887. _this.unregisterBeforeRender(execFunc);
  22888. });
  22889. };
  22890. this.registerBeforeRender(execFunc);
  22891. };
  22892. /**
  22893. * The provided function will run before render once and will be disposed afterwards.
  22894. * A timeout delay can be provided so that the function will be executed in N ms.
  22895. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22896. * @param func The function to be executed.
  22897. * @param timeout optional delay in ms
  22898. */
  22899. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22900. var _this = this;
  22901. if (timeout !== undefined) {
  22902. setTimeout(function () {
  22903. _this._executeOnceBeforeRender(func);
  22904. }, timeout);
  22905. }
  22906. else {
  22907. this._executeOnceBeforeRender(func);
  22908. }
  22909. };
  22910. Scene.prototype._addPendingData = function (data) {
  22911. this._pendingData.push(data);
  22912. };
  22913. Scene.prototype._removePendingData = function (data) {
  22914. var wasLoading = this.isLoading;
  22915. var index = this._pendingData.indexOf(data);
  22916. if (index !== -1) {
  22917. this._pendingData.splice(index, 1);
  22918. }
  22919. if (wasLoading && !this.isLoading) {
  22920. this.onDataLoadedObservable.notifyObservers(this);
  22921. }
  22922. };
  22923. Scene.prototype.getWaitingItemsCount = function () {
  22924. return this._pendingData.length;
  22925. };
  22926. Object.defineProperty(Scene.prototype, "isLoading", {
  22927. get: function () {
  22928. return this._pendingData.length > 0;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. /**
  22934. * Registers a function to be executed when the scene is ready.
  22935. * @param {Function} func - the function to be executed.
  22936. */
  22937. Scene.prototype.executeWhenReady = function (func) {
  22938. var _this = this;
  22939. this.onReadyObservable.add(func);
  22940. if (this._executeWhenReadyTimeoutId !== -1) {
  22941. return;
  22942. }
  22943. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22944. _this._checkIsReady();
  22945. }, 150);
  22946. };
  22947. /**
  22948. * Returns a promise that resolves when the scene is ready.
  22949. * @returns A promise that resolves when the scene is ready.
  22950. */
  22951. Scene.prototype.whenReadyAsync = function () {
  22952. var _this = this;
  22953. return new Promise(function (resolve) {
  22954. _this.executeWhenReady(function () {
  22955. resolve();
  22956. });
  22957. });
  22958. };
  22959. Scene.prototype._checkIsReady = function () {
  22960. var _this = this;
  22961. if (this.isReady()) {
  22962. this.onReadyObservable.notifyObservers(this);
  22963. this.onReadyObservable.clear();
  22964. this._executeWhenReadyTimeoutId = -1;
  22965. return;
  22966. }
  22967. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22968. _this._checkIsReady();
  22969. }, 150);
  22970. };
  22971. // Animations
  22972. /**
  22973. * Will start the animation sequence of a given target
  22974. * @param target - the target
  22975. * @param {number} from - from which frame should animation start
  22976. * @param {number} to - till which frame should animation run.
  22977. * @param {boolean} [loop] - should the animation loop
  22978. * @param {number} [speedRatio] - the speed in which to run the animation
  22979. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22980. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22981. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22982. * See BABYLON.Animatable
  22983. */
  22984. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22985. if (speedRatio === void 0) { speedRatio = 1.0; }
  22986. if (from > to && speedRatio > 0) {
  22987. speedRatio *= -1;
  22988. }
  22989. this.stopAnimation(target);
  22990. if (!animatable) {
  22991. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22992. }
  22993. // Local animations
  22994. if (target.animations) {
  22995. animatable.appendAnimations(target, target.animations);
  22996. }
  22997. // Children animations
  22998. if (target.getAnimatables) {
  22999. var animatables = target.getAnimatables();
  23000. for (var index = 0; index < animatables.length; index++) {
  23001. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23002. }
  23003. }
  23004. animatable.reset();
  23005. return animatable;
  23006. };
  23007. /**
  23008. * Begin a new animation on a given node
  23009. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23010. * @param {BABYLON.Animation[]} defines the list of animations to start
  23011. * @param {number} from defines the initial value
  23012. * @param {number} to defines the final value
  23013. * @param {boolean} loop defines if you want animation to loop (off by default)
  23014. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23015. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23016. * @returns the list of created animatables
  23017. */
  23018. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23019. if (speedRatio === undefined) {
  23020. speedRatio = 1.0;
  23021. }
  23022. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23023. return animatable;
  23024. };
  23025. /**
  23026. * Begin a new animation on a given node and its hierarchy
  23027. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23028. * @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.
  23029. * @param {BABYLON.Animation[]} defines the list of animations to start
  23030. * @param {number} from defines the initial value
  23031. * @param {number} to defines the final value
  23032. * @param {boolean} loop defines if you want animation to loop (off by default)
  23033. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23034. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23035. * @returns the list of animatables created for all nodes
  23036. */
  23037. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23038. var children = target.getDescendants(directDescendantsOnly);
  23039. var result = [];
  23040. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23041. var child = children_1[_i];
  23042. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23043. }
  23044. return result;
  23045. };
  23046. Scene.prototype.getAnimatableByTarget = function (target) {
  23047. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23048. if (this._activeAnimatables[index].target === target) {
  23049. return this._activeAnimatables[index];
  23050. }
  23051. }
  23052. return null;
  23053. };
  23054. Object.defineProperty(Scene.prototype, "animatables", {
  23055. get: function () {
  23056. return this._activeAnimatables;
  23057. },
  23058. enumerable: true,
  23059. configurable: true
  23060. });
  23061. /**
  23062. * Will stop the animation of the given target
  23063. * @param target - the target
  23064. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23065. * @see beginAnimation
  23066. */
  23067. Scene.prototype.stopAnimation = function (target, animationName) {
  23068. var animatable = this.getAnimatableByTarget(target);
  23069. if (animatable) {
  23070. animatable.stop(animationName);
  23071. }
  23072. };
  23073. /**
  23074. * Stops and removes all animations that have been applied to the scene
  23075. */
  23076. Scene.prototype.stopAllAnimations = function () {
  23077. if (this._activeAnimatables) {
  23078. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23079. this._activeAnimatables[i].stop();
  23080. }
  23081. this._activeAnimatables = [];
  23082. }
  23083. };
  23084. Scene.prototype._animate = function () {
  23085. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23086. return;
  23087. }
  23088. // Getting time
  23089. var now = BABYLON.Tools.Now;
  23090. if (!this._animationTimeLast) {
  23091. if (this._pendingData.length > 0) {
  23092. return;
  23093. }
  23094. this._animationTimeLast = now;
  23095. }
  23096. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23097. this._animationTime += deltaTime;
  23098. this._animationTimeLast = now;
  23099. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23100. this._activeAnimatables[index]._animate(this._animationTime);
  23101. }
  23102. };
  23103. // Matrix
  23104. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23105. this._useAlternateCameraConfiguration = active;
  23106. };
  23107. Scene.prototype.getViewMatrix = function () {
  23108. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23109. };
  23110. Scene.prototype.getProjectionMatrix = function () {
  23111. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23112. };
  23113. Scene.prototype.getTransformMatrix = function () {
  23114. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23115. };
  23116. Scene.prototype.setTransformMatrix = function (view, projection) {
  23117. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23118. return;
  23119. }
  23120. this._viewUpdateFlag = view.updateFlag;
  23121. this._projectionUpdateFlag = projection.updateFlag;
  23122. this._viewMatrix = view;
  23123. this._projectionMatrix = projection;
  23124. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23125. // Update frustum
  23126. if (!this._frustumPlanes) {
  23127. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23128. }
  23129. else {
  23130. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23131. }
  23132. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23133. var otherCamera = this.activeCamera._alternateCamera;
  23134. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23135. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23136. }
  23137. if (this._sceneUbo.useUbo) {
  23138. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23139. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23140. this._sceneUbo.update();
  23141. }
  23142. };
  23143. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23144. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23145. return;
  23146. }
  23147. this._alternateViewUpdateFlag = view.updateFlag;
  23148. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23149. this._alternateViewMatrix = view;
  23150. this._alternateProjectionMatrix = projection;
  23151. if (!this._alternateTransformMatrix) {
  23152. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23153. }
  23154. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23155. if (!this._alternateSceneUbo) {
  23156. this._createAlternateUbo();
  23157. }
  23158. if (this._alternateSceneUbo.useUbo) {
  23159. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23160. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23161. this._alternateSceneUbo.update();
  23162. }
  23163. };
  23164. Scene.prototype.getSceneUniformBuffer = function () {
  23165. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23166. };
  23167. // Methods
  23168. Scene.prototype.getUniqueId = function () {
  23169. var result = Scene._uniqueIdCounter;
  23170. Scene._uniqueIdCounter++;
  23171. return result;
  23172. };
  23173. Scene.prototype.addMesh = function (newMesh) {
  23174. this.meshes.push(newMesh);
  23175. //notify the collision coordinator
  23176. if (this.collisionCoordinator) {
  23177. this.collisionCoordinator.onMeshAdded(newMesh);
  23178. }
  23179. newMesh._resyncLightSources();
  23180. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23181. };
  23182. Scene.prototype.removeMesh = function (toRemove) {
  23183. var index = this.meshes.indexOf(toRemove);
  23184. if (index !== -1) {
  23185. // Remove from the scene if mesh found
  23186. this.meshes.splice(index, 1);
  23187. }
  23188. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23189. return index;
  23190. };
  23191. Scene.prototype.addTransformNode = function (newTransformNode) {
  23192. this.transformNodes.push(newTransformNode);
  23193. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23194. };
  23195. Scene.prototype.removeTransformNode = function (toRemove) {
  23196. var index = this.transformNodes.indexOf(toRemove);
  23197. if (index !== -1) {
  23198. // Remove from the scene if found
  23199. this.transformNodes.splice(index, 1);
  23200. }
  23201. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23202. return index;
  23203. };
  23204. Scene.prototype.removeSkeleton = function (toRemove) {
  23205. var index = this.skeletons.indexOf(toRemove);
  23206. if (index !== -1) {
  23207. // Remove from the scene if found
  23208. this.skeletons.splice(index, 1);
  23209. }
  23210. return index;
  23211. };
  23212. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23213. var index = this.morphTargetManagers.indexOf(toRemove);
  23214. if (index !== -1) {
  23215. // Remove from the scene if found
  23216. this.morphTargetManagers.splice(index, 1);
  23217. }
  23218. return index;
  23219. };
  23220. Scene.prototype.removeLight = function (toRemove) {
  23221. var index = this.lights.indexOf(toRemove);
  23222. if (index !== -1) {
  23223. // Remove from meshes
  23224. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23225. var mesh = _a[_i];
  23226. mesh._removeLightSource(toRemove);
  23227. }
  23228. // Remove from the scene if mesh found
  23229. this.lights.splice(index, 1);
  23230. this.sortLightsByPriority();
  23231. }
  23232. this.onLightRemovedObservable.notifyObservers(toRemove);
  23233. return index;
  23234. };
  23235. Scene.prototype.removeCamera = function (toRemove) {
  23236. var index = this.cameras.indexOf(toRemove);
  23237. if (index !== -1) {
  23238. // Remove from the scene if mesh found
  23239. this.cameras.splice(index, 1);
  23240. }
  23241. // Remove from activeCameras
  23242. var index2 = this.activeCameras.indexOf(toRemove);
  23243. if (index2 !== -1) {
  23244. // Remove from the scene if mesh found
  23245. this.activeCameras.splice(index2, 1);
  23246. }
  23247. // Reset the activeCamera
  23248. if (this.activeCamera === toRemove) {
  23249. if (this.cameras.length > 0) {
  23250. this.activeCamera = this.cameras[0];
  23251. }
  23252. else {
  23253. this.activeCamera = null;
  23254. }
  23255. }
  23256. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23257. return index;
  23258. };
  23259. Scene.prototype.removeParticleSystem = function (toRemove) {
  23260. var index = this.particleSystems.indexOf(toRemove);
  23261. if (index !== -1) {
  23262. this.particleSystems.splice(index, 1);
  23263. }
  23264. return index;
  23265. };
  23266. ;
  23267. Scene.prototype.removeAnimation = function (toRemove) {
  23268. var index = this.animations.indexOf(toRemove);
  23269. if (index !== -1) {
  23270. this.animations.splice(index, 1);
  23271. }
  23272. return index;
  23273. };
  23274. ;
  23275. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23276. var index = this.multiMaterials.indexOf(toRemove);
  23277. if (index !== -1) {
  23278. this.multiMaterials.splice(index, 1);
  23279. }
  23280. return index;
  23281. };
  23282. ;
  23283. Scene.prototype.removeMaterial = function (toRemove) {
  23284. var index = this.materials.indexOf(toRemove);
  23285. if (index !== -1) {
  23286. this.materials.splice(index, 1);
  23287. }
  23288. return index;
  23289. };
  23290. ;
  23291. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23292. var index = this.lensFlareSystems.indexOf(toRemove);
  23293. if (index !== -1) {
  23294. this.lensFlareSystems.splice(index, 1);
  23295. }
  23296. return index;
  23297. };
  23298. ;
  23299. Scene.prototype.removeActionManager = function (toRemove) {
  23300. var index = this._actionManagers.indexOf(toRemove);
  23301. if (index !== -1) {
  23302. this._actionManagers.splice(index, 1);
  23303. }
  23304. return index;
  23305. };
  23306. ;
  23307. Scene.prototype.addLight = function (newLight) {
  23308. this.lights.push(newLight);
  23309. this.sortLightsByPriority();
  23310. // Add light to all meshes (To support if the light is removed and then readded)
  23311. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23312. var mesh = _a[_i];
  23313. if (mesh._lightSources.indexOf(newLight) === -1) {
  23314. mesh._lightSources.push(newLight);
  23315. mesh._resyncLightSources();
  23316. }
  23317. }
  23318. this.onNewLightAddedObservable.notifyObservers(newLight);
  23319. };
  23320. Scene.prototype.sortLightsByPriority = function () {
  23321. if (this.requireLightSorting) {
  23322. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23323. }
  23324. };
  23325. Scene.prototype.addCamera = function (newCamera) {
  23326. this.cameras.push(newCamera);
  23327. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23328. };
  23329. Scene.prototype.addSkeleton = function (newSkeleton) {
  23330. this.skeletons.push(newSkeleton);
  23331. };
  23332. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23333. this.particleSystems.push(newParticleSystem);
  23334. };
  23335. Scene.prototype.addAnimation = function (newAnimation) {
  23336. this.animations.push(newAnimation);
  23337. };
  23338. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23339. this.multiMaterials.push(newMultiMaterial);
  23340. };
  23341. Scene.prototype.addMaterial = function (newMaterial) {
  23342. this.materials.push(newMaterial);
  23343. };
  23344. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23345. this.morphTargetManagers.push(newMorphTargetManager);
  23346. };
  23347. Scene.prototype.addGeometry = function (newGeometrie) {
  23348. this._geometries.push(newGeometrie);
  23349. };
  23350. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23351. this.lensFlareSystems.push(newLensFlareSystem);
  23352. };
  23353. Scene.prototype.addActionManager = function (newActionManager) {
  23354. this._actionManagers.push(newActionManager);
  23355. };
  23356. /**
  23357. * Switch active camera
  23358. * @param {Camera} newCamera - new active camera
  23359. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23360. */
  23361. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23362. if (attachControl === void 0) { attachControl = true; }
  23363. var canvas = this._engine.getRenderingCanvas();
  23364. if (!canvas) {
  23365. return;
  23366. }
  23367. if (this.activeCamera) {
  23368. this.activeCamera.detachControl(canvas);
  23369. }
  23370. this.activeCamera = newCamera;
  23371. if (attachControl) {
  23372. newCamera.attachControl(canvas);
  23373. }
  23374. };
  23375. /**
  23376. * sets the active camera of the scene using its ID
  23377. * @param {string} id - the camera's ID
  23378. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23379. * @see activeCamera
  23380. */
  23381. Scene.prototype.setActiveCameraByID = function (id) {
  23382. var camera = this.getCameraByID(id);
  23383. if (camera) {
  23384. this.activeCamera = camera;
  23385. return camera;
  23386. }
  23387. return null;
  23388. };
  23389. /**
  23390. * sets the active camera of the scene using its name
  23391. * @param {string} name - the camera's name
  23392. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23393. * @see activeCamera
  23394. */
  23395. Scene.prototype.setActiveCameraByName = function (name) {
  23396. var camera = this.getCameraByName(name);
  23397. if (camera) {
  23398. this.activeCamera = camera;
  23399. return camera;
  23400. }
  23401. return null;
  23402. };
  23403. /**
  23404. * get an animation group using its name
  23405. * @param {string} the material's name
  23406. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23407. */
  23408. Scene.prototype.getAnimationGroupByName = function (name) {
  23409. for (var index = 0; index < this.animationGroups.length; index++) {
  23410. if (this.animationGroups[index].name === name) {
  23411. return this.animationGroups[index];
  23412. }
  23413. }
  23414. return null;
  23415. };
  23416. /**
  23417. * get a material using its id
  23418. * @param {string} the material's ID
  23419. * @return {BABYLON.Material|null} the material or null if none found.
  23420. */
  23421. Scene.prototype.getMaterialByID = function (id) {
  23422. for (var index = 0; index < this.materials.length; index++) {
  23423. if (this.materials[index].id === id) {
  23424. return this.materials[index];
  23425. }
  23426. }
  23427. return null;
  23428. };
  23429. /**
  23430. * get a material using its name
  23431. * @param {string} the material's name
  23432. * @return {BABYLON.Material|null} the material or null if none found.
  23433. */
  23434. Scene.prototype.getMaterialByName = function (name) {
  23435. for (var index = 0; index < this.materials.length; index++) {
  23436. if (this.materials[index].name === name) {
  23437. return this.materials[index];
  23438. }
  23439. }
  23440. return null;
  23441. };
  23442. Scene.prototype.getLensFlareSystemByName = function (name) {
  23443. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23444. if (this.lensFlareSystems[index].name === name) {
  23445. return this.lensFlareSystems[index];
  23446. }
  23447. }
  23448. return null;
  23449. };
  23450. Scene.prototype.getLensFlareSystemByID = function (id) {
  23451. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23452. if (this.lensFlareSystems[index].id === id) {
  23453. return this.lensFlareSystems[index];
  23454. }
  23455. }
  23456. return null;
  23457. };
  23458. Scene.prototype.getCameraByID = function (id) {
  23459. for (var index = 0; index < this.cameras.length; index++) {
  23460. if (this.cameras[index].id === id) {
  23461. return this.cameras[index];
  23462. }
  23463. }
  23464. return null;
  23465. };
  23466. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23467. for (var index = 0; index < this.cameras.length; index++) {
  23468. if (this.cameras[index].uniqueId === uniqueId) {
  23469. return this.cameras[index];
  23470. }
  23471. }
  23472. return null;
  23473. };
  23474. /**
  23475. * get a camera using its name
  23476. * @param {string} the camera's name
  23477. * @return {BABYLON.Camera|null} the camera or null if none found.
  23478. */
  23479. Scene.prototype.getCameraByName = function (name) {
  23480. for (var index = 0; index < this.cameras.length; index++) {
  23481. if (this.cameras[index].name === name) {
  23482. return this.cameras[index];
  23483. }
  23484. }
  23485. return null;
  23486. };
  23487. /**
  23488. * get a bone using its id
  23489. * @param {string} the bone's id
  23490. * @return {BABYLON.Bone|null} the bone or null if not found
  23491. */
  23492. Scene.prototype.getBoneByID = function (id) {
  23493. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23494. var skeleton = this.skeletons[skeletonIndex];
  23495. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23496. if (skeleton.bones[boneIndex].id === id) {
  23497. return skeleton.bones[boneIndex];
  23498. }
  23499. }
  23500. }
  23501. return null;
  23502. };
  23503. /**
  23504. * get a bone using its id
  23505. * @param {string} the bone's name
  23506. * @return {BABYLON.Bone|null} the bone or null if not found
  23507. */
  23508. Scene.prototype.getBoneByName = function (name) {
  23509. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23510. var skeleton = this.skeletons[skeletonIndex];
  23511. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23512. if (skeleton.bones[boneIndex].name === name) {
  23513. return skeleton.bones[boneIndex];
  23514. }
  23515. }
  23516. }
  23517. return null;
  23518. };
  23519. /**
  23520. * get a light node using its name
  23521. * @param {string} the light's name
  23522. * @return {BABYLON.Light|null} the light or null if none found.
  23523. */
  23524. Scene.prototype.getLightByName = function (name) {
  23525. for (var index = 0; index < this.lights.length; index++) {
  23526. if (this.lights[index].name === name) {
  23527. return this.lights[index];
  23528. }
  23529. }
  23530. return null;
  23531. };
  23532. /**
  23533. * get a light node using its ID
  23534. * @param {string} the light's id
  23535. * @return {BABYLON.Light|null} the light or null if none found.
  23536. */
  23537. Scene.prototype.getLightByID = function (id) {
  23538. for (var index = 0; index < this.lights.length; index++) {
  23539. if (this.lights[index].id === id) {
  23540. return this.lights[index];
  23541. }
  23542. }
  23543. return null;
  23544. };
  23545. /**
  23546. * get a light node using its scene-generated unique ID
  23547. * @param {number} the light's unique id
  23548. * @return {BABYLON.Light|null} the light or null if none found.
  23549. */
  23550. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23551. for (var index = 0; index < this.lights.length; index++) {
  23552. if (this.lights[index].uniqueId === uniqueId) {
  23553. return this.lights[index];
  23554. }
  23555. }
  23556. return null;
  23557. };
  23558. /**
  23559. * get a particle system by id
  23560. * @param id {number} the particle system id
  23561. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23562. */
  23563. Scene.prototype.getParticleSystemByID = function (id) {
  23564. for (var index = 0; index < this.particleSystems.length; index++) {
  23565. if (this.particleSystems[index].id === id) {
  23566. return this.particleSystems[index];
  23567. }
  23568. }
  23569. return null;
  23570. };
  23571. /**
  23572. * get a geometry using its ID
  23573. * @param {string} the geometry's id
  23574. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23575. */
  23576. Scene.prototype.getGeometryByID = function (id) {
  23577. for (var index = 0; index < this._geometries.length; index++) {
  23578. if (this._geometries[index].id === id) {
  23579. return this._geometries[index];
  23580. }
  23581. }
  23582. return null;
  23583. };
  23584. /**
  23585. * add a new geometry to this scene.
  23586. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23587. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23588. * @return {boolean} was the geometry added or not
  23589. */
  23590. Scene.prototype.pushGeometry = function (geometry, force) {
  23591. if (!force && this.getGeometryByID(geometry.id)) {
  23592. return false;
  23593. }
  23594. this._geometries.push(geometry);
  23595. //notify the collision coordinator
  23596. if (this.collisionCoordinator) {
  23597. this.collisionCoordinator.onGeometryAdded(geometry);
  23598. }
  23599. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23600. return true;
  23601. };
  23602. /**
  23603. * Removes an existing geometry
  23604. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23605. * @return {boolean} was the geometry removed or not
  23606. */
  23607. Scene.prototype.removeGeometry = function (geometry) {
  23608. var index = this._geometries.indexOf(geometry);
  23609. if (index > -1) {
  23610. this._geometries.splice(index, 1);
  23611. //notify the collision coordinator
  23612. if (this.collisionCoordinator) {
  23613. this.collisionCoordinator.onGeometryDeleted(geometry);
  23614. }
  23615. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23616. return true;
  23617. }
  23618. return false;
  23619. };
  23620. Scene.prototype.getGeometries = function () {
  23621. return this._geometries;
  23622. };
  23623. /**
  23624. * Get the first added mesh found of a given ID
  23625. * @param {string} id - the id to search for
  23626. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23627. */
  23628. Scene.prototype.getMeshByID = function (id) {
  23629. for (var index = 0; index < this.meshes.length; index++) {
  23630. if (this.meshes[index].id === id) {
  23631. return this.meshes[index];
  23632. }
  23633. }
  23634. return null;
  23635. };
  23636. Scene.prototype.getMeshesByID = function (id) {
  23637. return this.meshes.filter(function (m) {
  23638. return m.id === id;
  23639. });
  23640. };
  23641. /**
  23642. * Get the first added transform node found of a given ID
  23643. * @param {string} id - the id to search for
  23644. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23645. */
  23646. Scene.prototype.getTransformNodeByID = function (id) {
  23647. for (var index = 0; index < this.transformNodes.length; index++) {
  23648. if (this.transformNodes[index].id === id) {
  23649. return this.transformNodes[index];
  23650. }
  23651. }
  23652. return null;
  23653. };
  23654. Scene.prototype.getTransformNodesByID = function (id) {
  23655. return this.transformNodes.filter(function (m) {
  23656. return m.id === id;
  23657. });
  23658. };
  23659. /**
  23660. * Get a mesh with its auto-generated unique id
  23661. * @param {number} uniqueId - the unique id to search for
  23662. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23663. */
  23664. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23665. for (var index = 0; index < this.meshes.length; index++) {
  23666. if (this.meshes[index].uniqueId === uniqueId) {
  23667. return this.meshes[index];
  23668. }
  23669. }
  23670. return null;
  23671. };
  23672. /**
  23673. * Get a the last added mesh found of a given ID
  23674. * @param {string} id - the id to search for
  23675. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23676. */
  23677. Scene.prototype.getLastMeshByID = function (id) {
  23678. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23679. if (this.meshes[index].id === id) {
  23680. return this.meshes[index];
  23681. }
  23682. }
  23683. return null;
  23684. };
  23685. /**
  23686. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23687. * @param {string} id - the id to search for
  23688. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23689. */
  23690. Scene.prototype.getLastEntryByID = function (id) {
  23691. var index;
  23692. for (index = this.meshes.length - 1; index >= 0; index--) {
  23693. if (this.meshes[index].id === id) {
  23694. return this.meshes[index];
  23695. }
  23696. }
  23697. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23698. if (this.transformNodes[index].id === id) {
  23699. return this.transformNodes[index];
  23700. }
  23701. }
  23702. for (index = this.cameras.length - 1; index >= 0; index--) {
  23703. if (this.cameras[index].id === id) {
  23704. return this.cameras[index];
  23705. }
  23706. }
  23707. for (index = this.lights.length - 1; index >= 0; index--) {
  23708. if (this.lights[index].id === id) {
  23709. return this.lights[index];
  23710. }
  23711. }
  23712. return null;
  23713. };
  23714. Scene.prototype.getNodeByID = function (id) {
  23715. var mesh = this.getMeshByID(id);
  23716. if (mesh) {
  23717. return mesh;
  23718. }
  23719. var light = this.getLightByID(id);
  23720. if (light) {
  23721. return light;
  23722. }
  23723. var camera = this.getCameraByID(id);
  23724. if (camera) {
  23725. return camera;
  23726. }
  23727. var bone = this.getBoneByID(id);
  23728. return bone;
  23729. };
  23730. Scene.prototype.getNodeByName = function (name) {
  23731. var mesh = this.getMeshByName(name);
  23732. if (mesh) {
  23733. return mesh;
  23734. }
  23735. var light = this.getLightByName(name);
  23736. if (light) {
  23737. return light;
  23738. }
  23739. var camera = this.getCameraByName(name);
  23740. if (camera) {
  23741. return camera;
  23742. }
  23743. var bone = this.getBoneByName(name);
  23744. return bone;
  23745. };
  23746. Scene.prototype.getMeshByName = function (name) {
  23747. for (var index = 0; index < this.meshes.length; index++) {
  23748. if (this.meshes[index].name === name) {
  23749. return this.meshes[index];
  23750. }
  23751. }
  23752. return null;
  23753. };
  23754. Scene.prototype.getTransformNodeByName = function (name) {
  23755. for (var index = 0; index < this.transformNodes.length; index++) {
  23756. if (this.transformNodes[index].name === name) {
  23757. return this.transformNodes[index];
  23758. }
  23759. }
  23760. return null;
  23761. };
  23762. Scene.prototype.getSoundByName = function (name) {
  23763. var index;
  23764. if (BABYLON.AudioEngine) {
  23765. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23766. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23767. return this.mainSoundTrack.soundCollection[index];
  23768. }
  23769. }
  23770. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23771. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23772. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23773. return this.soundTracks[sdIndex].soundCollection[index];
  23774. }
  23775. }
  23776. }
  23777. }
  23778. return null;
  23779. };
  23780. Scene.prototype.getLastSkeletonByID = function (id) {
  23781. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23782. if (this.skeletons[index].id === id) {
  23783. return this.skeletons[index];
  23784. }
  23785. }
  23786. return null;
  23787. };
  23788. Scene.prototype.getSkeletonById = function (id) {
  23789. for (var index = 0; index < this.skeletons.length; index++) {
  23790. if (this.skeletons[index].id === id) {
  23791. return this.skeletons[index];
  23792. }
  23793. }
  23794. return null;
  23795. };
  23796. Scene.prototype.getSkeletonByName = function (name) {
  23797. for (var index = 0; index < this.skeletons.length; index++) {
  23798. if (this.skeletons[index].name === name) {
  23799. return this.skeletons[index];
  23800. }
  23801. }
  23802. return null;
  23803. };
  23804. Scene.prototype.getMorphTargetManagerById = function (id) {
  23805. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23806. if (this.morphTargetManagers[index].uniqueId === id) {
  23807. return this.morphTargetManagers[index];
  23808. }
  23809. }
  23810. return null;
  23811. };
  23812. Scene.prototype.isActiveMesh = function (mesh) {
  23813. return (this._activeMeshes.indexOf(mesh) !== -1);
  23814. };
  23815. /**
  23816. * Return a the first highlight layer of the scene with a given name.
  23817. * @param name The name of the highlight layer to look for.
  23818. * @return The highlight layer if found otherwise null.
  23819. */
  23820. Scene.prototype.getHighlightLayerByName = function (name) {
  23821. for (var index = 0; index < this.effectLayers.length; index++) {
  23822. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23823. return this.effectLayers[index];
  23824. }
  23825. }
  23826. return null;
  23827. };
  23828. /**
  23829. * Return a the first highlight layer of the scene with a given name.
  23830. * @param name The name of the highlight layer to look for.
  23831. * @return The highlight layer if found otherwise null.
  23832. */
  23833. Scene.prototype.getGlowLayerByName = function (name) {
  23834. for (var index = 0; index < this.effectLayers.length; index++) {
  23835. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23836. return this.effectLayers[index];
  23837. }
  23838. }
  23839. return null;
  23840. };
  23841. Object.defineProperty(Scene.prototype, "uid", {
  23842. /**
  23843. * Return a unique id as a string which can serve as an identifier for the scene
  23844. */
  23845. get: function () {
  23846. if (!this._uid) {
  23847. this._uid = BABYLON.Tools.RandomId();
  23848. }
  23849. return this._uid;
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. /**
  23855. * Add an externaly attached data from its key.
  23856. * This method call will fail and return false, if such key already exists.
  23857. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23858. * @param key the unique key that identifies the data
  23859. * @param data the data object to associate to the key for this Engine instance
  23860. * @return true if no such key were already present and the data was added successfully, false otherwise
  23861. */
  23862. Scene.prototype.addExternalData = function (key, data) {
  23863. if (!this._externalData) {
  23864. this._externalData = new BABYLON.StringDictionary();
  23865. }
  23866. return this._externalData.add(key, data);
  23867. };
  23868. /**
  23869. * Get an externaly attached data from its key
  23870. * @param key the unique key that identifies the data
  23871. * @return the associated data, if present (can be null), or undefined if not present
  23872. */
  23873. Scene.prototype.getExternalData = function (key) {
  23874. if (!this._externalData) {
  23875. return null;
  23876. }
  23877. return this._externalData.get(key);
  23878. };
  23879. /**
  23880. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23881. * @param key the unique key that identifies the data
  23882. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23883. * @return the associated data, can be null if the factory returned null.
  23884. */
  23885. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23886. if (!this._externalData) {
  23887. this._externalData = new BABYLON.StringDictionary();
  23888. }
  23889. return this._externalData.getOrAddWithFactory(key, factory);
  23890. };
  23891. /**
  23892. * Remove an externaly attached data from the Engine instance
  23893. * @param key the unique key that identifies the data
  23894. * @return true if the data was successfully removed, false if it doesn't exist
  23895. */
  23896. Scene.prototype.removeExternalData = function (key) {
  23897. return this._externalData.remove(key);
  23898. };
  23899. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23900. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23901. if (mesh.showSubMeshesBoundingBox) {
  23902. var boundingInfo = subMesh.getBoundingInfo();
  23903. if (boundingInfo !== null && boundingInfo !== undefined) {
  23904. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23905. }
  23906. }
  23907. var material = subMesh.getMaterial();
  23908. if (material !== null && material !== undefined) {
  23909. // Render targets
  23910. if (material.getRenderTargetTextures !== undefined) {
  23911. if (this._processedMaterials.indexOf(material) === -1) {
  23912. this._processedMaterials.push(material);
  23913. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23914. }
  23915. }
  23916. // Dispatch
  23917. this._activeIndices.addCount(subMesh.indexCount, false);
  23918. this._renderingManager.dispatch(subMesh, mesh, material);
  23919. }
  23920. }
  23921. };
  23922. Scene.prototype._isInIntermediateRendering = function () {
  23923. return this._intermediateRendering;
  23924. };
  23925. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23926. this._activeMeshCandidateProvider = provider;
  23927. };
  23928. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23929. return this._activeMeshCandidateProvider;
  23930. };
  23931. /**
  23932. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23933. */
  23934. Scene.prototype.freezeActiveMeshes = function () {
  23935. this._evaluateActiveMeshes();
  23936. this._activeMeshesFrozen = true;
  23937. return this;
  23938. };
  23939. /**
  23940. * Use this function to restart evaluating active meshes on every frame
  23941. */
  23942. Scene.prototype.unfreezeActiveMeshes = function () {
  23943. this._activeMeshesFrozen = false;
  23944. return this;
  23945. };
  23946. Scene.prototype._evaluateActiveMeshes = function () {
  23947. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23948. return;
  23949. }
  23950. if (!this.activeCamera) {
  23951. return;
  23952. }
  23953. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23954. this.activeCamera._activeMeshes.reset();
  23955. this._activeMeshes.reset();
  23956. this._renderingManager.reset();
  23957. this._processedMaterials.reset();
  23958. this._activeParticleSystems.reset();
  23959. this._activeSkeletons.reset();
  23960. this._softwareSkinnedMeshes.reset();
  23961. if (this._boundingBoxRenderer) {
  23962. this._boundingBoxRenderer.reset();
  23963. }
  23964. // Meshes
  23965. var meshes;
  23966. var len;
  23967. var checkIsEnabled = true;
  23968. // Determine mesh candidates
  23969. if (this._activeMeshCandidateProvider !== undefined) {
  23970. // Use _activeMeshCandidateProvider
  23971. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23972. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23973. if (meshes !== undefined) {
  23974. len = meshes.length;
  23975. }
  23976. else {
  23977. len = 0;
  23978. }
  23979. }
  23980. else if (this._selectionOctree !== undefined) {
  23981. // Octree
  23982. var selection = this._selectionOctree.select(this._frustumPlanes);
  23983. meshes = selection.data;
  23984. len = selection.length;
  23985. }
  23986. else {
  23987. // Full scene traversal
  23988. len = this.meshes.length;
  23989. meshes = this.meshes;
  23990. }
  23991. // Check each mesh
  23992. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23993. mesh = meshes[meshIndex];
  23994. if (mesh.isBlocked) {
  23995. continue;
  23996. }
  23997. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23998. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23999. continue;
  24000. }
  24001. mesh.computeWorldMatrix();
  24002. // Intersections
  24003. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24004. this._meshesForIntersections.pushNoDuplicate(mesh);
  24005. }
  24006. // Switch to current LOD
  24007. meshLOD = mesh.getLOD(this.activeCamera);
  24008. if (meshLOD === undefined || meshLOD === null) {
  24009. continue;
  24010. }
  24011. mesh._preActivate();
  24012. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24013. this._activeMeshes.push(mesh);
  24014. this.activeCamera._activeMeshes.push(mesh);
  24015. mesh._activate(this._renderId);
  24016. if (meshLOD !== mesh) {
  24017. meshLOD._activate(this._renderId);
  24018. }
  24019. this._activeMesh(mesh, meshLOD);
  24020. }
  24021. }
  24022. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24023. // Particle systems
  24024. if (this.particlesEnabled) {
  24025. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24026. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24027. var particleSystem = this.particleSystems[particleIndex];
  24028. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24029. continue;
  24030. }
  24031. var emitter = particleSystem.emitter;
  24032. if (!emitter.position || emitter.isEnabled()) {
  24033. this._activeParticleSystems.push(particleSystem);
  24034. particleSystem.animate();
  24035. this._renderingManager.dispatchParticles(particleSystem);
  24036. }
  24037. }
  24038. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24039. }
  24040. };
  24041. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24042. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24043. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24044. mesh.skeleton.prepare();
  24045. }
  24046. if (!mesh.computeBonesUsingShaders) {
  24047. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24048. }
  24049. }
  24050. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24051. var boundingInfo = sourceMesh.getBoundingInfo();
  24052. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24053. }
  24054. if (mesh !== undefined && mesh !== null
  24055. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24056. // Submeshes Octrees
  24057. var len;
  24058. var subMeshes;
  24059. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24060. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24061. len = intersections.length;
  24062. subMeshes = intersections.data;
  24063. }
  24064. else {
  24065. subMeshes = mesh.subMeshes;
  24066. len = subMeshes.length;
  24067. }
  24068. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24069. subMesh = subMeshes[subIndex];
  24070. this._evaluateSubMesh(subMesh, mesh);
  24071. }
  24072. }
  24073. };
  24074. Scene.prototype.updateTransformMatrix = function (force) {
  24075. if (!this.activeCamera) {
  24076. return;
  24077. }
  24078. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24079. };
  24080. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24081. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24082. };
  24083. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24084. if (camera && camera._skipRendering) {
  24085. return;
  24086. }
  24087. var engine = this._engine;
  24088. this.activeCamera = camera;
  24089. if (!this.activeCamera)
  24090. throw new Error("Active camera not set");
  24091. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24092. // Viewport
  24093. engine.setViewport(this.activeCamera.viewport);
  24094. // Camera
  24095. this.resetCachedMaterial();
  24096. this._renderId++;
  24097. this.updateTransformMatrix();
  24098. if (camera._alternateCamera) {
  24099. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24100. this._alternateRendering = true;
  24101. }
  24102. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24103. // Meshes
  24104. this._evaluateActiveMeshes();
  24105. // Software skinning
  24106. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24107. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24108. mesh.applySkeleton(mesh.skeleton);
  24109. }
  24110. // Render targets
  24111. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24112. var needsRestoreFrameBuffer = false;
  24113. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24114. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24115. }
  24116. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24117. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24118. }
  24119. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24120. this._intermediateRendering = true;
  24121. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24122. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24123. var renderTarget = this._renderTargets.data[renderIndex];
  24124. if (renderTarget._shouldRender()) {
  24125. this._renderId++;
  24126. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24127. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24128. }
  24129. }
  24130. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24131. this._intermediateRendering = false;
  24132. this._renderId++;
  24133. needsRestoreFrameBuffer = true; // Restore back buffer
  24134. }
  24135. // Render EffecttLayer Texture
  24136. var stencilState = this._engine.getStencilBuffer();
  24137. var renderEffects = false;
  24138. var needStencil = false;
  24139. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24140. this._intermediateRendering = true;
  24141. for (var i = 0; i < this.effectLayers.length; i++) {
  24142. var effectLayer = this.effectLayers[i];
  24143. if (effectLayer.shouldRender() &&
  24144. (!effectLayer.camera ||
  24145. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24146. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24147. renderEffects = true;
  24148. needStencil = needStencil || effectLayer.needStencil();
  24149. var renderTarget = effectLayer._mainTexture;
  24150. if (renderTarget._shouldRender()) {
  24151. this._renderId++;
  24152. renderTarget.render(false, false);
  24153. needsRestoreFrameBuffer = true;
  24154. }
  24155. }
  24156. }
  24157. this._intermediateRendering = false;
  24158. this._renderId++;
  24159. }
  24160. if (needsRestoreFrameBuffer) {
  24161. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24162. }
  24163. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24164. // Prepare Frame
  24165. this.postProcessManager._prepareFrame();
  24166. // Backgrounds
  24167. var layerIndex;
  24168. var layer;
  24169. if (this.layers.length) {
  24170. engine.setDepthBuffer(false);
  24171. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24172. layer = this.layers[layerIndex];
  24173. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24174. layer.render();
  24175. }
  24176. }
  24177. engine.setDepthBuffer(true);
  24178. }
  24179. // Activate effect Layer stencil
  24180. if (needStencil) {
  24181. this._engine.setStencilBuffer(true);
  24182. }
  24183. // Render
  24184. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24185. this._renderingManager.render(null, null, true, true);
  24186. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24187. // Restore effect Layer stencil
  24188. if (needStencil) {
  24189. this._engine.setStencilBuffer(stencilState);
  24190. }
  24191. // Bounding boxes
  24192. if (this._boundingBoxRenderer) {
  24193. this._boundingBoxRenderer.render();
  24194. }
  24195. // Lens flares
  24196. if (this.lensFlaresEnabled) {
  24197. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24198. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24199. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24200. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24201. lensFlareSystem.render();
  24202. }
  24203. }
  24204. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24205. }
  24206. // Foregrounds
  24207. if (this.layers.length) {
  24208. engine.setDepthBuffer(false);
  24209. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24210. layer = this.layers[layerIndex];
  24211. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24212. layer.render();
  24213. }
  24214. }
  24215. engine.setDepthBuffer(true);
  24216. }
  24217. // Effect Layer
  24218. if (renderEffects) {
  24219. engine.setDepthBuffer(false);
  24220. for (var i = 0; i < this.effectLayers.length; i++) {
  24221. if (this.effectLayers[i].shouldRender()) {
  24222. this.effectLayers[i].render();
  24223. }
  24224. }
  24225. engine.setDepthBuffer(true);
  24226. }
  24227. // Finalize frame
  24228. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24229. // Reset some special arrays
  24230. this._renderTargets.reset();
  24231. this._alternateRendering = false;
  24232. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24233. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24234. };
  24235. Scene.prototype._processSubCameras = function (camera) {
  24236. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24237. this._renderForCamera(camera);
  24238. return;
  24239. }
  24240. // rig cameras
  24241. for (var index = 0; index < camera._rigCameras.length; index++) {
  24242. this._renderForCamera(camera._rigCameras[index], camera);
  24243. }
  24244. this.activeCamera = camera;
  24245. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24246. };
  24247. Scene.prototype._checkIntersections = function () {
  24248. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24249. var sourceMesh = this._meshesForIntersections.data[index];
  24250. if (!sourceMesh.actionManager) {
  24251. continue;
  24252. }
  24253. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24254. var action = sourceMesh.actionManager.actions[actionIndex];
  24255. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24256. var parameters = action.getTriggerParameter();
  24257. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24258. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24259. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24260. if (areIntersecting && currentIntersectionInProgress === -1) {
  24261. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24262. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24263. sourceMesh._intersectionsInProgress.push(otherMesh);
  24264. }
  24265. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24266. sourceMesh._intersectionsInProgress.push(otherMesh);
  24267. }
  24268. }
  24269. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24270. //They intersected, and now they don't.
  24271. //is this trigger an exit trigger? execute an event.
  24272. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24273. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24274. }
  24275. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24276. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24277. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24278. }
  24279. }
  24280. }
  24281. }
  24282. }
  24283. };
  24284. Scene.prototype.render = function () {
  24285. if (this.isDisposed) {
  24286. return;
  24287. }
  24288. this._activeParticles.fetchNewFrame();
  24289. this._totalVertices.fetchNewFrame();
  24290. this._activeIndices.fetchNewFrame();
  24291. this._activeBones.fetchNewFrame();
  24292. this._meshesForIntersections.reset();
  24293. this.resetCachedMaterial();
  24294. this.onBeforeAnimationsObservable.notifyObservers(this);
  24295. // Actions
  24296. if (this.actionManager) {
  24297. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24298. }
  24299. //Simplification Queue
  24300. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24301. this.simplificationQueue.executeNext();
  24302. }
  24303. if (this._engine.isDeterministicLockStep()) {
  24304. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24305. var defaultFPS = (60.0 / 1000.0);
  24306. var defaultFrameTime = 1000 / 60; // frame time in MS
  24307. if (this._physicsEngine) {
  24308. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24309. }
  24310. var stepsTaken = 0;
  24311. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24312. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24313. internalSteps = Math.min(internalSteps, maxSubSteps);
  24314. do {
  24315. this.onBeforeStepObservable.notifyObservers(this);
  24316. // Animations
  24317. this._animationRatio = defaultFrameTime * defaultFPS;
  24318. this._animate();
  24319. this.onAfterAnimationsObservable.notifyObservers(this);
  24320. // Physics
  24321. if (this._physicsEngine) {
  24322. this.onBeforePhysicsObservable.notifyObservers(this);
  24323. this._physicsEngine._step(defaultFrameTime / 1000);
  24324. this.onAfterPhysicsObservable.notifyObservers(this);
  24325. }
  24326. this.onAfterStepObservable.notifyObservers(this);
  24327. this._currentStepId++;
  24328. stepsTaken++;
  24329. deltaTime -= defaultFrameTime;
  24330. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24331. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24332. }
  24333. else {
  24334. // Animations
  24335. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24336. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24337. this._animate();
  24338. this.onAfterAnimationsObservable.notifyObservers(this);
  24339. // Physics
  24340. if (this._physicsEngine) {
  24341. this.onBeforePhysicsObservable.notifyObservers(this);
  24342. this._physicsEngine._step(deltaTime / 1000.0);
  24343. this.onAfterPhysicsObservable.notifyObservers(this);
  24344. }
  24345. }
  24346. // update gamepad manager
  24347. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24348. this._gamepadManager._checkGamepadsStatus();
  24349. }
  24350. // Update Cameras
  24351. if (this.activeCameras.length > 0) {
  24352. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24353. var camera = this.activeCameras[cameraIndex];
  24354. camera.update();
  24355. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24356. // rig cameras
  24357. for (var index = 0; index < camera._rigCameras.length; index++) {
  24358. camera._rigCameras[index].update();
  24359. }
  24360. }
  24361. }
  24362. }
  24363. else if (this.activeCamera) {
  24364. this.activeCamera.update();
  24365. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24366. // rig cameras
  24367. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24368. this.activeCamera._rigCameras[index].update();
  24369. }
  24370. }
  24371. }
  24372. // Before render
  24373. this.onBeforeRenderObservable.notifyObservers(this);
  24374. // Customs render targets
  24375. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24376. var engine = this.getEngine();
  24377. var currentActiveCamera = this.activeCamera;
  24378. if (this.renderTargetsEnabled) {
  24379. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24380. this._intermediateRendering = true;
  24381. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24382. var renderTarget = this.customRenderTargets[customIndex];
  24383. if (renderTarget._shouldRender()) {
  24384. this._renderId++;
  24385. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24386. if (!this.activeCamera)
  24387. throw new Error("Active camera not set");
  24388. // Viewport
  24389. engine.setViewport(this.activeCamera.viewport);
  24390. // Camera
  24391. this.updateTransformMatrix();
  24392. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24393. }
  24394. }
  24395. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24396. this._intermediateRendering = false;
  24397. this._renderId++;
  24398. }
  24399. // Restore back buffer
  24400. if (this.customRenderTargets.length > 0) {
  24401. engine.restoreDefaultFramebuffer();
  24402. }
  24403. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24404. this.activeCamera = currentActiveCamera;
  24405. // Procedural textures
  24406. if (this.proceduralTexturesEnabled) {
  24407. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24408. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24409. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24410. if (proceduralTexture._shouldRender()) {
  24411. proceduralTexture.render();
  24412. }
  24413. }
  24414. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24415. }
  24416. // Clear
  24417. if (this.autoClearDepthAndStencil || this.autoClear) {
  24418. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24419. }
  24420. // Shadows
  24421. if (this.shadowsEnabled) {
  24422. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24423. var light = this.lights[lightIndex];
  24424. var shadowGenerator = light.getShadowGenerator();
  24425. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24426. var shadowMap = (shadowGenerator.getShadowMap());
  24427. if (this.textures.indexOf(shadowMap) !== -1) {
  24428. this._renderTargets.push(shadowMap);
  24429. }
  24430. }
  24431. }
  24432. }
  24433. // Depth renderer
  24434. for (var key in this._depthRenderer) {
  24435. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24436. }
  24437. // Geometry renderer
  24438. if (this._geometryBufferRenderer) {
  24439. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24440. }
  24441. // RenderPipeline
  24442. if (this._postProcessRenderPipelineManager) {
  24443. this._postProcessRenderPipelineManager.update();
  24444. }
  24445. // Multi-cameras?
  24446. if (this.activeCameras.length > 0) {
  24447. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24448. if (cameraIndex > 0) {
  24449. this._engine.clear(null, false, true, true);
  24450. }
  24451. this._processSubCameras(this.activeCameras[cameraIndex]);
  24452. }
  24453. }
  24454. else {
  24455. if (!this.activeCamera) {
  24456. throw new Error("No camera defined");
  24457. }
  24458. this._processSubCameras(this.activeCamera);
  24459. }
  24460. // Intersection checks
  24461. this._checkIntersections();
  24462. // Update the audio listener attached to the camera
  24463. if (BABYLON.AudioEngine) {
  24464. this._updateAudioParameters();
  24465. }
  24466. // After render
  24467. if (this.afterRender) {
  24468. this.afterRender();
  24469. }
  24470. this.onAfterRenderObservable.notifyObservers(this);
  24471. // Cleaning
  24472. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24473. var data = this._toBeDisposed.data[index];
  24474. if (data) {
  24475. data.dispose();
  24476. }
  24477. this._toBeDisposed[index] = null;
  24478. }
  24479. this._toBeDisposed.reset();
  24480. if (this.dumpNextRenderTargets) {
  24481. this.dumpNextRenderTargets = false;
  24482. }
  24483. this._activeBones.addCount(0, true);
  24484. this._activeIndices.addCount(0, true);
  24485. this._activeParticles.addCount(0, true);
  24486. };
  24487. Scene.prototype._updateAudioParameters = function () {
  24488. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24489. return;
  24490. }
  24491. var listeningCamera;
  24492. var audioEngine = BABYLON.Engine.audioEngine;
  24493. if (this.activeCameras.length > 0) {
  24494. listeningCamera = this.activeCameras[0];
  24495. }
  24496. else {
  24497. listeningCamera = this.activeCamera;
  24498. }
  24499. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24500. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24501. // for VR cameras
  24502. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24503. listeningCamera = listeningCamera.rigCameras[0];
  24504. }
  24505. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24506. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24507. cameraDirection.normalize();
  24508. // To avoid some errors on GearVR
  24509. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24510. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24511. }
  24512. var i;
  24513. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24514. var sound = this.mainSoundTrack.soundCollection[i];
  24515. if (sound.useCustomAttenuation) {
  24516. sound.updateDistanceFromListener();
  24517. }
  24518. }
  24519. for (i = 0; i < this.soundTracks.length; i++) {
  24520. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24521. sound = this.soundTracks[i].soundCollection[j];
  24522. if (sound.useCustomAttenuation) {
  24523. sound.updateDistanceFromListener();
  24524. }
  24525. }
  24526. }
  24527. }
  24528. };
  24529. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24530. // Audio
  24531. get: function () {
  24532. return this._audioEnabled;
  24533. },
  24534. set: function (value) {
  24535. this._audioEnabled = value;
  24536. if (BABYLON.AudioEngine) {
  24537. if (this._audioEnabled) {
  24538. this._enableAudio();
  24539. }
  24540. else {
  24541. this._disableAudio();
  24542. }
  24543. }
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Scene.prototype._disableAudio = function () {
  24549. var i;
  24550. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24551. this.mainSoundTrack.soundCollection[i].pause();
  24552. }
  24553. for (i = 0; i < this.soundTracks.length; i++) {
  24554. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24555. this.soundTracks[i].soundCollection[j].pause();
  24556. }
  24557. }
  24558. };
  24559. Scene.prototype._enableAudio = function () {
  24560. var i;
  24561. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24562. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24563. this.mainSoundTrack.soundCollection[i].play();
  24564. }
  24565. }
  24566. for (i = 0; i < this.soundTracks.length; i++) {
  24567. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24568. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24569. this.soundTracks[i].soundCollection[j].play();
  24570. }
  24571. }
  24572. }
  24573. };
  24574. Object.defineProperty(Scene.prototype, "headphone", {
  24575. get: function () {
  24576. return this._headphone;
  24577. },
  24578. set: function (value) {
  24579. this._headphone = value;
  24580. if (BABYLON.AudioEngine) {
  24581. if (this._headphone) {
  24582. this._switchAudioModeForHeadphones();
  24583. }
  24584. else {
  24585. this._switchAudioModeForNormalSpeakers();
  24586. }
  24587. }
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Scene.prototype._switchAudioModeForHeadphones = function () {
  24593. this.mainSoundTrack.switchPanningModelToHRTF();
  24594. for (var i = 0; i < this.soundTracks.length; i++) {
  24595. this.soundTracks[i].switchPanningModelToHRTF();
  24596. }
  24597. };
  24598. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24599. this.mainSoundTrack.switchPanningModelToEqualPower();
  24600. for (var i = 0; i < this.soundTracks.length; i++) {
  24601. this.soundTracks[i].switchPanningModelToEqualPower();
  24602. }
  24603. };
  24604. /**
  24605. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24606. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24607. * @returns the created depth renderer
  24608. */
  24609. Scene.prototype.enableDepthRenderer = function (camera) {
  24610. camera = camera || this.activeCamera;
  24611. if (!camera) {
  24612. throw "No camera available to enable depth renderer";
  24613. }
  24614. if (!this._depthRenderer[camera.id]) {
  24615. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24616. }
  24617. return this._depthRenderer[camera.id];
  24618. };
  24619. /**
  24620. * Disables a depth renderer for a given camera
  24621. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24622. */
  24623. Scene.prototype.disableDepthRenderer = function (camera) {
  24624. camera = camera || this.activeCamera;
  24625. if (!camera || !this._depthRenderer[camera.id]) {
  24626. return;
  24627. }
  24628. this._depthRenderer[camera.id].dispose();
  24629. delete this._depthRenderer[camera.id];
  24630. };
  24631. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24632. if (ratio === void 0) { ratio = 1; }
  24633. if (this._geometryBufferRenderer) {
  24634. return this._geometryBufferRenderer;
  24635. }
  24636. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24637. if (!this._geometryBufferRenderer.isSupported) {
  24638. this._geometryBufferRenderer = null;
  24639. }
  24640. return this._geometryBufferRenderer;
  24641. };
  24642. Scene.prototype.disableGeometryBufferRenderer = function () {
  24643. if (!this._geometryBufferRenderer) {
  24644. return;
  24645. }
  24646. this._geometryBufferRenderer.dispose();
  24647. this._geometryBufferRenderer = null;
  24648. };
  24649. Scene.prototype.freezeMaterials = function () {
  24650. for (var i = 0; i < this.materials.length; i++) {
  24651. this.materials[i].freeze();
  24652. }
  24653. };
  24654. Scene.prototype.unfreezeMaterials = function () {
  24655. for (var i = 0; i < this.materials.length; i++) {
  24656. this.materials[i].unfreeze();
  24657. }
  24658. };
  24659. Scene.prototype.dispose = function () {
  24660. this.beforeRender = null;
  24661. this.afterRender = null;
  24662. this.skeletons = [];
  24663. this.morphTargetManagers = [];
  24664. this.importedMeshesFiles = new Array();
  24665. this.stopAllAnimations();
  24666. this.resetCachedMaterial();
  24667. for (var key in this._depthRenderer) {
  24668. this._depthRenderer[key].dispose();
  24669. }
  24670. if (this._gamepadManager) {
  24671. this._gamepadManager.dispose();
  24672. this._gamepadManager = null;
  24673. }
  24674. // Smart arrays
  24675. if (this.activeCamera) {
  24676. this.activeCamera._activeMeshes.dispose();
  24677. this.activeCamera = null;
  24678. }
  24679. this._activeMeshes.dispose();
  24680. this._renderingManager.dispose();
  24681. this._processedMaterials.dispose();
  24682. this._activeParticleSystems.dispose();
  24683. this._activeSkeletons.dispose();
  24684. this._softwareSkinnedMeshes.dispose();
  24685. this._renderTargets.dispose();
  24686. if (this._boundingBoxRenderer) {
  24687. this._boundingBoxRenderer.dispose();
  24688. }
  24689. this._meshesForIntersections.dispose();
  24690. this._toBeDisposed.dispose();
  24691. // Abort active requests
  24692. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24693. var request = _a[_i];
  24694. request.abort();
  24695. }
  24696. // Debug layer
  24697. if (this._debugLayer) {
  24698. this._debugLayer.hide();
  24699. }
  24700. // Events
  24701. this.onDisposeObservable.notifyObservers(this);
  24702. this.onDisposeObservable.clear();
  24703. this.onBeforeRenderObservable.clear();
  24704. this.onAfterRenderObservable.clear();
  24705. this.OnBeforeRenderTargetsRenderObservable.clear();
  24706. this.OnAfterRenderTargetsRenderObservable.clear();
  24707. this.onAfterStepObservable.clear();
  24708. this.onBeforeStepObservable.clear();
  24709. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24710. this.onAfterActiveMeshesEvaluationObservable.clear();
  24711. this.onBeforeParticlesRenderingObservable.clear();
  24712. this.onAfterParticlesRenderingObservable.clear();
  24713. this.onBeforeSpritesRenderingObservable.clear();
  24714. this.onAfterSpritesRenderingObservable.clear();
  24715. this.onBeforeDrawPhaseObservable.clear();
  24716. this.onAfterDrawPhaseObservable.clear();
  24717. this.onBeforePhysicsObservable.clear();
  24718. this.onAfterPhysicsObservable.clear();
  24719. this.onBeforeAnimationsObservable.clear();
  24720. this.onAfterAnimationsObservable.clear();
  24721. this.onDataLoadedObservable.clear();
  24722. this.detachControl();
  24723. // Release sounds & sounds tracks
  24724. if (BABYLON.AudioEngine) {
  24725. this.disposeSounds();
  24726. }
  24727. // VR Helper
  24728. if (this.VRHelper) {
  24729. this.VRHelper.dispose();
  24730. }
  24731. // Detach cameras
  24732. var canvas = this._engine.getRenderingCanvas();
  24733. if (canvas) {
  24734. var index;
  24735. for (index = 0; index < this.cameras.length; index++) {
  24736. this.cameras[index].detachControl(canvas);
  24737. }
  24738. }
  24739. // Release animation groups
  24740. while (this.animationGroups.length) {
  24741. this.animationGroups[0].dispose();
  24742. }
  24743. // Release lights
  24744. while (this.lights.length) {
  24745. this.lights[0].dispose();
  24746. }
  24747. // Release meshes
  24748. while (this.meshes.length) {
  24749. this.meshes[0].dispose(true);
  24750. }
  24751. while (this.transformNodes.length) {
  24752. this.removeTransformNode(this.transformNodes[0]);
  24753. }
  24754. // Release cameras
  24755. while (this.cameras.length) {
  24756. this.cameras[0].dispose();
  24757. }
  24758. // Release materials
  24759. if (this.defaultMaterial) {
  24760. this.defaultMaterial.dispose();
  24761. }
  24762. while (this.multiMaterials.length) {
  24763. this.multiMaterials[0].dispose();
  24764. }
  24765. while (this.materials.length) {
  24766. this.materials[0].dispose();
  24767. }
  24768. // Release particles
  24769. while (this.particleSystems.length) {
  24770. this.particleSystems[0].dispose();
  24771. }
  24772. // Release sprites
  24773. while (this.spriteManagers.length) {
  24774. this.spriteManagers[0].dispose();
  24775. }
  24776. // Release postProcesses
  24777. while (this.postProcesses.length) {
  24778. this.postProcesses[0].dispose();
  24779. }
  24780. // Release layers
  24781. while (this.layers.length) {
  24782. this.layers[0].dispose();
  24783. }
  24784. while (this.effectLayers.length) {
  24785. this.effectLayers[0].dispose();
  24786. }
  24787. // Release textures
  24788. while (this.textures.length) {
  24789. this.textures[0].dispose();
  24790. }
  24791. // Release UBO
  24792. this._sceneUbo.dispose();
  24793. if (this._alternateSceneUbo) {
  24794. this._alternateSceneUbo.dispose();
  24795. }
  24796. // Post-processes
  24797. this.postProcessManager.dispose();
  24798. if (this._postProcessRenderPipelineManager) {
  24799. this._postProcessRenderPipelineManager.dispose();
  24800. }
  24801. // Physics
  24802. if (this._physicsEngine) {
  24803. this.disablePhysicsEngine();
  24804. }
  24805. // Remove from engine
  24806. index = this._engine.scenes.indexOf(this);
  24807. if (index > -1) {
  24808. this._engine.scenes.splice(index, 1);
  24809. }
  24810. this._engine.wipeCaches(true);
  24811. this._isDisposed = true;
  24812. };
  24813. Object.defineProperty(Scene.prototype, "isDisposed", {
  24814. get: function () {
  24815. return this._isDisposed;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. // Release sounds & sounds tracks
  24821. Scene.prototype.disposeSounds = function () {
  24822. if (!this._mainSoundTrack) {
  24823. return;
  24824. }
  24825. this.mainSoundTrack.dispose();
  24826. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24827. this.soundTracks[scIndex].dispose();
  24828. }
  24829. };
  24830. // Octrees
  24831. /**
  24832. * Get the world extend vectors with an optional filter
  24833. *
  24834. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24835. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24836. */
  24837. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24838. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24839. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24840. filterPredicate = filterPredicate || (function () { return true; });
  24841. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24842. mesh.computeWorldMatrix(true);
  24843. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24844. return;
  24845. }
  24846. var boundingInfo = mesh.getBoundingInfo();
  24847. var minBox = boundingInfo.boundingBox.minimumWorld;
  24848. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24849. BABYLON.Tools.CheckExtends(minBox, min, max);
  24850. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24851. });
  24852. return {
  24853. min: min,
  24854. max: max
  24855. };
  24856. };
  24857. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24858. if (maxCapacity === void 0) { maxCapacity = 64; }
  24859. if (maxDepth === void 0) { maxDepth = 2; }
  24860. if (!this._selectionOctree) {
  24861. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24862. }
  24863. var worldExtends = this.getWorldExtends();
  24864. // Update octree
  24865. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24866. return this._selectionOctree;
  24867. };
  24868. // Picking
  24869. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24870. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24871. var result = BABYLON.Ray.Zero();
  24872. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24873. return result;
  24874. };
  24875. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24876. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24877. var engine = this._engine;
  24878. if (!camera) {
  24879. if (!this.activeCamera)
  24880. throw new Error("Active camera not set");
  24881. camera = this.activeCamera;
  24882. }
  24883. var cameraViewport = camera.viewport;
  24884. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24885. // Moving coordinates to local viewport world
  24886. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24887. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24888. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24889. return this;
  24890. };
  24891. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24892. var result = BABYLON.Ray.Zero();
  24893. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24894. return result;
  24895. };
  24896. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24897. if (!BABYLON.PickingInfo) {
  24898. return this;
  24899. }
  24900. var engine = this._engine;
  24901. if (!camera) {
  24902. if (!this.activeCamera)
  24903. throw new Error("Active camera not set");
  24904. camera = this.activeCamera;
  24905. }
  24906. var cameraViewport = camera.viewport;
  24907. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24908. var identity = BABYLON.Matrix.Identity();
  24909. // Moving coordinates to local viewport world
  24910. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24911. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24912. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24913. return this;
  24914. };
  24915. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24916. if (!BABYLON.PickingInfo) {
  24917. return null;
  24918. }
  24919. var pickingInfo = null;
  24920. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24921. var mesh = this.meshes[meshIndex];
  24922. if (predicate) {
  24923. if (!predicate(mesh)) {
  24924. continue;
  24925. }
  24926. }
  24927. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24928. continue;
  24929. }
  24930. var world = mesh.getWorldMatrix();
  24931. var ray = rayFunction(world);
  24932. var result = mesh.intersects(ray, fastCheck);
  24933. if (!result || !result.hit)
  24934. continue;
  24935. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24936. continue;
  24937. pickingInfo = result;
  24938. if (fastCheck) {
  24939. break;
  24940. }
  24941. }
  24942. return pickingInfo || new BABYLON.PickingInfo();
  24943. };
  24944. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24945. if (!BABYLON.PickingInfo) {
  24946. return null;
  24947. }
  24948. var pickingInfos = new Array();
  24949. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24950. var mesh = this.meshes[meshIndex];
  24951. if (predicate) {
  24952. if (!predicate(mesh)) {
  24953. continue;
  24954. }
  24955. }
  24956. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24957. continue;
  24958. }
  24959. var world = mesh.getWorldMatrix();
  24960. var ray = rayFunction(world);
  24961. var result = mesh.intersects(ray, false);
  24962. if (!result || !result.hit)
  24963. continue;
  24964. pickingInfos.push(result);
  24965. }
  24966. return pickingInfos;
  24967. };
  24968. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24969. if (!BABYLON.PickingInfo) {
  24970. return null;
  24971. }
  24972. var pickingInfo = null;
  24973. if (!camera) {
  24974. if (!this.activeCamera) {
  24975. return null;
  24976. }
  24977. camera = this.activeCamera;
  24978. }
  24979. if (this.spriteManagers.length > 0) {
  24980. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24981. var spriteManager = this.spriteManagers[spriteIndex];
  24982. if (!spriteManager.isPickable) {
  24983. continue;
  24984. }
  24985. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24986. if (!result || !result.hit)
  24987. continue;
  24988. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24989. continue;
  24990. pickingInfo = result;
  24991. if (fastCheck) {
  24992. break;
  24993. }
  24994. }
  24995. }
  24996. return pickingInfo || new BABYLON.PickingInfo();
  24997. };
  24998. /** Launch a ray to try to pick a mesh in the scene
  24999. * @param x position on screen
  25000. * @param y position on screen
  25001. * @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
  25002. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25003. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25004. */
  25005. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25006. var _this = this;
  25007. if (!BABYLON.PickingInfo) {
  25008. return null;
  25009. }
  25010. return this._internalPick(function (world) {
  25011. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25012. return _this._tempPickingRay;
  25013. }, predicate, fastCheck);
  25014. };
  25015. /** Launch a ray to try to pick a sprite in the scene
  25016. * @param x position on screen
  25017. * @param y position on screen
  25018. * @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
  25019. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25020. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25021. */
  25022. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25023. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25024. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25025. };
  25026. /** Use the given ray to pick a mesh in the scene
  25027. * @param ray The ray to use to pick meshes
  25028. * @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
  25029. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25030. */
  25031. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25032. var _this = this;
  25033. return this._internalPick(function (world) {
  25034. if (!_this._pickWithRayInverseMatrix) {
  25035. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25036. }
  25037. world.invertToRef(_this._pickWithRayInverseMatrix);
  25038. if (!_this._cachedRayForTransform) {
  25039. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25040. }
  25041. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25042. return _this._cachedRayForTransform;
  25043. }, predicate, fastCheck);
  25044. };
  25045. /**
  25046. * Launch a ray to try to pick a mesh in the scene
  25047. * @param x X position on screen
  25048. * @param y Y position on screen
  25049. * @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
  25050. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25051. */
  25052. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25053. var _this = this;
  25054. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25055. };
  25056. /**
  25057. * Launch a ray to try to pick a mesh in the scene
  25058. * @param ray Ray to use
  25059. * @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
  25060. */
  25061. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25062. var _this = this;
  25063. return this._internalMultiPick(function (world) {
  25064. if (!_this._pickWithRayInverseMatrix) {
  25065. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25066. }
  25067. world.invertToRef(_this._pickWithRayInverseMatrix);
  25068. if (!_this._cachedRayForTransform) {
  25069. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25070. }
  25071. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25072. return _this._cachedRayForTransform;
  25073. }, predicate);
  25074. };
  25075. Scene.prototype.setPointerOverMesh = function (mesh) {
  25076. if (this._pointerOverMesh === mesh) {
  25077. return;
  25078. }
  25079. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25080. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25081. }
  25082. this._pointerOverMesh = mesh;
  25083. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25084. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25085. }
  25086. };
  25087. Scene.prototype.getPointerOverMesh = function () {
  25088. return this._pointerOverMesh;
  25089. };
  25090. Scene.prototype.setPointerOverSprite = function (sprite) {
  25091. if (this._pointerOverSprite === sprite) {
  25092. return;
  25093. }
  25094. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25095. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25096. }
  25097. this._pointerOverSprite = sprite;
  25098. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25099. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25100. }
  25101. };
  25102. Scene.prototype.getPointerOverSprite = function () {
  25103. return this._pointerOverSprite;
  25104. };
  25105. // Physics
  25106. Scene.prototype.getPhysicsEngine = function () {
  25107. return this._physicsEngine;
  25108. };
  25109. /**
  25110. * Enables physics to the current scene
  25111. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25112. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25113. * @return {boolean} was the physics engine initialized
  25114. */
  25115. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25116. if (gravity === void 0) { gravity = null; }
  25117. if (this._physicsEngine) {
  25118. return true;
  25119. }
  25120. try {
  25121. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25122. return true;
  25123. }
  25124. catch (e) {
  25125. BABYLON.Tools.Error(e.message);
  25126. return false;
  25127. }
  25128. };
  25129. Scene.prototype.disablePhysicsEngine = function () {
  25130. if (!this._physicsEngine) {
  25131. return;
  25132. }
  25133. this._physicsEngine.dispose();
  25134. this._physicsEngine = null;
  25135. };
  25136. Scene.prototype.isPhysicsEnabled = function () {
  25137. return this._physicsEngine !== undefined;
  25138. };
  25139. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25140. var mesh = compound.parts[0].mesh;
  25141. if (mesh.physicsImpostor) {
  25142. mesh.physicsImpostor.dispose();
  25143. mesh.physicsImpostor = null;
  25144. }
  25145. };
  25146. // Misc.
  25147. Scene.prototype._rebuildGeometries = function () {
  25148. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25149. var geometry = _a[_i];
  25150. geometry._rebuild();
  25151. }
  25152. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25153. var mesh = _c[_b];
  25154. mesh._rebuild();
  25155. }
  25156. if (this.postProcessManager) {
  25157. this.postProcessManager._rebuild();
  25158. }
  25159. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25160. var layer = _e[_d];
  25161. layer._rebuild();
  25162. }
  25163. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25164. var effectLayer = _g[_f];
  25165. effectLayer._rebuild();
  25166. }
  25167. if (this._boundingBoxRenderer) {
  25168. this._boundingBoxRenderer._rebuild();
  25169. }
  25170. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25171. var system = _j[_h];
  25172. system.rebuild();
  25173. }
  25174. if (this._postProcessRenderPipelineManager) {
  25175. this._postProcessRenderPipelineManager._rebuild();
  25176. }
  25177. };
  25178. Scene.prototype._rebuildTextures = function () {
  25179. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25180. var texture = _a[_i];
  25181. texture._rebuild();
  25182. }
  25183. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25184. };
  25185. /**
  25186. * Creates a default light for the scene.
  25187. * @param replace Whether to replace the existing lights in the scene.
  25188. */
  25189. Scene.prototype.createDefaultLight = function (replace) {
  25190. if (replace === void 0) { replace = false; }
  25191. // Dispose existing light in replace mode.
  25192. if (replace) {
  25193. if (this.lights) {
  25194. for (var i = 0; i < this.lights.length; i++) {
  25195. this.lights[i].dispose();
  25196. }
  25197. }
  25198. }
  25199. // Light
  25200. if (this.lights.length === 0) {
  25201. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25202. }
  25203. };
  25204. /**
  25205. * Creates a default camera for the scene.
  25206. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25207. * @param replace Whether to replace the existing active camera in the scene.
  25208. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25209. */
  25210. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25211. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25212. if (replace === void 0) { replace = false; }
  25213. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25214. // Dispose existing camera in replace mode.
  25215. if (replace) {
  25216. if (this.activeCamera) {
  25217. this.activeCamera.dispose();
  25218. this.activeCamera = null;
  25219. }
  25220. }
  25221. // Camera
  25222. if (!this.activeCamera) {
  25223. var worldExtends = this.getWorldExtends();
  25224. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25225. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25226. var camera;
  25227. var radius = worldSize.length() * 1.5;
  25228. // empty scene scenario!
  25229. if (!isFinite(radius)) {
  25230. radius = 1;
  25231. worldCenter.copyFromFloats(0, 0, 0);
  25232. }
  25233. if (createArcRotateCamera) {
  25234. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25235. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25236. arcRotateCamera.wheelPrecision = 100 / radius;
  25237. camera = arcRotateCamera;
  25238. }
  25239. else {
  25240. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25241. freeCamera.setTarget(worldCenter);
  25242. camera = freeCamera;
  25243. }
  25244. camera.minZ = radius * 0.01;
  25245. camera.maxZ = radius * 1000;
  25246. camera.speed = radius * 0.2;
  25247. this.activeCamera = camera;
  25248. var canvas = this.getEngine().getRenderingCanvas();
  25249. if (attachCameraControls && canvas) {
  25250. camera.attachControl(canvas);
  25251. }
  25252. }
  25253. };
  25254. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25255. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25256. if (replace === void 0) { replace = false; }
  25257. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25258. this.createDefaultLight(replace);
  25259. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25260. };
  25261. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25262. if (pbr === void 0) { pbr = false; }
  25263. if (scale === void 0) { scale = 1000; }
  25264. if (blur === void 0) { blur = 0; }
  25265. if (environmentTexture) {
  25266. this.environmentTexture = environmentTexture;
  25267. }
  25268. if (!this.environmentTexture) {
  25269. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25270. return null;
  25271. }
  25272. // Skybox
  25273. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25274. if (pbr) {
  25275. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25276. hdrSkyboxMaterial.backFaceCulling = false;
  25277. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25278. if (hdrSkyboxMaterial.reflectionTexture) {
  25279. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25280. }
  25281. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25282. hdrSkyboxMaterial.disableLighting = true;
  25283. hdrSkyboxMaterial.twoSidedLighting = true;
  25284. hdrSkybox.infiniteDistance = true;
  25285. hdrSkybox.material = hdrSkyboxMaterial;
  25286. }
  25287. else {
  25288. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25289. skyboxMaterial.backFaceCulling = false;
  25290. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25291. if (skyboxMaterial.reflectionTexture) {
  25292. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25293. }
  25294. skyboxMaterial.disableLighting = true;
  25295. hdrSkybox.infiniteDistance = true;
  25296. hdrSkybox.material = skyboxMaterial;
  25297. }
  25298. return hdrSkybox;
  25299. };
  25300. Scene.prototype.createDefaultEnvironment = function (options) {
  25301. if (BABYLON.EnvironmentHelper) {
  25302. return new BABYLON.EnvironmentHelper(options, this);
  25303. }
  25304. return null;
  25305. };
  25306. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25307. if (webVROptions === void 0) { webVROptions = {}; }
  25308. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25309. };
  25310. // Tags
  25311. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25312. if (tagsQuery === undefined) {
  25313. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25314. return list;
  25315. }
  25316. var listByTags = [];
  25317. forEach = forEach || (function (item) { return; });
  25318. for (var i in list) {
  25319. var item = list[i];
  25320. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25321. listByTags.push(item);
  25322. forEach(item);
  25323. }
  25324. }
  25325. return listByTags;
  25326. };
  25327. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25328. return this._getByTags(this.meshes, tagsQuery, forEach);
  25329. };
  25330. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25331. return this._getByTags(this.cameras, tagsQuery, forEach);
  25332. };
  25333. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25334. return this._getByTags(this.lights, tagsQuery, forEach);
  25335. };
  25336. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25337. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25338. };
  25339. /**
  25340. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25341. * This allowed control for front to back rendering or reversly depending of the special needs.
  25342. *
  25343. * @param renderingGroupId The rendering group id corresponding to its index
  25344. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25345. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25346. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25347. */
  25348. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25349. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25350. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25351. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25352. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25353. };
  25354. /**
  25355. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25356. *
  25357. * @param renderingGroupId The rendering group id corresponding to its index
  25358. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25359. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25360. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25361. */
  25362. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25363. if (depth === void 0) { depth = true; }
  25364. if (stencil === void 0) { stencil = true; }
  25365. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25366. };
  25367. /**
  25368. * Will flag all materials as dirty to trigger new shader compilation
  25369. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25370. */
  25371. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25372. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25373. var material = _a[_i];
  25374. if (predicate && !predicate(material)) {
  25375. continue;
  25376. }
  25377. material.markAsDirty(flag);
  25378. }
  25379. };
  25380. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25381. var _this = this;
  25382. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25383. this._activeRequests.push(request);
  25384. request.onCompleteObservable.add(function (request) {
  25385. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25386. });
  25387. return request;
  25388. };
  25389. /** @ignore */
  25390. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25391. var _this = this;
  25392. return new Promise(function (resolve, reject) {
  25393. _this._loadFile(url, function (data) {
  25394. resolve(data);
  25395. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25396. reject(exception);
  25397. });
  25398. });
  25399. };
  25400. // Statics
  25401. Scene._FOGMODE_NONE = 0;
  25402. Scene._FOGMODE_EXP = 1;
  25403. Scene._FOGMODE_EXP2 = 2;
  25404. Scene._FOGMODE_LINEAR = 3;
  25405. Scene._uniqueIdCounter = 0;
  25406. Scene.MinDeltaTime = 1.0;
  25407. Scene.MaxDeltaTime = 1000.0;
  25408. /** The distance in pixel that you have to move to prevent some events */
  25409. Scene.DragMovementThreshold = 10; // in pixels
  25410. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25411. Scene.LongPressDelay = 500; // in milliseconds
  25412. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25413. Scene.DoubleClickDelay = 300; // in milliseconds
  25414. /** If you need to check double click without raising a single click at first click, enable this flag */
  25415. Scene.ExclusiveDoubleClickMode = false;
  25416. return Scene;
  25417. }());
  25418. BABYLON.Scene = Scene;
  25419. })(BABYLON || (BABYLON = {}));
  25420. //# sourceMappingURL=babylon.scene.js.map
  25421. var BABYLON;
  25422. (function (BABYLON) {
  25423. /**
  25424. * Set of assets to keep when moving a scene into an asset container.
  25425. */
  25426. var KeepAssets = /** @class */ (function () {
  25427. function KeepAssets() {
  25428. /**
  25429. * Cameras to keep.
  25430. */
  25431. this.cameras = new Array();
  25432. /**
  25433. * Lights to keep.
  25434. */
  25435. this.lights = new Array();
  25436. /**
  25437. * Meshes to keep.
  25438. */
  25439. this.meshes = new Array();
  25440. /**
  25441. * Skeletons to keep.
  25442. */
  25443. this.skeletons = new Array();
  25444. /**
  25445. * ParticleSystems to keep.
  25446. */
  25447. this.particleSystems = new Array();
  25448. /**
  25449. * Animations to keep.
  25450. */
  25451. this.animations = new Array();
  25452. /**
  25453. * MultiMaterials to keep.
  25454. */
  25455. this.multiMaterials = new Array();
  25456. /**
  25457. * Materials to keep.
  25458. */
  25459. this.materials = new Array();
  25460. /**
  25461. * MorphTargetManagers to keep.
  25462. */
  25463. this.morphTargetManagers = new Array();
  25464. /**
  25465. * Geometries to keep.
  25466. */
  25467. this.geometries = new Array();
  25468. /**
  25469. * TransformNodes to keep.
  25470. */
  25471. this.transformNodes = new Array();
  25472. /**
  25473. * LensFlareSystems to keep.
  25474. */
  25475. this.lensFlareSystems = new Array();
  25476. /**
  25477. * ShadowGenerators to keep.
  25478. */
  25479. this.shadowGenerators = new Array();
  25480. /**
  25481. * ActionManagers to keep.
  25482. */
  25483. this.actionManagers = new Array();
  25484. /**
  25485. * Sounds to keep.
  25486. */
  25487. this.sounds = new Array();
  25488. }
  25489. return KeepAssets;
  25490. }());
  25491. BABYLON.KeepAssets = KeepAssets;
  25492. /**
  25493. * Container with a set of assets that can be added or removed from a scene.
  25494. */
  25495. var AssetContainer = /** @class */ (function () {
  25496. /**
  25497. * Instantiates an AssetContainer.
  25498. * @param scene The scene the AssetContainer belongs to.
  25499. */
  25500. function AssetContainer(scene) {
  25501. // Objects
  25502. /**
  25503. * Cameras populated in the container.
  25504. */
  25505. this.cameras = new Array();
  25506. /**
  25507. * Lights populated in the container.
  25508. */
  25509. this.lights = new Array();
  25510. /**
  25511. * Meshes populated in the container.
  25512. */
  25513. this.meshes = new Array();
  25514. /**
  25515. * Skeletons populated in the container.
  25516. */
  25517. this.skeletons = new Array();
  25518. /**
  25519. * ParticleSystems populated in the container.
  25520. */
  25521. this.particleSystems = new Array();
  25522. /**
  25523. * Animations populated in the container.
  25524. */
  25525. this.animations = new Array();
  25526. /**
  25527. * MultiMaterials populated in the container.
  25528. */
  25529. this.multiMaterials = new Array();
  25530. /**
  25531. * Materials populated in the container.
  25532. */
  25533. this.materials = new Array();
  25534. /**
  25535. * MorphTargetManagers populated in the container.
  25536. */
  25537. this.morphTargetManagers = new Array();
  25538. /**
  25539. * Geometries populated in the container.
  25540. */
  25541. this.geometries = new Array();
  25542. /**
  25543. * TransformNodes populated in the container.
  25544. */
  25545. this.transformNodes = new Array();
  25546. /**
  25547. * LensFlareSystems populated in the container.
  25548. */
  25549. this.lensFlareSystems = new Array();
  25550. /**
  25551. * ShadowGenerators populated in the container.
  25552. */
  25553. this.shadowGenerators = new Array();
  25554. /**
  25555. * ActionManagers populated in the container.
  25556. */
  25557. this.actionManagers = new Array();
  25558. /**
  25559. * Sounds populated in the container.
  25560. */
  25561. this.sounds = new Array();
  25562. this.scene = scene;
  25563. }
  25564. /**
  25565. * Adds all the assets from the container to the scene.
  25566. */
  25567. AssetContainer.prototype.addAllToScene = function () {
  25568. var _this = this;
  25569. this.cameras.forEach(function (o) {
  25570. _this.scene.addCamera(o);
  25571. });
  25572. this.lights.forEach(function (o) {
  25573. _this.scene.addLight(o);
  25574. });
  25575. this.meshes.forEach(function (o) {
  25576. _this.scene.addMesh(o);
  25577. });
  25578. this.skeletons.forEach(function (o) {
  25579. _this.scene.addSkeleton(o);
  25580. });
  25581. this.particleSystems.forEach(function (o) {
  25582. _this.scene.addParticleSystem(o);
  25583. });
  25584. this.animations.forEach(function (o) {
  25585. _this.scene.addAnimation(o);
  25586. });
  25587. this.multiMaterials.forEach(function (o) {
  25588. _this.scene.addMultiMaterial(o);
  25589. });
  25590. this.materials.forEach(function (o) {
  25591. _this.scene.addMaterial(o);
  25592. });
  25593. this.morphTargetManagers.forEach(function (o) {
  25594. _this.scene.addMorphTargetManager(o);
  25595. });
  25596. this.geometries.forEach(function (o) {
  25597. _this.scene.addGeometry(o);
  25598. });
  25599. this.transformNodes.forEach(function (o) {
  25600. _this.scene.addTransformNode(o);
  25601. });
  25602. this.lensFlareSystems.forEach(function (o) {
  25603. _this.scene.addLensFlareSystem(o);
  25604. });
  25605. this.actionManagers.forEach(function (o) {
  25606. _this.scene.addActionManager(o);
  25607. });
  25608. this.sounds.forEach(function (o) {
  25609. o.play();
  25610. o.autoplay = true;
  25611. _this.scene.mainSoundTrack.AddSound(o);
  25612. });
  25613. };
  25614. /**
  25615. * Removes all the assets in the container from the scene
  25616. */
  25617. AssetContainer.prototype.removeAllFromScene = function () {
  25618. var _this = this;
  25619. this.cameras.forEach(function (o) {
  25620. _this.scene.removeCamera(o);
  25621. });
  25622. this.lights.forEach(function (o) {
  25623. _this.scene.removeLight(o);
  25624. });
  25625. this.meshes.forEach(function (o) {
  25626. _this.scene.removeMesh(o);
  25627. });
  25628. this.skeletons.forEach(function (o) {
  25629. _this.scene.removeSkeleton(o);
  25630. });
  25631. this.particleSystems.forEach(function (o) {
  25632. _this.scene.removeParticleSystem(o);
  25633. });
  25634. this.animations.forEach(function (o) {
  25635. _this.scene.removeAnimation(o);
  25636. });
  25637. this.multiMaterials.forEach(function (o) {
  25638. _this.scene.removeMultiMaterial(o);
  25639. });
  25640. this.materials.forEach(function (o) {
  25641. _this.scene.removeMaterial(o);
  25642. });
  25643. this.morphTargetManagers.forEach(function (o) {
  25644. _this.scene.removeMorphTargetManager(o);
  25645. });
  25646. this.geometries.forEach(function (o) {
  25647. _this.scene.removeGeometry(o);
  25648. });
  25649. this.transformNodes.forEach(function (o) {
  25650. _this.scene.removeTransformNode(o);
  25651. });
  25652. this.lensFlareSystems.forEach(function (o) {
  25653. _this.scene.removeLensFlareSystem(o);
  25654. });
  25655. this.actionManagers.forEach(function (o) {
  25656. _this.scene.removeActionManager(o);
  25657. });
  25658. this.sounds.forEach(function (o) {
  25659. o.stop();
  25660. o.autoplay = false;
  25661. _this.scene.mainSoundTrack.RemoveSound(o);
  25662. });
  25663. };
  25664. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25665. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25666. var asset = sourceAssets_1[_i];
  25667. var move = true;
  25668. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25669. var keepAsset = keepAssets_1[_a];
  25670. if (asset === keepAsset) {
  25671. move = false;
  25672. break;
  25673. }
  25674. }
  25675. if (move) {
  25676. targetAssets.push(asset);
  25677. }
  25678. }
  25679. };
  25680. /**
  25681. * Removes all the assets contained in the scene and adds them to the container.
  25682. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25683. */
  25684. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25685. if (keepAssets === undefined) {
  25686. keepAssets = new KeepAssets();
  25687. }
  25688. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25689. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25690. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25691. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25692. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25693. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25694. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25695. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25696. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25697. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25698. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25699. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25700. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25701. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25702. this.removeAllFromScene();
  25703. };
  25704. return AssetContainer;
  25705. }());
  25706. BABYLON.AssetContainer = AssetContainer;
  25707. })(BABYLON || (BABYLON = {}));
  25708. //# sourceMappingURL=babylon.assetContainer.js.map
  25709. var BABYLON;
  25710. (function (BABYLON) {
  25711. var Buffer = /** @class */ (function () {
  25712. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25713. if (instanced === void 0) { instanced = false; }
  25714. if (engine instanceof BABYLON.Mesh) {
  25715. this._engine = engine.getScene().getEngine();
  25716. }
  25717. else {
  25718. this._engine = engine;
  25719. }
  25720. this._updatable = updatable;
  25721. this._instanced = instanced;
  25722. this._data = data;
  25723. this._strideSize = stride;
  25724. if (!postponeInternalCreation) {
  25725. this.create();
  25726. }
  25727. }
  25728. /**
  25729. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25730. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25731. * @param offset defines offset in the buffer (0 by default)
  25732. * @param size defines the size in floats of attributes (position is 3 for instance)
  25733. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25734. * @param instanced defines if the vertex buffer contains indexed data
  25735. * @returns the new vertex buffer
  25736. */
  25737. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25738. // a lot of these parameters are ignored as they are overriden by the buffer
  25739. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25740. };
  25741. // Properties
  25742. Buffer.prototype.isUpdatable = function () {
  25743. return this._updatable;
  25744. };
  25745. Buffer.prototype.getData = function () {
  25746. return this._data;
  25747. };
  25748. Buffer.prototype.getBuffer = function () {
  25749. return this._buffer;
  25750. };
  25751. Buffer.prototype.getStrideSize = function () {
  25752. return this._strideSize;
  25753. };
  25754. // public getIsInstanced(): boolean {
  25755. // return this._instanced;
  25756. // }
  25757. // public get instanceDivisor(): number {
  25758. // return this._instanceDivisor;
  25759. // }
  25760. // public set instanceDivisor(value: number) {
  25761. // this._instanceDivisor = value;
  25762. // if (value == 0) {
  25763. // this._instanced = false;
  25764. // } else {
  25765. // this._instanced = true;
  25766. // }
  25767. // }
  25768. // Methods
  25769. Buffer.prototype.create = function (data) {
  25770. if (data === void 0) { data = null; }
  25771. if (!data && this._buffer) {
  25772. return; // nothing to do
  25773. }
  25774. data = data || this._data;
  25775. if (!data) {
  25776. return;
  25777. }
  25778. if (!this._buffer) {
  25779. if (this._updatable) {
  25780. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25781. this._data = data;
  25782. }
  25783. else {
  25784. this._buffer = this._engine.createVertexBuffer(data);
  25785. }
  25786. }
  25787. else if (this._updatable) {
  25788. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25789. this._data = data;
  25790. }
  25791. };
  25792. Buffer.prototype._rebuild = function () {
  25793. this._buffer = null;
  25794. this.create(this._data);
  25795. };
  25796. Buffer.prototype.update = function (data) {
  25797. this.create(data);
  25798. };
  25799. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25800. if (!this._buffer) {
  25801. return;
  25802. }
  25803. if (this._updatable) {
  25804. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25805. this._data = null;
  25806. }
  25807. };
  25808. Buffer.prototype.dispose = function () {
  25809. if (!this._buffer) {
  25810. return;
  25811. }
  25812. if (this._engine._releaseBuffer(this._buffer)) {
  25813. this._buffer = null;
  25814. }
  25815. };
  25816. return Buffer;
  25817. }());
  25818. BABYLON.Buffer = Buffer;
  25819. })(BABYLON || (BABYLON = {}));
  25820. //# sourceMappingURL=babylon.buffer.js.map
  25821. var BABYLON;
  25822. (function (BABYLON) {
  25823. var VertexBuffer = /** @class */ (function () {
  25824. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25825. if (data instanceof BABYLON.Buffer) {
  25826. if (!stride) {
  25827. stride = data.getStrideSize();
  25828. }
  25829. this._buffer = data;
  25830. this._ownsBuffer = false;
  25831. }
  25832. else {
  25833. if (!stride) {
  25834. stride = VertexBuffer.DeduceStride(kind);
  25835. }
  25836. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25837. this._ownsBuffer = true;
  25838. }
  25839. this._stride = stride;
  25840. this._instanced = instanced !== undefined ? instanced : false;
  25841. this._instanceDivisor = instanced ? 1 : 0;
  25842. this._offset = offset ? offset : 0;
  25843. this._size = size ? size : stride;
  25844. this._kind = kind;
  25845. }
  25846. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25847. /**
  25848. * Gets or sets the instance divisor when in instanced mode
  25849. */
  25850. get: function () {
  25851. return this._instanceDivisor;
  25852. },
  25853. set: function (value) {
  25854. this._instanceDivisor = value;
  25855. if (value == 0) {
  25856. this._instanced = false;
  25857. }
  25858. else {
  25859. this._instanced = true;
  25860. }
  25861. },
  25862. enumerable: true,
  25863. configurable: true
  25864. });
  25865. VertexBuffer.prototype._rebuild = function () {
  25866. if (!this._buffer) {
  25867. return;
  25868. }
  25869. this._buffer._rebuild();
  25870. };
  25871. /**
  25872. * Returns the kind of the VertexBuffer (string).
  25873. */
  25874. VertexBuffer.prototype.getKind = function () {
  25875. return this._kind;
  25876. };
  25877. // Properties
  25878. /**
  25879. * Boolean : is the VertexBuffer updatable ?
  25880. */
  25881. VertexBuffer.prototype.isUpdatable = function () {
  25882. return this._buffer.isUpdatable();
  25883. };
  25884. /**
  25885. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25886. */
  25887. VertexBuffer.prototype.getData = function () {
  25888. return this._buffer.getData();
  25889. };
  25890. /**
  25891. * Returns the WebGLBuffer associated to the VertexBuffer.
  25892. */
  25893. VertexBuffer.prototype.getBuffer = function () {
  25894. return this._buffer.getBuffer();
  25895. };
  25896. /**
  25897. * Returns the stride of the VertexBuffer (integer).
  25898. */
  25899. VertexBuffer.prototype.getStrideSize = function () {
  25900. return this._stride;
  25901. };
  25902. /**
  25903. * Returns the offset (integer).
  25904. */
  25905. VertexBuffer.prototype.getOffset = function () {
  25906. return this._offset;
  25907. };
  25908. /**
  25909. * Returns the VertexBuffer total size (integer).
  25910. */
  25911. VertexBuffer.prototype.getSize = function () {
  25912. return this._size;
  25913. };
  25914. /**
  25915. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25916. */
  25917. VertexBuffer.prototype.getIsInstanced = function () {
  25918. return this._instanced;
  25919. };
  25920. /**
  25921. * Returns the instancing divisor, zero for non-instanced (integer).
  25922. */
  25923. VertexBuffer.prototype.getInstanceDivisor = function () {
  25924. return this._instanceDivisor;
  25925. };
  25926. // Methods
  25927. /**
  25928. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25929. * Returns the created WebGLBuffer.
  25930. */
  25931. VertexBuffer.prototype.create = function (data) {
  25932. return this._buffer.create(data);
  25933. };
  25934. /**
  25935. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25936. * This function will create a new buffer if the current one is not updatable
  25937. * Returns the updated WebGLBuffer.
  25938. */
  25939. VertexBuffer.prototype.update = function (data) {
  25940. return this._buffer.update(data);
  25941. };
  25942. /**
  25943. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25944. * Returns the directly updated WebGLBuffer.
  25945. */
  25946. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25947. return this._buffer.updateDirectly(data, offset);
  25948. };
  25949. /**
  25950. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25951. */
  25952. VertexBuffer.prototype.dispose = function () {
  25953. if (this._ownsBuffer) {
  25954. this._buffer.dispose();
  25955. }
  25956. };
  25957. Object.defineProperty(VertexBuffer, "PositionKind", {
  25958. get: function () {
  25959. return VertexBuffer._PositionKind;
  25960. },
  25961. enumerable: true,
  25962. configurable: true
  25963. });
  25964. Object.defineProperty(VertexBuffer, "NormalKind", {
  25965. get: function () {
  25966. return VertexBuffer._NormalKind;
  25967. },
  25968. enumerable: true,
  25969. configurable: true
  25970. });
  25971. Object.defineProperty(VertexBuffer, "TangentKind", {
  25972. get: function () {
  25973. return VertexBuffer._TangentKind;
  25974. },
  25975. enumerable: true,
  25976. configurable: true
  25977. });
  25978. Object.defineProperty(VertexBuffer, "UVKind", {
  25979. get: function () {
  25980. return VertexBuffer._UVKind;
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25986. get: function () {
  25987. return VertexBuffer._UV2Kind;
  25988. },
  25989. enumerable: true,
  25990. configurable: true
  25991. });
  25992. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25993. get: function () {
  25994. return VertexBuffer._UV3Kind;
  25995. },
  25996. enumerable: true,
  25997. configurable: true
  25998. });
  25999. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26000. get: function () {
  26001. return VertexBuffer._UV4Kind;
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26007. get: function () {
  26008. return VertexBuffer._UV5Kind;
  26009. },
  26010. enumerable: true,
  26011. configurable: true
  26012. });
  26013. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26014. get: function () {
  26015. return VertexBuffer._UV6Kind;
  26016. },
  26017. enumerable: true,
  26018. configurable: true
  26019. });
  26020. Object.defineProperty(VertexBuffer, "ColorKind", {
  26021. get: function () {
  26022. return VertexBuffer._ColorKind;
  26023. },
  26024. enumerable: true,
  26025. configurable: true
  26026. });
  26027. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26028. get: function () {
  26029. return VertexBuffer._MatricesIndicesKind;
  26030. },
  26031. enumerable: true,
  26032. configurable: true
  26033. });
  26034. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26035. get: function () {
  26036. return VertexBuffer._MatricesWeightsKind;
  26037. },
  26038. enumerable: true,
  26039. configurable: true
  26040. });
  26041. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26042. get: function () {
  26043. return VertexBuffer._MatricesIndicesExtraKind;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26049. get: function () {
  26050. return VertexBuffer._MatricesWeightsExtraKind;
  26051. },
  26052. enumerable: true,
  26053. configurable: true
  26054. });
  26055. /**
  26056. * Deduces the stride given a kind.
  26057. * @param kind The kind string to deduce
  26058. * @returns The deduced stride
  26059. */
  26060. VertexBuffer.DeduceStride = function (kind) {
  26061. switch (kind) {
  26062. case VertexBuffer.UVKind:
  26063. case VertexBuffer.UV2Kind:
  26064. case VertexBuffer.UV3Kind:
  26065. case VertexBuffer.UV4Kind:
  26066. case VertexBuffer.UV5Kind:
  26067. case VertexBuffer.UV6Kind:
  26068. return 2;
  26069. case VertexBuffer.NormalKind:
  26070. case VertexBuffer.PositionKind:
  26071. return 3;
  26072. case VertexBuffer.ColorKind:
  26073. case VertexBuffer.MatricesIndicesKind:
  26074. case VertexBuffer.MatricesIndicesExtraKind:
  26075. case VertexBuffer.MatricesWeightsKind:
  26076. case VertexBuffer.MatricesWeightsExtraKind:
  26077. case VertexBuffer.TangentKind:
  26078. return 4;
  26079. default:
  26080. throw new Error("Invalid kind '" + kind + "'");
  26081. }
  26082. };
  26083. // Enums
  26084. VertexBuffer._PositionKind = "position";
  26085. VertexBuffer._NormalKind = "normal";
  26086. VertexBuffer._TangentKind = "tangent";
  26087. VertexBuffer._UVKind = "uv";
  26088. VertexBuffer._UV2Kind = "uv2";
  26089. VertexBuffer._UV3Kind = "uv3";
  26090. VertexBuffer._UV4Kind = "uv4";
  26091. VertexBuffer._UV5Kind = "uv5";
  26092. VertexBuffer._UV6Kind = "uv6";
  26093. VertexBuffer._ColorKind = "color";
  26094. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26095. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26096. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26097. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26098. return VertexBuffer;
  26099. }());
  26100. BABYLON.VertexBuffer = VertexBuffer;
  26101. })(BABYLON || (BABYLON = {}));
  26102. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26103. var BABYLON;
  26104. (function (BABYLON) {
  26105. /**
  26106. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26107. */
  26108. var DummyInternalTextureTracker = /** @class */ (function () {
  26109. function DummyInternalTextureTracker() {
  26110. /**
  26111. * Gets or set the previous tracker in the list
  26112. */
  26113. this.previous = null;
  26114. /**
  26115. * Gets or set the next tracker in the list
  26116. */
  26117. this.next = null;
  26118. }
  26119. return DummyInternalTextureTracker;
  26120. }());
  26121. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26122. })(BABYLON || (BABYLON = {}));
  26123. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26124. var BABYLON;
  26125. (function (BABYLON) {
  26126. /**
  26127. * Class used to store data associated with WebGL texture data for the engine
  26128. * This class should not be used directly
  26129. */
  26130. var InternalTexture = /** @class */ (function () {
  26131. /**
  26132. * Creates a new InternalTexture
  26133. * @param engine defines the engine to use
  26134. * @param dataSource defines the type of data that will be used
  26135. */
  26136. function InternalTexture(engine, dataSource) {
  26137. /**
  26138. * Observable called when the texture is loaded
  26139. */
  26140. this.onLoadedObservable = new BABYLON.Observable();
  26141. /**
  26142. * Gets or set the previous tracker in the list
  26143. */
  26144. this.previous = null;
  26145. /**
  26146. * Gets or set the next tracker in the list
  26147. */
  26148. this.next = null;
  26149. // Private
  26150. /** @ignore */
  26151. this._initialSlot = -1;
  26152. /** @ignore */
  26153. this._designatedSlot = -1;
  26154. /** @ignore */
  26155. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26156. /** @ignore */
  26157. this._comparisonFunction = 0;
  26158. /** @ignore */
  26159. this._references = 1;
  26160. this._engine = engine;
  26161. this._dataSource = dataSource;
  26162. this._webGLTexture = engine._createTexture();
  26163. }
  26164. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26165. /**
  26166. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26167. */
  26168. get: function () {
  26169. return this._dataSource;
  26170. },
  26171. enumerable: true,
  26172. configurable: true
  26173. });
  26174. /**
  26175. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26176. */
  26177. InternalTexture.prototype.incrementReferences = function () {
  26178. this._references++;
  26179. };
  26180. /**
  26181. * Change the size of the texture (not the size of the content)
  26182. * @param width defines the new width
  26183. * @param height defines the new height
  26184. * @param depth defines the new depth (1 by default)
  26185. */
  26186. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26187. if (depth === void 0) { depth = 1; }
  26188. this.width = width;
  26189. this.height = height;
  26190. this.depth = depth;
  26191. this.baseWidth = width;
  26192. this.baseHeight = height;
  26193. this.baseDepth = depth;
  26194. this._size = width * height * depth;
  26195. };
  26196. /** @ignore */
  26197. InternalTexture.prototype._rebuild = function () {
  26198. var _this = this;
  26199. var proxy;
  26200. this.isReady = false;
  26201. this._cachedCoordinatesMode = null;
  26202. this._cachedWrapU = null;
  26203. this._cachedWrapV = null;
  26204. this._cachedAnisotropicFilteringLevel = null;
  26205. switch (this._dataSource) {
  26206. case InternalTexture.DATASOURCE_TEMP:
  26207. return;
  26208. case InternalTexture.DATASOURCE_URL:
  26209. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26210. _this.isReady = true;
  26211. }, null, this._buffer, undefined, this.format);
  26212. proxy._swapAndDie(this);
  26213. return;
  26214. case InternalTexture.DATASOURCE_RAW:
  26215. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26216. proxy._swapAndDie(this);
  26217. this.isReady = true;
  26218. return;
  26219. case InternalTexture.DATASOURCE_RAW3D:
  26220. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26221. proxy._swapAndDie(this);
  26222. this.isReady = true;
  26223. return;
  26224. case InternalTexture.DATASOURCE_DYNAMIC:
  26225. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26226. proxy._swapAndDie(this);
  26227. // The engine will make sure to update content so no need to flag it as isReady = true
  26228. return;
  26229. case InternalTexture.DATASOURCE_RENDERTARGET:
  26230. var options = new BABYLON.RenderTargetCreationOptions();
  26231. options.generateDepthBuffer = this._generateDepthBuffer;
  26232. options.generateMipMaps = this.generateMipMaps;
  26233. options.generateStencilBuffer = this._generateStencilBuffer;
  26234. options.samplingMode = this.samplingMode;
  26235. options.type = this.type;
  26236. if (this.isCube) {
  26237. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26238. }
  26239. else {
  26240. var size = {
  26241. width: this.width,
  26242. height: this.height
  26243. };
  26244. proxy = this._engine.createRenderTargetTexture(size, options);
  26245. }
  26246. proxy._swapAndDie(this);
  26247. this.isReady = true;
  26248. return;
  26249. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26250. var depthTextureOptions = {
  26251. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26252. comparisonFunction: this._comparisonFunction,
  26253. generateStencil: this._generateStencilBuffer,
  26254. };
  26255. if (this.isCube) {
  26256. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26257. }
  26258. else {
  26259. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26260. }
  26261. proxy._swapAndDie(this);
  26262. this.isReady = true;
  26263. return;
  26264. case InternalTexture.DATASOURCE_CUBE:
  26265. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26266. _this.isReady = true;
  26267. }, null, this.format, this._extension);
  26268. proxy._swapAndDie(this);
  26269. return;
  26270. case InternalTexture.DATASOURCE_CUBERAW:
  26271. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26272. proxy._swapAndDie(this);
  26273. this.isReady = true;
  26274. return;
  26275. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26276. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26277. if (proxy) {
  26278. proxy._swapAndDie(_this);
  26279. }
  26280. _this.isReady = true;
  26281. }, null, this.format, this._extension);
  26282. return;
  26283. }
  26284. };
  26285. InternalTexture.prototype._swapAndDie = function (target) {
  26286. target._webGLTexture = this._webGLTexture;
  26287. if (this._framebuffer) {
  26288. target._framebuffer = this._framebuffer;
  26289. }
  26290. if (this._depthStencilBuffer) {
  26291. target._depthStencilBuffer = this._depthStencilBuffer;
  26292. }
  26293. if (this._lodTextureHigh) {
  26294. if (target._lodTextureHigh) {
  26295. target._lodTextureHigh.dispose();
  26296. }
  26297. target._lodTextureHigh = this._lodTextureHigh;
  26298. }
  26299. if (this._lodTextureMid) {
  26300. if (target._lodTextureMid) {
  26301. target._lodTextureMid.dispose();
  26302. }
  26303. target._lodTextureMid = this._lodTextureMid;
  26304. }
  26305. if (this._lodTextureLow) {
  26306. if (target._lodTextureLow) {
  26307. target._lodTextureLow.dispose();
  26308. }
  26309. target._lodTextureLow = this._lodTextureLow;
  26310. }
  26311. var cache = this._engine.getLoadedTexturesCache();
  26312. var index = cache.indexOf(this);
  26313. if (index !== -1) {
  26314. cache.splice(index, 1);
  26315. }
  26316. };
  26317. /**
  26318. * Dispose the current allocated resources
  26319. */
  26320. InternalTexture.prototype.dispose = function () {
  26321. if (!this._webGLTexture) {
  26322. return;
  26323. }
  26324. this._references--;
  26325. if (this._references === 0) {
  26326. this._engine._releaseTexture(this);
  26327. this._webGLTexture = null;
  26328. this.previous = null;
  26329. this.next = null;
  26330. }
  26331. };
  26332. /**
  26333. * The source of the texture data is unknown
  26334. */
  26335. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26336. /**
  26337. * Texture data comes from an URL
  26338. */
  26339. InternalTexture.DATASOURCE_URL = 1;
  26340. /**
  26341. * Texture data is only used for temporary storage
  26342. */
  26343. InternalTexture.DATASOURCE_TEMP = 2;
  26344. /**
  26345. * Texture data comes from raw data (ArrayBuffer)
  26346. */
  26347. InternalTexture.DATASOURCE_RAW = 3;
  26348. /**
  26349. * Texture content is dynamic (video or dynamic texture)
  26350. */
  26351. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26352. /**
  26353. * Texture content is generated by rendering to it
  26354. */
  26355. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26356. /**
  26357. * Texture content is part of a multi render target process
  26358. */
  26359. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26360. /**
  26361. * Texture data comes from a cube data file
  26362. */
  26363. InternalTexture.DATASOURCE_CUBE = 7;
  26364. /**
  26365. * Texture data comes from a raw cube data
  26366. */
  26367. InternalTexture.DATASOURCE_CUBERAW = 8;
  26368. /**
  26369. * Texture data come from a prefiltered cube data file
  26370. */
  26371. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26372. /**
  26373. * Texture content is raw 3D data
  26374. */
  26375. InternalTexture.DATASOURCE_RAW3D = 10;
  26376. /**
  26377. * Texture content is a depth texture
  26378. */
  26379. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26380. return InternalTexture;
  26381. }());
  26382. BABYLON.InternalTexture = InternalTexture;
  26383. })(BABYLON || (BABYLON = {}));
  26384. //# sourceMappingURL=babylon.internalTexture.js.map
  26385. var BABYLON;
  26386. (function (BABYLON) {
  26387. var BaseTexture = /** @class */ (function () {
  26388. function BaseTexture(scene) {
  26389. this._hasAlpha = false;
  26390. this.getAlphaFromRGB = false;
  26391. this.level = 1;
  26392. this.coordinatesIndex = 0;
  26393. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26394. /**
  26395. * | Value | Type | Description |
  26396. * | ----- | ------------------ | ----------- |
  26397. * | 0 | CLAMP_ADDRESSMODE | |
  26398. * | 1 | WRAP_ADDRESSMODE | |
  26399. * | 2 | MIRROR_ADDRESSMODE | |
  26400. */
  26401. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26402. /**
  26403. * | Value | Type | Description |
  26404. * | ----- | ------------------ | ----------- |
  26405. * | 0 | CLAMP_ADDRESSMODE | |
  26406. * | 1 | WRAP_ADDRESSMODE | |
  26407. * | 2 | MIRROR_ADDRESSMODE | |
  26408. */
  26409. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26410. /**
  26411. * | Value | Type | Description |
  26412. * | ----- | ------------------ | ----------- |
  26413. * | 0 | CLAMP_ADDRESSMODE | |
  26414. * | 1 | WRAP_ADDRESSMODE | |
  26415. * | 2 | MIRROR_ADDRESSMODE | |
  26416. */
  26417. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26418. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26419. this.isCube = false;
  26420. this.is3D = false;
  26421. this.gammaSpace = true;
  26422. this.invertZ = false;
  26423. this.lodLevelInAlpha = false;
  26424. this.lodGenerationOffset = 0.0;
  26425. this.lodGenerationScale = 0.8;
  26426. this.isRenderTarget = false;
  26427. this.animations = new Array();
  26428. /**
  26429. * An event triggered when the texture is disposed.
  26430. * @type {BABYLON.Observable}
  26431. */
  26432. this.onDisposeObservable = new BABYLON.Observable();
  26433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26435. if (this._scene) {
  26436. this._scene.textures.push(this);
  26437. }
  26438. this._uid = null;
  26439. }
  26440. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26441. get: function () {
  26442. return this._hasAlpha;
  26443. },
  26444. set: function (value) {
  26445. if (this._hasAlpha === value) {
  26446. return;
  26447. }
  26448. this._hasAlpha = value;
  26449. if (this._scene) {
  26450. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26451. }
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26457. get: function () {
  26458. return this._coordinatesMode;
  26459. },
  26460. /**
  26461. * How a texture is mapped.
  26462. *
  26463. * | Value | Type | Description |
  26464. * | ----- | ----------------------------------- | ----------- |
  26465. * | 0 | EXPLICIT_MODE | |
  26466. * | 1 | SPHERICAL_MODE | |
  26467. * | 2 | PLANAR_MODE | |
  26468. * | 3 | CUBIC_MODE | |
  26469. * | 4 | PROJECTION_MODE | |
  26470. * | 5 | SKYBOX_MODE | |
  26471. * | 6 | INVCUBIC_MODE | |
  26472. * | 7 | EQUIRECTANGULAR_MODE | |
  26473. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26474. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26475. */
  26476. set: function (value) {
  26477. if (this._coordinatesMode === value) {
  26478. return;
  26479. }
  26480. this._coordinatesMode = value;
  26481. if (this._scene) {
  26482. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26483. }
  26484. },
  26485. enumerable: true,
  26486. configurable: true
  26487. });
  26488. Object.defineProperty(BaseTexture.prototype, "uid", {
  26489. get: function () {
  26490. if (!this._uid) {
  26491. this._uid = BABYLON.Tools.RandomId();
  26492. }
  26493. return this._uid;
  26494. },
  26495. enumerable: true,
  26496. configurable: true
  26497. });
  26498. BaseTexture.prototype.toString = function () {
  26499. return this.name;
  26500. };
  26501. BaseTexture.prototype.getClassName = function () {
  26502. return "BaseTexture";
  26503. };
  26504. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26505. set: function (callback) {
  26506. if (this._onDisposeObserver) {
  26507. this.onDisposeObservable.remove(this._onDisposeObserver);
  26508. }
  26509. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26510. },
  26511. enumerable: true,
  26512. configurable: true
  26513. });
  26514. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26515. get: function () {
  26516. return true;
  26517. },
  26518. enumerable: true,
  26519. configurable: true
  26520. });
  26521. BaseTexture.prototype.getScene = function () {
  26522. return this._scene;
  26523. };
  26524. BaseTexture.prototype.getTextureMatrix = function () {
  26525. return BABYLON.Matrix.IdentityReadOnly;
  26526. };
  26527. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26528. return BABYLON.Matrix.IdentityReadOnly;
  26529. };
  26530. BaseTexture.prototype.getInternalTexture = function () {
  26531. return this._texture;
  26532. };
  26533. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26534. return !this.isBlocking || this.isReady();
  26535. };
  26536. BaseTexture.prototype.isReady = function () {
  26537. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26538. this.delayLoad();
  26539. return false;
  26540. }
  26541. if (this._texture) {
  26542. return this._texture.isReady;
  26543. }
  26544. return false;
  26545. };
  26546. BaseTexture.prototype.getSize = function () {
  26547. if (this._texture && this._texture.width) {
  26548. return new BABYLON.Size(this._texture.width, this._texture.height);
  26549. }
  26550. if (this._texture && this._texture._size) {
  26551. return new BABYLON.Size(this._texture._size, this._texture._size);
  26552. }
  26553. return BABYLON.Size.Zero();
  26554. };
  26555. BaseTexture.prototype.getBaseSize = function () {
  26556. if (!this.isReady() || !this._texture)
  26557. return BABYLON.Size.Zero();
  26558. if (this._texture._size) {
  26559. return new BABYLON.Size(this._texture._size, this._texture._size);
  26560. }
  26561. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26562. };
  26563. BaseTexture.prototype.scale = function (ratio) {
  26564. };
  26565. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26566. get: function () {
  26567. return false;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26573. if (!this._scene) {
  26574. return null;
  26575. }
  26576. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26577. for (var index = 0; index < texturesCache.length; index++) {
  26578. var texturesCacheEntry = texturesCache[index];
  26579. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26580. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26581. texturesCacheEntry.incrementReferences();
  26582. return texturesCacheEntry;
  26583. }
  26584. }
  26585. }
  26586. return null;
  26587. };
  26588. BaseTexture.prototype._rebuild = function () {
  26589. };
  26590. BaseTexture.prototype.delayLoad = function () {
  26591. };
  26592. BaseTexture.prototype.clone = function () {
  26593. return null;
  26594. };
  26595. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26596. get: function () {
  26597. if (!this._texture) {
  26598. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26599. }
  26600. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26606. get: function () {
  26607. if (!this._texture) {
  26608. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26609. }
  26610. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26611. },
  26612. enumerable: true,
  26613. configurable: true
  26614. });
  26615. BaseTexture.prototype.readPixels = function (faceIndex) {
  26616. if (faceIndex === void 0) { faceIndex = 0; }
  26617. if (!this._texture) {
  26618. return null;
  26619. }
  26620. var size = this.getSize();
  26621. var scene = this.getScene();
  26622. if (!scene) {
  26623. return null;
  26624. }
  26625. var engine = scene.getEngine();
  26626. if (this._texture.isCube) {
  26627. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26628. }
  26629. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26630. };
  26631. BaseTexture.prototype.releaseInternalTexture = function () {
  26632. if (this._texture) {
  26633. this._texture.dispose();
  26634. this._texture = null;
  26635. }
  26636. };
  26637. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26638. get: function () {
  26639. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26640. return null;
  26641. }
  26642. if (!this._texture._sphericalPolynomial) {
  26643. this._texture._sphericalPolynomial =
  26644. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26645. }
  26646. return this._texture._sphericalPolynomial;
  26647. },
  26648. set: function (value) {
  26649. if (this._texture) {
  26650. this._texture._sphericalPolynomial = value;
  26651. }
  26652. },
  26653. enumerable: true,
  26654. configurable: true
  26655. });
  26656. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26657. get: function () {
  26658. if (this._texture) {
  26659. return this._texture._lodTextureHigh;
  26660. }
  26661. return null;
  26662. },
  26663. enumerable: true,
  26664. configurable: true
  26665. });
  26666. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26667. get: function () {
  26668. if (this._texture) {
  26669. return this._texture._lodTextureMid;
  26670. }
  26671. return null;
  26672. },
  26673. enumerable: true,
  26674. configurable: true
  26675. });
  26676. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26677. get: function () {
  26678. if (this._texture) {
  26679. return this._texture._lodTextureLow;
  26680. }
  26681. return null;
  26682. },
  26683. enumerable: true,
  26684. configurable: true
  26685. });
  26686. BaseTexture.prototype.dispose = function () {
  26687. if (!this._scene) {
  26688. return;
  26689. }
  26690. // Animations
  26691. this._scene.stopAnimation(this);
  26692. // Remove from scene
  26693. this._scene._removePendingData(this);
  26694. var index = this._scene.textures.indexOf(this);
  26695. if (index >= 0) {
  26696. this._scene.textures.splice(index, 1);
  26697. }
  26698. if (this._texture === undefined) {
  26699. return;
  26700. }
  26701. // Release
  26702. this.releaseInternalTexture();
  26703. // Callback
  26704. this.onDisposeObservable.notifyObservers(this);
  26705. this.onDisposeObservable.clear();
  26706. };
  26707. BaseTexture.prototype.serialize = function () {
  26708. if (!this.name) {
  26709. return null;
  26710. }
  26711. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26712. // Animations
  26713. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26714. return serializationObject;
  26715. };
  26716. BaseTexture.WhenAllReady = function (textures, callback) {
  26717. var numRemaining = textures.length;
  26718. if (numRemaining === 0) {
  26719. callback();
  26720. return;
  26721. }
  26722. var _loop_1 = function () {
  26723. texture = textures[i];
  26724. if (texture.isReady()) {
  26725. if (--numRemaining === 0) {
  26726. callback();
  26727. }
  26728. }
  26729. else {
  26730. onLoadObservable = texture.onLoadObservable;
  26731. var onLoadCallback_1 = function () {
  26732. onLoadObservable.removeCallback(onLoadCallback_1);
  26733. if (--numRemaining === 0) {
  26734. callback();
  26735. }
  26736. };
  26737. onLoadObservable.add(onLoadCallback_1);
  26738. }
  26739. };
  26740. var texture, onLoadObservable;
  26741. for (var i = 0; i < textures.length; i++) {
  26742. _loop_1();
  26743. }
  26744. };
  26745. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26746. __decorate([
  26747. BABYLON.serialize()
  26748. ], BaseTexture.prototype, "name", void 0);
  26749. __decorate([
  26750. BABYLON.serialize("hasAlpha")
  26751. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26752. __decorate([
  26753. BABYLON.serialize()
  26754. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26755. __decorate([
  26756. BABYLON.serialize()
  26757. ], BaseTexture.prototype, "level", void 0);
  26758. __decorate([
  26759. BABYLON.serialize()
  26760. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26761. __decorate([
  26762. BABYLON.serialize("coordinatesMode")
  26763. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26764. __decorate([
  26765. BABYLON.serialize()
  26766. ], BaseTexture.prototype, "wrapU", void 0);
  26767. __decorate([
  26768. BABYLON.serialize()
  26769. ], BaseTexture.prototype, "wrapV", void 0);
  26770. __decorate([
  26771. BABYLON.serialize()
  26772. ], BaseTexture.prototype, "wrapR", void 0);
  26773. __decorate([
  26774. BABYLON.serialize()
  26775. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26776. __decorate([
  26777. BABYLON.serialize()
  26778. ], BaseTexture.prototype, "isCube", void 0);
  26779. __decorate([
  26780. BABYLON.serialize()
  26781. ], BaseTexture.prototype, "is3D", void 0);
  26782. __decorate([
  26783. BABYLON.serialize()
  26784. ], BaseTexture.prototype, "gammaSpace", void 0);
  26785. __decorate([
  26786. BABYLON.serialize()
  26787. ], BaseTexture.prototype, "invertZ", void 0);
  26788. __decorate([
  26789. BABYLON.serialize()
  26790. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26791. __decorate([
  26792. BABYLON.serialize()
  26793. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26794. __decorate([
  26795. BABYLON.serialize()
  26796. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26797. __decorate([
  26798. BABYLON.serialize()
  26799. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26800. return BaseTexture;
  26801. }());
  26802. BABYLON.BaseTexture = BaseTexture;
  26803. })(BABYLON || (BABYLON = {}));
  26804. //# sourceMappingURL=babylon.baseTexture.js.map
  26805. var BABYLON;
  26806. (function (BABYLON) {
  26807. var Texture = /** @class */ (function (_super) {
  26808. __extends(Texture, _super);
  26809. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26810. if (noMipmap === void 0) { noMipmap = false; }
  26811. if (invertY === void 0) { invertY = true; }
  26812. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26813. if (onLoad === void 0) { onLoad = null; }
  26814. if (onError === void 0) { onError = null; }
  26815. if (buffer === void 0) { buffer = null; }
  26816. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26817. var _this = _super.call(this, scene) || this;
  26818. _this.uOffset = 0;
  26819. _this.vOffset = 0;
  26820. _this.uScale = 1.0;
  26821. _this.vScale = 1.0;
  26822. _this.uAng = 0;
  26823. _this.vAng = 0;
  26824. _this.wAng = 0;
  26825. _this._isBlocking = true;
  26826. _this.name = url || "";
  26827. _this.url = url;
  26828. _this._noMipmap = noMipmap;
  26829. _this._invertY = invertY;
  26830. _this._samplingMode = samplingMode;
  26831. _this._buffer = buffer;
  26832. _this._deleteBuffer = deleteBuffer;
  26833. if (format) {
  26834. _this._format = format;
  26835. }
  26836. scene = _this.getScene();
  26837. if (!scene) {
  26838. return _this;
  26839. }
  26840. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26841. var load = function () {
  26842. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26843. _this.onLoadObservable.notifyObservers(_this);
  26844. }
  26845. if (onLoad) {
  26846. onLoad();
  26847. }
  26848. if (!_this.isBlocking && scene) {
  26849. scene.resetCachedMaterial();
  26850. }
  26851. };
  26852. if (!_this.url) {
  26853. _this._delayedOnLoad = load;
  26854. _this._delayedOnError = onError;
  26855. return _this;
  26856. }
  26857. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26858. if (!_this._texture) {
  26859. if (!scene.useDelayedTextureLoading) {
  26860. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26861. if (deleteBuffer) {
  26862. delete _this._buffer;
  26863. }
  26864. }
  26865. else {
  26866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26867. _this._delayedOnLoad = load;
  26868. _this._delayedOnError = onError;
  26869. }
  26870. }
  26871. else {
  26872. if (_this._texture.isReady) {
  26873. BABYLON.Tools.SetImmediate(function () { return load(); });
  26874. }
  26875. else {
  26876. _this._texture.onLoadedObservable.add(load);
  26877. }
  26878. }
  26879. return _this;
  26880. }
  26881. Object.defineProperty(Texture.prototype, "noMipmap", {
  26882. get: function () {
  26883. return this._noMipmap;
  26884. },
  26885. enumerable: true,
  26886. configurable: true
  26887. });
  26888. Object.defineProperty(Texture.prototype, "isBlocking", {
  26889. get: function () {
  26890. return this._isBlocking;
  26891. },
  26892. set: function (value) {
  26893. this._isBlocking = value;
  26894. },
  26895. enumerable: true,
  26896. configurable: true
  26897. });
  26898. Object.defineProperty(Texture.prototype, "samplingMode", {
  26899. get: function () {
  26900. return this._samplingMode;
  26901. },
  26902. enumerable: true,
  26903. configurable: true
  26904. });
  26905. Texture.prototype.updateURL = function (url) {
  26906. this.url = url;
  26907. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26908. this.delayLoad();
  26909. };
  26910. Texture.prototype.delayLoad = function () {
  26911. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26912. return;
  26913. }
  26914. var scene = this.getScene();
  26915. if (!scene) {
  26916. return;
  26917. }
  26918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26919. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26920. if (!this._texture) {
  26921. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26922. if (this._deleteBuffer) {
  26923. delete this._buffer;
  26924. }
  26925. }
  26926. else {
  26927. if (this._delayedOnLoad) {
  26928. if (this._texture.isReady) {
  26929. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26930. }
  26931. else {
  26932. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26933. }
  26934. }
  26935. }
  26936. this._delayedOnLoad = null;
  26937. this._delayedOnError = null;
  26938. };
  26939. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26940. if (!this._texture) {
  26941. return;
  26942. }
  26943. var scene = this.getScene();
  26944. if (!scene) {
  26945. return;
  26946. }
  26947. this._samplingMode = samplingMode;
  26948. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26949. };
  26950. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26951. x *= this.uScale;
  26952. y *= this.vScale;
  26953. x -= 0.5 * this.uScale;
  26954. y -= 0.5 * this.vScale;
  26955. z -= 0.5;
  26956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26957. t.x += 0.5 * this.uScale + this.uOffset;
  26958. t.y += 0.5 * this.vScale + this.vOffset;
  26959. t.z += 0.5;
  26960. };
  26961. Texture.prototype.getTextureMatrix = function () {
  26962. var _this = this;
  26963. if (this.uOffset === this._cachedUOffset &&
  26964. this.vOffset === this._cachedVOffset &&
  26965. this.uScale === this._cachedUScale &&
  26966. this.vScale === this._cachedVScale &&
  26967. this.uAng === this._cachedUAng &&
  26968. this.vAng === this._cachedVAng &&
  26969. this.wAng === this._cachedWAng) {
  26970. return this._cachedTextureMatrix;
  26971. }
  26972. this._cachedUOffset = this.uOffset;
  26973. this._cachedVOffset = this.vOffset;
  26974. this._cachedUScale = this.uScale;
  26975. this._cachedVScale = this.vScale;
  26976. this._cachedUAng = this.uAng;
  26977. this._cachedVAng = this.vAng;
  26978. this._cachedWAng = this.wAng;
  26979. if (!this._cachedTextureMatrix) {
  26980. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26981. this._rowGenerationMatrix = new BABYLON.Matrix();
  26982. this._t0 = BABYLON.Vector3.Zero();
  26983. this._t1 = BABYLON.Vector3.Zero();
  26984. this._t2 = BABYLON.Vector3.Zero();
  26985. }
  26986. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26987. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26988. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26989. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26990. this._t1.subtractInPlace(this._t0);
  26991. this._t2.subtractInPlace(this._t0);
  26992. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26993. this._cachedTextureMatrix.m[0] = this._t1.x;
  26994. this._cachedTextureMatrix.m[1] = this._t1.y;
  26995. this._cachedTextureMatrix.m[2] = this._t1.z;
  26996. this._cachedTextureMatrix.m[4] = this._t2.x;
  26997. this._cachedTextureMatrix.m[5] = this._t2.y;
  26998. this._cachedTextureMatrix.m[6] = this._t2.z;
  26999. this._cachedTextureMatrix.m[8] = this._t0.x;
  27000. this._cachedTextureMatrix.m[9] = this._t0.y;
  27001. this._cachedTextureMatrix.m[10] = this._t0.z;
  27002. var scene = this.getScene();
  27003. if (!scene) {
  27004. return this._cachedTextureMatrix;
  27005. }
  27006. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27007. return mat.hasTexture(_this);
  27008. });
  27009. return this._cachedTextureMatrix;
  27010. };
  27011. Texture.prototype.getReflectionTextureMatrix = function () {
  27012. var _this = this;
  27013. var scene = this.getScene();
  27014. if (!scene) {
  27015. return this._cachedTextureMatrix;
  27016. }
  27017. if (this.uOffset === this._cachedUOffset &&
  27018. this.vOffset === this._cachedVOffset &&
  27019. this.uScale === this._cachedUScale &&
  27020. this.vScale === this._cachedVScale &&
  27021. this.coordinatesMode === this._cachedCoordinatesMode) {
  27022. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27023. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27024. return this._cachedTextureMatrix;
  27025. }
  27026. }
  27027. else {
  27028. return this._cachedTextureMatrix;
  27029. }
  27030. }
  27031. if (!this._cachedTextureMatrix) {
  27032. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27033. }
  27034. if (!this._projectionModeMatrix) {
  27035. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27036. }
  27037. this._cachedUOffset = this.uOffset;
  27038. this._cachedVOffset = this.vOffset;
  27039. this._cachedUScale = this.uScale;
  27040. this._cachedVScale = this.vScale;
  27041. this._cachedCoordinatesMode = this.coordinatesMode;
  27042. switch (this.coordinatesMode) {
  27043. case Texture.PLANAR_MODE:
  27044. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27045. this._cachedTextureMatrix[0] = this.uScale;
  27046. this._cachedTextureMatrix[5] = this.vScale;
  27047. this._cachedTextureMatrix[12] = this.uOffset;
  27048. this._cachedTextureMatrix[13] = this.vOffset;
  27049. break;
  27050. case Texture.PROJECTION_MODE:
  27051. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27052. this._projectionModeMatrix.m[0] = 0.5;
  27053. this._projectionModeMatrix.m[5] = -0.5;
  27054. this._projectionModeMatrix.m[10] = 0.0;
  27055. this._projectionModeMatrix.m[12] = 0.5;
  27056. this._projectionModeMatrix.m[13] = 0.5;
  27057. this._projectionModeMatrix.m[14] = 1.0;
  27058. this._projectionModeMatrix.m[15] = 1.0;
  27059. var projectionMatrix = scene.getProjectionMatrix();
  27060. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27061. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27062. break;
  27063. default:
  27064. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27065. break;
  27066. }
  27067. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27068. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27069. });
  27070. return this._cachedTextureMatrix;
  27071. };
  27072. Texture.prototype.clone = function () {
  27073. var _this = this;
  27074. return BABYLON.SerializationHelper.Clone(function () {
  27075. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27076. }, this);
  27077. };
  27078. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27079. get: function () {
  27080. if (!this._onLoadObservable) {
  27081. this._onLoadObservable = new BABYLON.Observable();
  27082. }
  27083. return this._onLoadObservable;
  27084. },
  27085. enumerable: true,
  27086. configurable: true
  27087. });
  27088. Texture.prototype.serialize = function () {
  27089. var serializationObject = _super.prototype.serialize.call(this);
  27090. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27091. serializationObject.base64String = this._buffer;
  27092. serializationObject.name = serializationObject.name.replace("data:", "");
  27093. }
  27094. return serializationObject;
  27095. };
  27096. Texture.prototype.getClassName = function () {
  27097. return "Texture";
  27098. };
  27099. Texture.prototype.dispose = function () {
  27100. _super.prototype.dispose.call(this);
  27101. if (this.onLoadObservable) {
  27102. this.onLoadObservable.clear();
  27103. this._onLoadObservable = null;
  27104. }
  27105. this._delayedOnLoad = null;
  27106. this._delayedOnError = null;
  27107. };
  27108. // Statics
  27109. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27110. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27111. if (onLoad === void 0) { onLoad = null; }
  27112. if (onError === void 0) { onError = null; }
  27113. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27114. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27115. };
  27116. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27117. if (parsedTexture.customType) {
  27118. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27119. // Update Sampling Mode
  27120. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27121. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27122. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27123. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27124. }
  27125. }
  27126. return parsedCustomTexture;
  27127. }
  27128. if (parsedTexture.isCube) {
  27129. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27130. }
  27131. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27132. return null;
  27133. }
  27134. var texture = BABYLON.SerializationHelper.Parse(function () {
  27135. var generateMipMaps = true;
  27136. if (parsedTexture.noMipmap) {
  27137. generateMipMaps = false;
  27138. }
  27139. if (parsedTexture.mirrorPlane) {
  27140. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27141. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27142. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27143. return mirrorTexture;
  27144. }
  27145. else if (parsedTexture.isRenderTarget) {
  27146. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27147. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27148. return renderTargetTexture;
  27149. }
  27150. else {
  27151. var texture;
  27152. if (parsedTexture.base64String) {
  27153. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27154. }
  27155. else {
  27156. var url = rootUrl + parsedTexture.name;
  27157. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27158. url = parsedTexture.url;
  27159. }
  27160. texture = new Texture(url, scene, !generateMipMaps);
  27161. }
  27162. return texture;
  27163. }
  27164. }, parsedTexture, scene);
  27165. // Update Sampling Mode
  27166. if (parsedTexture.samplingMode) {
  27167. var sampling = parsedTexture.samplingMode;
  27168. if (texture._samplingMode !== sampling) {
  27169. texture.updateSamplingMode(sampling);
  27170. }
  27171. }
  27172. // Animations
  27173. if (parsedTexture.animations) {
  27174. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27175. var parsedAnimation = parsedTexture.animations[animationIndex];
  27176. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27177. }
  27178. }
  27179. return texture;
  27180. };
  27181. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27182. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27183. if (noMipmap === void 0) { noMipmap = false; }
  27184. if (invertY === void 0) { invertY = true; }
  27185. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27186. if (onLoad === void 0) { onLoad = null; }
  27187. if (onError === void 0) { onError = null; }
  27188. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27189. if (name.substr(0, 5) !== "data:") {
  27190. name = "data:" + name;
  27191. }
  27192. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27193. };
  27194. // Constants
  27195. Texture.NEAREST_SAMPLINGMODE = 1;
  27196. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27197. Texture.BILINEAR_SAMPLINGMODE = 2;
  27198. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27199. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27200. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27201. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27202. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27203. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27204. Texture.NEAREST_LINEAR = 7;
  27205. Texture.NEAREST_NEAREST = 8;
  27206. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27207. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27208. Texture.LINEAR_LINEAR = 11;
  27209. Texture.LINEAR_NEAREST = 12;
  27210. Texture.EXPLICIT_MODE = 0;
  27211. Texture.SPHERICAL_MODE = 1;
  27212. Texture.PLANAR_MODE = 2;
  27213. Texture.CUBIC_MODE = 3;
  27214. Texture.PROJECTION_MODE = 4;
  27215. Texture.SKYBOX_MODE = 5;
  27216. Texture.INVCUBIC_MODE = 6;
  27217. Texture.EQUIRECTANGULAR_MODE = 7;
  27218. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27219. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27220. Texture.CLAMP_ADDRESSMODE = 0;
  27221. Texture.WRAP_ADDRESSMODE = 1;
  27222. Texture.MIRROR_ADDRESSMODE = 2;
  27223. /**
  27224. * 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
  27225. */
  27226. Texture.UseSerializedUrlIfAny = false;
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], Texture.prototype, "url", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], Texture.prototype, "uOffset", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], Texture.prototype, "vOffset", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], Texture.prototype, "uScale", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], Texture.prototype, "vScale", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], Texture.prototype, "uAng", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], Texture.prototype, "vAng", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], Texture.prototype, "wAng", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], Texture.prototype, "isBlocking", null);
  27254. return Texture;
  27255. }(BABYLON.BaseTexture));
  27256. BABYLON.Texture = Texture;
  27257. })(BABYLON || (BABYLON = {}));
  27258. //# sourceMappingURL=babylon.texture.js.map
  27259. var BABYLON;
  27260. (function (BABYLON) {
  27261. var _InstancesBatch = /** @class */ (function () {
  27262. function _InstancesBatch() {
  27263. this.mustReturn = false;
  27264. this.visibleInstances = new Array();
  27265. this.renderSelf = new Array();
  27266. }
  27267. return _InstancesBatch;
  27268. }());
  27269. BABYLON._InstancesBatch = _InstancesBatch;
  27270. var Mesh = /** @class */ (function (_super) {
  27271. __extends(Mesh, _super);
  27272. /**
  27273. * @constructor
  27274. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27275. * @param {Scene} scene The scene to add this mesh to.
  27276. * @param {Node} parent The parent of this mesh, if it has one
  27277. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27278. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27279. * When false, achieved by calling a clone(), also passing False.
  27280. * This will make creation of children, recursive.
  27281. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27282. */
  27283. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27284. if (scene === void 0) { scene = null; }
  27285. if (parent === void 0) { parent = null; }
  27286. if (source === void 0) { source = null; }
  27287. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27288. var _this = _super.call(this, name, scene) || this;
  27289. // Events
  27290. /**
  27291. * An event triggered before rendering the mesh
  27292. * @type {BABYLON.Observable}
  27293. */
  27294. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27295. /**
  27296. * An event triggered after rendering the mesh
  27297. * @type {BABYLON.Observable}
  27298. */
  27299. _this.onAfterRenderObservable = new BABYLON.Observable();
  27300. /**
  27301. * An event triggered before drawing the mesh
  27302. * @type {BABYLON.Observable}
  27303. */
  27304. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27305. // Members
  27306. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27307. _this.instances = new Array();
  27308. _this._LODLevels = new Array();
  27309. _this._visibleInstances = {};
  27310. _this._renderIdForInstances = new Array();
  27311. _this._batchCache = new _InstancesBatch();
  27312. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27313. // Use by builder only to know what orientation were the mesh build in.
  27314. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27315. _this.overrideMaterialSideOrientation = null;
  27316. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27317. // Will be used to save a source mesh reference, If any
  27318. _this._source = null;
  27319. scene = _this.getScene();
  27320. if (source) {
  27321. // Source mesh
  27322. _this._source = source;
  27323. // Geometry
  27324. if (source._geometry) {
  27325. source._geometry.applyToMesh(_this);
  27326. }
  27327. // Deep copy
  27328. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27329. // Metadata
  27330. if (source.metadata && source.metadata.clone) {
  27331. _this.metadata = source.metadata.clone();
  27332. }
  27333. else {
  27334. _this.metadata = source.metadata;
  27335. }
  27336. // Tags
  27337. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27338. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27339. }
  27340. // Parent
  27341. _this.parent = source.parent;
  27342. // Pivot
  27343. _this.setPivotMatrix(source.getPivotMatrix());
  27344. _this.id = name + "." + source.id;
  27345. // Material
  27346. _this.material = source.material;
  27347. var index;
  27348. if (!doNotCloneChildren) {
  27349. // Children
  27350. var directDescendants = source.getDescendants(true);
  27351. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27352. var child = directDescendants[index_1];
  27353. if (child.clone) {
  27354. child.clone(name + "." + child.name, _this);
  27355. }
  27356. }
  27357. }
  27358. // Physics clone
  27359. var physicsEngine = _this.getScene().getPhysicsEngine();
  27360. if (clonePhysicsImpostor && physicsEngine) {
  27361. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27362. if (impostor) {
  27363. _this.physicsImpostor = impostor.clone(_this);
  27364. }
  27365. }
  27366. // Particles
  27367. for (index = 0; index < scene.particleSystems.length; index++) {
  27368. var system = scene.particleSystems[index];
  27369. if (system.emitter === source) {
  27370. system.clone(system.name, _this);
  27371. }
  27372. }
  27373. _this.computeWorldMatrix(true);
  27374. }
  27375. // Parent
  27376. if (parent !== null) {
  27377. _this.parent = parent;
  27378. }
  27379. return _this;
  27380. }
  27381. Object.defineProperty(Mesh, "FRONTSIDE", {
  27382. /**
  27383. * Mesh side orientation : usually the external or front surface
  27384. */
  27385. get: function () {
  27386. return Mesh._FRONTSIDE;
  27387. },
  27388. enumerable: true,
  27389. configurable: true
  27390. });
  27391. Object.defineProperty(Mesh, "BACKSIDE", {
  27392. /**
  27393. * Mesh side orientation : usually the internal or back surface
  27394. */
  27395. get: function () {
  27396. return Mesh._BACKSIDE;
  27397. },
  27398. enumerable: true,
  27399. configurable: true
  27400. });
  27401. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27402. /**
  27403. * Mesh side orientation : both internal and external or front and back surfaces
  27404. */
  27405. get: function () {
  27406. return Mesh._DOUBLESIDE;
  27407. },
  27408. enumerable: true,
  27409. configurable: true
  27410. });
  27411. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27412. /**
  27413. * Mesh side orientation : by default, `FRONTSIDE`
  27414. */
  27415. get: function () {
  27416. return Mesh._DEFAULTSIDE;
  27417. },
  27418. enumerable: true,
  27419. configurable: true
  27420. });
  27421. Object.defineProperty(Mesh, "NO_CAP", {
  27422. /**
  27423. * Mesh cap setting : no cap
  27424. */
  27425. get: function () {
  27426. return Mesh._NO_CAP;
  27427. },
  27428. enumerable: true,
  27429. configurable: true
  27430. });
  27431. Object.defineProperty(Mesh, "CAP_START", {
  27432. /**
  27433. * Mesh cap setting : one cap at the beginning of the mesh
  27434. */
  27435. get: function () {
  27436. return Mesh._CAP_START;
  27437. },
  27438. enumerable: true,
  27439. configurable: true
  27440. });
  27441. Object.defineProperty(Mesh, "CAP_END", {
  27442. /**
  27443. * Mesh cap setting : one cap at the end of the mesh
  27444. */
  27445. get: function () {
  27446. return Mesh._CAP_END;
  27447. },
  27448. enumerable: true,
  27449. configurable: true
  27450. });
  27451. Object.defineProperty(Mesh, "CAP_ALL", {
  27452. /**
  27453. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27454. */
  27455. get: function () {
  27456. return Mesh._CAP_ALL;
  27457. },
  27458. enumerable: true,
  27459. configurable: true
  27460. });
  27461. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27462. set: function (callback) {
  27463. if (this._onBeforeDrawObserver) {
  27464. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27465. }
  27466. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27467. },
  27468. enumerable: true,
  27469. configurable: true
  27470. });
  27471. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27472. get: function () {
  27473. return this._morphTargetManager;
  27474. },
  27475. set: function (value) {
  27476. if (this._morphTargetManager === value) {
  27477. return;
  27478. }
  27479. this._morphTargetManager = value;
  27480. this._syncGeometryWithMorphTargetManager();
  27481. },
  27482. enumerable: true,
  27483. configurable: true
  27484. });
  27485. Object.defineProperty(Mesh.prototype, "source", {
  27486. get: function () {
  27487. return this._source;
  27488. },
  27489. enumerable: true,
  27490. configurable: true
  27491. });
  27492. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27493. get: function () {
  27494. return this._unIndexed;
  27495. },
  27496. set: function (value) {
  27497. if (this._unIndexed !== value) {
  27498. this._unIndexed = value;
  27499. this._markSubMeshesAsAttributesDirty();
  27500. }
  27501. },
  27502. enumerable: true,
  27503. configurable: true
  27504. });
  27505. // Methods
  27506. /**
  27507. * Returns the string "Mesh".
  27508. */
  27509. Mesh.prototype.getClassName = function () {
  27510. return "Mesh";
  27511. };
  27512. /**
  27513. * Returns a string.
  27514. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27515. */
  27516. Mesh.prototype.toString = function (fullDetails) {
  27517. var ret = _super.prototype.toString.call(this, fullDetails);
  27518. ret += ", n vertices: " + this.getTotalVertices();
  27519. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27520. if (this.animations) {
  27521. for (var i = 0; i < this.animations.length; i++) {
  27522. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27523. }
  27524. }
  27525. if (fullDetails) {
  27526. if (this._geometry) {
  27527. var ib = this.getIndices();
  27528. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27529. if (vb && ib) {
  27530. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27531. }
  27532. }
  27533. else {
  27534. ret += ", flat shading: UNKNOWN";
  27535. }
  27536. }
  27537. return ret;
  27538. };
  27539. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27540. /**
  27541. * True if the mesh has some Levels Of Details (LOD).
  27542. * Returns a boolean.
  27543. */
  27544. get: function () {
  27545. return this._LODLevels.length > 0;
  27546. },
  27547. enumerable: true,
  27548. configurable: true
  27549. });
  27550. /**
  27551. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27552. * @returns an array of {BABYLON.MeshLODLevel}
  27553. */
  27554. Mesh.prototype.getLODLevels = function () {
  27555. return this._LODLevels;
  27556. };
  27557. Mesh.prototype._sortLODLevels = function () {
  27558. this._LODLevels.sort(function (a, b) {
  27559. if (a.distance < b.distance) {
  27560. return 1;
  27561. }
  27562. if (a.distance > b.distance) {
  27563. return -1;
  27564. }
  27565. return 0;
  27566. });
  27567. };
  27568. /**
  27569. * Add a mesh as LOD level triggered at the given distance.
  27570. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27571. * @param {number} distance The distance from the center of the object to show this level
  27572. * @param {Mesh} mesh The mesh to be added as LOD level
  27573. * @return {Mesh} This mesh (for chaining)
  27574. */
  27575. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27576. if (mesh && mesh._masterMesh) {
  27577. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27578. return this;
  27579. }
  27580. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27581. this._LODLevels.push(level);
  27582. if (mesh) {
  27583. mesh._masterMesh = this;
  27584. }
  27585. this._sortLODLevels();
  27586. return this;
  27587. };
  27588. /**
  27589. * Returns the LOD level mesh at the passed distance or null if not found.
  27590. * It is related to the method `addLODLevel(distance, mesh)`.
  27591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27592. * Returns an object Mesh or `null`.
  27593. */
  27594. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27595. for (var index = 0; index < this._LODLevels.length; index++) {
  27596. var level = this._LODLevels[index];
  27597. if (level.distance === distance) {
  27598. return level.mesh;
  27599. }
  27600. }
  27601. return null;
  27602. };
  27603. /**
  27604. * Remove a mesh from the LOD array
  27605. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27606. * @param {Mesh} mesh The mesh to be removed.
  27607. * @return {Mesh} This mesh (for chaining)
  27608. */
  27609. Mesh.prototype.removeLODLevel = function (mesh) {
  27610. for (var index = 0; index < this._LODLevels.length; index++) {
  27611. if (this._LODLevels[index].mesh === mesh) {
  27612. this._LODLevels.splice(index, 1);
  27613. if (mesh) {
  27614. mesh._masterMesh = null;
  27615. }
  27616. }
  27617. }
  27618. this._sortLODLevels();
  27619. return this;
  27620. };
  27621. /**
  27622. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27623. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27624. */
  27625. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27626. if (!this._LODLevels || this._LODLevels.length === 0) {
  27627. return this;
  27628. }
  27629. var bSphere;
  27630. if (boundingSphere) {
  27631. bSphere = boundingSphere;
  27632. }
  27633. else {
  27634. var boundingInfo = this.getBoundingInfo();
  27635. bSphere = boundingInfo.boundingSphere;
  27636. }
  27637. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27638. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27639. if (this.onLODLevelSelection) {
  27640. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27641. }
  27642. return this;
  27643. }
  27644. for (var index = 0; index < this._LODLevels.length; index++) {
  27645. var level = this._LODLevels[index];
  27646. if (level.distance < distanceToCamera) {
  27647. if (level.mesh) {
  27648. level.mesh._preActivate();
  27649. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27650. }
  27651. if (this.onLODLevelSelection) {
  27652. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27653. }
  27654. return level.mesh;
  27655. }
  27656. }
  27657. if (this.onLODLevelSelection) {
  27658. this.onLODLevelSelection(distanceToCamera, this, this);
  27659. }
  27660. return this;
  27661. };
  27662. Object.defineProperty(Mesh.prototype, "geometry", {
  27663. /**
  27664. * Returns the mesh internal Geometry object.
  27665. */
  27666. get: function () {
  27667. return this._geometry;
  27668. },
  27669. enumerable: true,
  27670. configurable: true
  27671. });
  27672. /**
  27673. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27674. */
  27675. Mesh.prototype.getTotalVertices = function () {
  27676. if (this._geometry === null || this._geometry === undefined) {
  27677. return 0;
  27678. }
  27679. return this._geometry.getTotalVertices();
  27680. };
  27681. /**
  27682. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27683. * 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.
  27684. * You can force the copy with forceCopy === true
  27685. * Returns null if the mesh has no geometry or no vertex buffer.
  27686. * Possible `kind` values :
  27687. * - BABYLON.VertexBuffer.PositionKind
  27688. * - BABYLON.VertexBuffer.UVKind
  27689. * - BABYLON.VertexBuffer.UV2Kind
  27690. * - BABYLON.VertexBuffer.UV3Kind
  27691. * - BABYLON.VertexBuffer.UV4Kind
  27692. * - BABYLON.VertexBuffer.UV5Kind
  27693. * - BABYLON.VertexBuffer.UV6Kind
  27694. * - BABYLON.VertexBuffer.ColorKind
  27695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27699. */
  27700. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27701. if (!this._geometry) {
  27702. return null;
  27703. }
  27704. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27705. };
  27706. /**
  27707. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27708. * Returns `null` if the mesh has no geometry.
  27709. * Possible `kind` values :
  27710. * - BABYLON.VertexBuffer.PositionKind
  27711. * - BABYLON.VertexBuffer.UVKind
  27712. * - BABYLON.VertexBuffer.UV2Kind
  27713. * - BABYLON.VertexBuffer.UV3Kind
  27714. * - BABYLON.VertexBuffer.UV4Kind
  27715. * - BABYLON.VertexBuffer.UV5Kind
  27716. * - BABYLON.VertexBuffer.UV6Kind
  27717. * - BABYLON.VertexBuffer.ColorKind
  27718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27722. */
  27723. Mesh.prototype.getVertexBuffer = function (kind) {
  27724. if (!this._geometry) {
  27725. return null;
  27726. }
  27727. return this._geometry.getVertexBuffer(kind);
  27728. };
  27729. /**
  27730. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27731. * Possible `kind` values :
  27732. * - BABYLON.VertexBuffer.PositionKind
  27733. * - BABYLON.VertexBuffer.UVKind
  27734. * - BABYLON.VertexBuffer.UV2Kind
  27735. * - BABYLON.VertexBuffer.UV3Kind
  27736. * - BABYLON.VertexBuffer.UV4Kind
  27737. * - BABYLON.VertexBuffer.UV5Kind
  27738. * - BABYLON.VertexBuffer.UV6Kind
  27739. * - BABYLON.VertexBuffer.ColorKind
  27740. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27741. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27742. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27743. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27744. */
  27745. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27746. if (!this._geometry) {
  27747. if (this._delayInfo) {
  27748. return this._delayInfo.indexOf(kind) !== -1;
  27749. }
  27750. return false;
  27751. }
  27752. return this._geometry.isVerticesDataPresent(kind);
  27753. };
  27754. /**
  27755. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27756. * Possible `kind` values :
  27757. * - BABYLON.VertexBuffer.PositionKind
  27758. * - BABYLON.VertexBuffer.UVKind
  27759. * - BABYLON.VertexBuffer.UV2Kind
  27760. * - BABYLON.VertexBuffer.UV3Kind
  27761. * - BABYLON.VertexBuffer.UV4Kind
  27762. * - BABYLON.VertexBuffer.UV5Kind
  27763. * - BABYLON.VertexBuffer.UV6Kind
  27764. * - BABYLON.VertexBuffer.ColorKind
  27765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27769. */
  27770. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27771. if (!this._geometry) {
  27772. if (this._delayInfo) {
  27773. return this._delayInfo.indexOf(kind) !== -1;
  27774. }
  27775. return false;
  27776. }
  27777. return this._geometry.isVertexBufferUpdatable(kind);
  27778. };
  27779. /**
  27780. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27781. * Possible `kind` values :
  27782. * - BABYLON.VertexBuffer.PositionKind
  27783. * - BABYLON.VertexBuffer.UVKind
  27784. * - BABYLON.VertexBuffer.UV2Kind
  27785. * - BABYLON.VertexBuffer.UV3Kind
  27786. * - BABYLON.VertexBuffer.UV4Kind
  27787. * - BABYLON.VertexBuffer.UV5Kind
  27788. * - BABYLON.VertexBuffer.UV6Kind
  27789. * - BABYLON.VertexBuffer.ColorKind
  27790. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27791. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27792. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27793. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27794. */
  27795. Mesh.prototype.getVerticesDataKinds = function () {
  27796. if (!this._geometry) {
  27797. var result = new Array();
  27798. if (this._delayInfo) {
  27799. this._delayInfo.forEach(function (kind, index, array) {
  27800. result.push(kind);
  27801. });
  27802. }
  27803. return result;
  27804. }
  27805. return this._geometry.getVerticesDataKinds();
  27806. };
  27807. /**
  27808. * Returns a positive integer : the total number of indices in this mesh geometry.
  27809. * Returns zero if the mesh has no geometry.
  27810. */
  27811. Mesh.prototype.getTotalIndices = function () {
  27812. if (!this._geometry) {
  27813. return 0;
  27814. }
  27815. return this._geometry.getTotalIndices();
  27816. };
  27817. /**
  27818. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27819. * 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.
  27820. * Returns an empty array if the mesh has no geometry.
  27821. */
  27822. Mesh.prototype.getIndices = function (copyWhenShared) {
  27823. if (!this._geometry) {
  27824. return [];
  27825. }
  27826. return this._geometry.getIndices(copyWhenShared);
  27827. };
  27828. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27829. get: function () {
  27830. return this._masterMesh !== null && this._masterMesh !== undefined;
  27831. },
  27832. enumerable: true,
  27833. configurable: true
  27834. });
  27835. /**
  27836. * Determine if the current mesh is ready to be rendered
  27837. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27838. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27839. * @returns true if all associated assets are ready (material, textures, shaders)
  27840. */
  27841. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27842. if (completeCheck === void 0) { completeCheck = false; }
  27843. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27844. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27845. return false;
  27846. }
  27847. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27848. return false;
  27849. }
  27850. if (!this.subMeshes || this.subMeshes.length === 0) {
  27851. return true;
  27852. }
  27853. if (!completeCheck) {
  27854. return true;
  27855. }
  27856. var engine = this.getEngine();
  27857. var scene = this.getScene();
  27858. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27859. this.computeWorldMatrix();
  27860. var mat = this.material || scene.defaultMaterial;
  27861. if (mat) {
  27862. if (mat.storeEffectOnSubMeshes) {
  27863. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27864. var subMesh = _a[_i];
  27865. var effectiveMaterial = subMesh.getMaterial();
  27866. if (effectiveMaterial) {
  27867. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27868. return false;
  27869. }
  27870. }
  27871. }
  27872. }
  27873. else {
  27874. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27875. return false;
  27876. }
  27877. }
  27878. }
  27879. // Shadows
  27880. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27881. var light = _c[_b];
  27882. var generator = light.getShadowGenerator();
  27883. if (generator) {
  27884. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27885. var subMesh = _e[_d];
  27886. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27887. return false;
  27888. }
  27889. }
  27890. }
  27891. }
  27892. // LOD
  27893. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27894. var lod = _g[_f];
  27895. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27896. return false;
  27897. }
  27898. }
  27899. return true;
  27900. };
  27901. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27902. /**
  27903. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27904. * This property is pertinent only for updatable parametric shapes.
  27905. */
  27906. get: function () {
  27907. return this._areNormalsFrozen;
  27908. },
  27909. enumerable: true,
  27910. configurable: true
  27911. });
  27912. /**
  27913. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27914. * It has no effect at all on other shapes.
  27915. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27916. * Returns the Mesh.
  27917. */
  27918. Mesh.prototype.freezeNormals = function () {
  27919. this._areNormalsFrozen = true;
  27920. return this;
  27921. };
  27922. /**
  27923. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27924. * It has no effect at all on other shapes.
  27925. * It reactivates the mesh normals computation if it was previously frozen.
  27926. * Returns the Mesh.
  27927. */
  27928. Mesh.prototype.unfreezeNormals = function () {
  27929. this._areNormalsFrozen = false;
  27930. return this;
  27931. };
  27932. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27933. /**
  27934. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27935. */
  27936. set: function (count) {
  27937. this._overridenInstanceCount = count;
  27938. },
  27939. enumerable: true,
  27940. configurable: true
  27941. });
  27942. // Methods
  27943. Mesh.prototype._preActivate = function () {
  27944. var sceneRenderId = this.getScene().getRenderId();
  27945. if (this._preActivateId === sceneRenderId) {
  27946. return this;
  27947. }
  27948. this._preActivateId = sceneRenderId;
  27949. this._visibleInstances = null;
  27950. return this;
  27951. };
  27952. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27953. if (this._visibleInstances) {
  27954. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27955. }
  27956. return this;
  27957. };
  27958. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27959. if (!this._visibleInstances) {
  27960. this._visibleInstances = {};
  27961. this._visibleInstances.defaultRenderId = renderId;
  27962. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27963. }
  27964. if (!this._visibleInstances[renderId]) {
  27965. this._visibleInstances[renderId] = new Array();
  27966. }
  27967. this._visibleInstances[renderId].push(instance);
  27968. return this;
  27969. };
  27970. /**
  27971. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27972. * This means the mesh underlying bounding box and sphere are recomputed.
  27973. * Returns the Mesh.
  27974. */
  27975. Mesh.prototype.refreshBoundingInfo = function () {
  27976. return this._refreshBoundingInfo(false);
  27977. };
  27978. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27979. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27980. return this;
  27981. }
  27982. var data = this._getPositionData(applySkeleton);
  27983. if (data) {
  27984. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27985. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27986. }
  27987. if (this.subMeshes) {
  27988. for (var index = 0; index < this.subMeshes.length; index++) {
  27989. this.subMeshes[index].refreshBoundingInfo();
  27990. }
  27991. }
  27992. this._updateBoundingInfo();
  27993. return this;
  27994. };
  27995. Mesh.prototype._getPositionData = function (applySkeleton) {
  27996. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27997. if (data && applySkeleton && this.skeleton) {
  27998. data = BABYLON.Tools.Slice(data);
  27999. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28000. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28001. if (matricesWeightsData && matricesIndicesData) {
  28002. var needExtras = this.numBoneInfluencers > 4;
  28003. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28004. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28005. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28006. var tempVector = BABYLON.Tmp.Vector3[0];
  28007. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28008. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28009. var matWeightIdx = 0;
  28010. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28011. finalMatrix.reset();
  28012. var inf;
  28013. var weight;
  28014. for (inf = 0; inf < 4; inf++) {
  28015. weight = matricesWeightsData[matWeightIdx + inf];
  28016. if (weight <= 0)
  28017. break;
  28018. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28019. finalMatrix.addToSelf(tempMatrix);
  28020. }
  28021. if (needExtras) {
  28022. for (inf = 0; inf < 4; inf++) {
  28023. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28024. if (weight <= 0)
  28025. break;
  28026. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28027. finalMatrix.addToSelf(tempMatrix);
  28028. }
  28029. }
  28030. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28031. tempVector.toArray(data, index);
  28032. }
  28033. }
  28034. }
  28035. return data;
  28036. };
  28037. Mesh.prototype._createGlobalSubMesh = function (force) {
  28038. var totalVertices = this.getTotalVertices();
  28039. if (!totalVertices || !this.getIndices()) {
  28040. return null;
  28041. }
  28042. // Check if we need to recreate the submeshes
  28043. if (this.subMeshes && this.subMeshes.length > 0) {
  28044. var ib = this.getIndices();
  28045. if (!ib) {
  28046. return null;
  28047. }
  28048. var totalIndices = ib.length;
  28049. var needToRecreate = false;
  28050. if (force) {
  28051. needToRecreate = true;
  28052. }
  28053. else {
  28054. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28055. var submesh = _a[_i];
  28056. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28057. needToRecreate = true;
  28058. break;
  28059. }
  28060. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28061. needToRecreate = true;
  28062. break;
  28063. }
  28064. }
  28065. }
  28066. if (!needToRecreate) {
  28067. return this.subMeshes[0];
  28068. }
  28069. }
  28070. this.releaseSubMeshes();
  28071. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28072. };
  28073. Mesh.prototype.subdivide = function (count) {
  28074. if (count < 1) {
  28075. return;
  28076. }
  28077. var totalIndices = this.getTotalIndices();
  28078. var subdivisionSize = (totalIndices / count) | 0;
  28079. var offset = 0;
  28080. // Ensure that subdivisionSize is a multiple of 3
  28081. while (subdivisionSize % 3 !== 0) {
  28082. subdivisionSize++;
  28083. }
  28084. this.releaseSubMeshes();
  28085. for (var index = 0; index < count; index++) {
  28086. if (offset >= totalIndices) {
  28087. break;
  28088. }
  28089. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28090. offset += subdivisionSize;
  28091. }
  28092. this.synchronizeInstances();
  28093. };
  28094. /**
  28095. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28096. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28097. * The `data` are either a numeric array either a Float32Array.
  28098. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28099. * 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).
  28100. * Note that a new underlying VertexBuffer object is created each call.
  28101. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28102. *
  28103. * Possible `kind` values :
  28104. * - BABYLON.VertexBuffer.PositionKind
  28105. * - BABYLON.VertexBuffer.UVKind
  28106. * - BABYLON.VertexBuffer.UV2Kind
  28107. * - BABYLON.VertexBuffer.UV3Kind
  28108. * - BABYLON.VertexBuffer.UV4Kind
  28109. * - BABYLON.VertexBuffer.UV5Kind
  28110. * - BABYLON.VertexBuffer.UV6Kind
  28111. * - BABYLON.VertexBuffer.ColorKind
  28112. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28113. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28114. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28115. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28116. *
  28117. * Returns the Mesh.
  28118. */
  28119. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28120. if (updatable === void 0) { updatable = false; }
  28121. if (!this._geometry) {
  28122. var vertexData = new BABYLON.VertexData();
  28123. vertexData.set(data, kind);
  28124. var scene = this.getScene();
  28125. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28126. }
  28127. else {
  28128. this._geometry.setVerticesData(kind, data, updatable, stride);
  28129. }
  28130. return this;
  28131. };
  28132. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28133. if (updatable === void 0) { updatable = true; }
  28134. var vb = this.getVertexBuffer(kind);
  28135. if (!vb || vb.isUpdatable() === updatable) {
  28136. return;
  28137. }
  28138. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28139. };
  28140. /**
  28141. * Sets the mesh VertexBuffer.
  28142. * Returns the Mesh.
  28143. */
  28144. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28145. if (!this._geometry) {
  28146. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28147. }
  28148. this._geometry.setVerticesBuffer(buffer);
  28149. return this;
  28150. };
  28151. /**
  28152. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28153. * If the mesh has no geometry, it is simply returned as it is.
  28154. * The `data` are either a numeric array either a Float32Array.
  28155. * No new underlying VertexBuffer object is created.
  28156. * 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.
  28157. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28158. *
  28159. * Possible `kind` values :
  28160. * - BABYLON.VertexBuffer.PositionKind
  28161. * - BABYLON.VertexBuffer.UVKind
  28162. * - BABYLON.VertexBuffer.UV2Kind
  28163. * - BABYLON.VertexBuffer.UV3Kind
  28164. * - BABYLON.VertexBuffer.UV4Kind
  28165. * - BABYLON.VertexBuffer.UV5Kind
  28166. * - BABYLON.VertexBuffer.UV6Kind
  28167. * - BABYLON.VertexBuffer.ColorKind
  28168. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28169. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28170. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28171. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28172. *
  28173. * Returns the Mesh.
  28174. */
  28175. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28176. if (!this._geometry) {
  28177. return this;
  28178. }
  28179. if (!makeItUnique) {
  28180. this._geometry.updateVerticesData(kind, data, updateExtends);
  28181. }
  28182. else {
  28183. this.makeGeometryUnique();
  28184. this.updateVerticesData(kind, data, updateExtends, false);
  28185. }
  28186. return this;
  28187. };
  28188. /**
  28189. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28190. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28191. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28192. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28193. * Returns the Mesh.
  28194. */
  28195. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28196. if (computeNormals === void 0) { computeNormals = true; }
  28197. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28198. if (!positions) {
  28199. return this;
  28200. }
  28201. positionFunction(positions);
  28202. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28203. if (computeNormals) {
  28204. var indices = this.getIndices();
  28205. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28206. if (!normals) {
  28207. return this;
  28208. }
  28209. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28210. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28211. }
  28212. return this;
  28213. };
  28214. /**
  28215. * Creates a un-shared specific occurence of the geometry for the mesh.
  28216. * Returns the Mesh.
  28217. */
  28218. Mesh.prototype.makeGeometryUnique = function () {
  28219. if (!this._geometry) {
  28220. return this;
  28221. }
  28222. var oldGeometry = this._geometry;
  28223. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28224. oldGeometry.releaseForMesh(this, true);
  28225. geometry.applyToMesh(this);
  28226. return this;
  28227. };
  28228. /**
  28229. * Sets the mesh indices.
  28230. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28231. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28232. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28233. * This method creates a new index buffer each call.
  28234. * Returns the Mesh.
  28235. */
  28236. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28237. if (totalVertices === void 0) { totalVertices = null; }
  28238. if (updatable === void 0) { updatable = false; }
  28239. if (!this._geometry) {
  28240. var vertexData = new BABYLON.VertexData();
  28241. vertexData.indices = indices;
  28242. var scene = this.getScene();
  28243. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28244. }
  28245. else {
  28246. this._geometry.setIndices(indices, totalVertices, updatable);
  28247. }
  28248. return this;
  28249. };
  28250. /**
  28251. * Update the current index buffer
  28252. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28253. * Returns the Mesh.
  28254. */
  28255. Mesh.prototype.updateIndices = function (indices, offset) {
  28256. if (!this._geometry) {
  28257. return this;
  28258. }
  28259. this._geometry.updateIndices(indices, offset);
  28260. return this;
  28261. };
  28262. /**
  28263. * Invert the geometry to move from a right handed system to a left handed one.
  28264. * Returns the Mesh.
  28265. */
  28266. Mesh.prototype.toLeftHanded = function () {
  28267. if (!this._geometry) {
  28268. return this;
  28269. }
  28270. this._geometry.toLeftHanded();
  28271. return this;
  28272. };
  28273. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28274. if (!this._geometry) {
  28275. return this;
  28276. }
  28277. var engine = this.getScene().getEngine();
  28278. // Wireframe
  28279. var indexToBind;
  28280. if (this._unIndexed) {
  28281. indexToBind = null;
  28282. }
  28283. else {
  28284. switch (fillMode) {
  28285. case BABYLON.Material.PointFillMode:
  28286. indexToBind = null;
  28287. break;
  28288. case BABYLON.Material.WireFrameFillMode:
  28289. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28290. break;
  28291. default:
  28292. case BABYLON.Material.TriangleFillMode:
  28293. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28294. break;
  28295. }
  28296. }
  28297. // VBOs
  28298. this._geometry._bind(effect, indexToBind);
  28299. return this;
  28300. };
  28301. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28302. if (alternate === void 0) { alternate = false; }
  28303. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28304. return this;
  28305. }
  28306. this.onBeforeDrawObservable.notifyObservers(this);
  28307. var scene = this.getScene();
  28308. var engine = scene.getEngine();
  28309. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28310. // or triangles as points
  28311. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28312. }
  28313. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28314. // Triangles as wireframe
  28315. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28316. }
  28317. else {
  28318. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28319. }
  28320. if (scene._isAlternateRenderingEnabled && !alternate) {
  28321. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28322. if (!effect || !scene.activeCamera) {
  28323. return this;
  28324. }
  28325. scene._switchToAlternateCameraConfiguration(true);
  28326. this._effectiveMaterial.bindView(effect);
  28327. this._effectiveMaterial.bindViewProjection(effect);
  28328. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28329. this._draw(subMesh, fillMode, instancesCount, true);
  28330. engine.setViewport(scene.activeCamera.viewport);
  28331. scene._switchToAlternateCameraConfiguration(false);
  28332. this._effectiveMaterial.bindView(effect);
  28333. this._effectiveMaterial.bindViewProjection(effect);
  28334. }
  28335. return this;
  28336. };
  28337. /**
  28338. * Registers for this mesh a javascript function called just before the rendering process.
  28339. * This function is passed the current mesh.
  28340. * Return the Mesh.
  28341. */
  28342. Mesh.prototype.registerBeforeRender = function (func) {
  28343. this.onBeforeRenderObservable.add(func);
  28344. return this;
  28345. };
  28346. /**
  28347. * Disposes a previously registered javascript function called before the rendering.
  28348. * This function is passed the current mesh.
  28349. * Returns the Mesh.
  28350. */
  28351. Mesh.prototype.unregisterBeforeRender = function (func) {
  28352. this.onBeforeRenderObservable.removeCallback(func);
  28353. return this;
  28354. };
  28355. /**
  28356. * Registers for this mesh a javascript function called just after the rendering is complete.
  28357. * This function is passed the current mesh.
  28358. * Returns the Mesh.
  28359. */
  28360. Mesh.prototype.registerAfterRender = function (func) {
  28361. this.onAfterRenderObservable.add(func);
  28362. return this;
  28363. };
  28364. /**
  28365. * Disposes a previously registered javascript function called after the rendering.
  28366. * This function is passed the current mesh.
  28367. * Return the Mesh.
  28368. */
  28369. Mesh.prototype.unregisterAfterRender = function (func) {
  28370. this.onAfterRenderObservable.removeCallback(func);
  28371. return this;
  28372. };
  28373. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28374. var scene = this.getScene();
  28375. this._batchCache.mustReturn = false;
  28376. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28377. this._batchCache.visibleInstances[subMeshId] = null;
  28378. if (this._visibleInstances) {
  28379. var currentRenderId = scene.getRenderId();
  28380. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28381. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28382. var selfRenderId = this._renderId;
  28383. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28384. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28385. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28386. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28387. }
  28388. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28389. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28390. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28391. this._batchCache.mustReturn = true;
  28392. return this._batchCache;
  28393. }
  28394. if (currentRenderId !== selfRenderId) {
  28395. this._batchCache.renderSelf[subMeshId] = false;
  28396. }
  28397. }
  28398. this._renderIdForInstances[subMeshId] = currentRenderId;
  28399. }
  28400. return this._batchCache;
  28401. };
  28402. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28403. var visibleInstances = batch.visibleInstances[subMesh._id];
  28404. if (!visibleInstances) {
  28405. return this;
  28406. }
  28407. var matricesCount = visibleInstances.length + 1;
  28408. var bufferSize = matricesCount * 16 * 4;
  28409. var currentInstancesBufferSize = this._instancesBufferSize;
  28410. var instancesBuffer = this._instancesBuffer;
  28411. while (this._instancesBufferSize < bufferSize) {
  28412. this._instancesBufferSize *= 2;
  28413. }
  28414. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28415. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28416. }
  28417. var offset = 0;
  28418. var instancesCount = 0;
  28419. var world = this.getWorldMatrix();
  28420. if (batch.renderSelf[subMesh._id]) {
  28421. world.copyToArray(this._instancesData, offset);
  28422. offset += 16;
  28423. instancesCount++;
  28424. }
  28425. if (visibleInstances) {
  28426. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28427. var instance = visibleInstances[instanceIndex];
  28428. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28429. offset += 16;
  28430. instancesCount++;
  28431. }
  28432. }
  28433. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28434. if (instancesBuffer) {
  28435. instancesBuffer.dispose();
  28436. }
  28437. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28438. this._instancesBuffer = instancesBuffer;
  28439. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28440. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28441. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28442. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28443. }
  28444. else {
  28445. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28446. }
  28447. this._bind(subMesh, effect, fillMode);
  28448. this._draw(subMesh, fillMode, instancesCount);
  28449. engine.unbindInstanceAttributes();
  28450. return this;
  28451. };
  28452. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28453. var scene = this.getScene();
  28454. var engine = scene.getEngine();
  28455. if (hardwareInstancedRendering) {
  28456. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28457. }
  28458. else {
  28459. if (batch.renderSelf[subMesh._id]) {
  28460. // Draw
  28461. if (onBeforeDraw) {
  28462. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28463. }
  28464. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28465. }
  28466. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28467. if (visibleInstancesForSubMesh) {
  28468. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28469. var instance = visibleInstancesForSubMesh[instanceIndex];
  28470. // World
  28471. var world = instance.getWorldMatrix();
  28472. if (onBeforeDraw) {
  28473. onBeforeDraw(true, world, effectiveMaterial);
  28474. }
  28475. // Draw
  28476. this._draw(subMesh, fillMode);
  28477. }
  28478. }
  28479. }
  28480. return this;
  28481. };
  28482. /**
  28483. * Triggers the draw call for the mesh.
  28484. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28485. * Returns the Mesh.
  28486. */
  28487. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28488. this.checkOcclusionQuery();
  28489. if (this._isOccluded) {
  28490. return this;
  28491. }
  28492. var scene = this.getScene();
  28493. // Managing instances
  28494. var batch = this._getInstancesRenderList(subMesh._id);
  28495. if (batch.mustReturn) {
  28496. return this;
  28497. }
  28498. // Checking geometry state
  28499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28500. return this;
  28501. }
  28502. this.onBeforeRenderObservable.notifyObservers(this);
  28503. var engine = scene.getEngine();
  28504. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28505. // Material
  28506. var material = subMesh.getMaterial();
  28507. if (!material) {
  28508. return this;
  28509. }
  28510. this._effectiveMaterial = material;
  28511. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28512. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28513. return this;
  28514. }
  28515. }
  28516. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28517. return this;
  28518. }
  28519. // Alpha mode
  28520. if (enableAlphaMode) {
  28521. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28522. }
  28523. // Outline - step 1
  28524. var savedDepthWrite = engine.getDepthWrite();
  28525. if (this.renderOutline) {
  28526. engine.setDepthWrite(false);
  28527. scene.getOutlineRenderer().render(subMesh, batch);
  28528. engine.setDepthWrite(savedDepthWrite);
  28529. }
  28530. var effect;
  28531. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28532. effect = subMesh.effect;
  28533. }
  28534. else {
  28535. effect = this._effectiveMaterial.getEffect();
  28536. }
  28537. if (!effect) {
  28538. return this;
  28539. }
  28540. var sideOrientation = this.overrideMaterialSideOrientation;
  28541. if (sideOrientation == null) {
  28542. sideOrientation = this._effectiveMaterial.sideOrientation;
  28543. if (this._getWorldMatrixDeterminant() < 0) {
  28544. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28545. }
  28546. }
  28547. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28548. if (this._effectiveMaterial.forceDepthWrite) {
  28549. engine.setDepthWrite(true);
  28550. }
  28551. // Bind
  28552. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28553. if (!hardwareInstancedRendering) {
  28554. this._bind(subMesh, effect, fillMode);
  28555. }
  28556. var world = this.getWorldMatrix();
  28557. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28558. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28559. }
  28560. else {
  28561. this._effectiveMaterial.bind(world, this);
  28562. }
  28563. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28564. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28565. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28566. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28567. }
  28568. // Draw
  28569. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28570. // Unbind
  28571. this._effectiveMaterial.unbind();
  28572. // Outline - step 2
  28573. if (this.renderOutline && savedDepthWrite) {
  28574. engine.setDepthWrite(true);
  28575. engine.setColorWrite(false);
  28576. scene.getOutlineRenderer().render(subMesh, batch);
  28577. engine.setColorWrite(true);
  28578. }
  28579. // Overlay
  28580. if (this.renderOverlay) {
  28581. var currentMode = engine.getAlphaMode();
  28582. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28583. scene.getOutlineRenderer().render(subMesh, batch, true);
  28584. engine.setAlphaMode(currentMode);
  28585. }
  28586. this.onAfterRenderObservable.notifyObservers(this);
  28587. return this;
  28588. };
  28589. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28590. if (isInstance && effectiveMaterial) {
  28591. effectiveMaterial.bindOnlyWorldMatrix(world);
  28592. }
  28593. };
  28594. /**
  28595. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28596. */
  28597. Mesh.prototype.getEmittedParticleSystems = function () {
  28598. var results = new Array();
  28599. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28600. var particleSystem = this.getScene().particleSystems[index];
  28601. if (particleSystem.emitter === this) {
  28602. results.push(particleSystem);
  28603. }
  28604. }
  28605. return results;
  28606. };
  28607. /**
  28608. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28609. */
  28610. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28611. var results = new Array();
  28612. var descendants = this.getDescendants();
  28613. descendants.push(this);
  28614. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28615. var particleSystem = this.getScene().particleSystems[index];
  28616. var emitter = particleSystem.emitter;
  28617. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28618. results.push(particleSystem);
  28619. }
  28620. }
  28621. return results;
  28622. };
  28623. Mesh.prototype._checkDelayState = function () {
  28624. var scene = this.getScene();
  28625. if (this._geometry) {
  28626. this._geometry.load(scene);
  28627. }
  28628. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28630. this._queueLoad(scene);
  28631. }
  28632. return this;
  28633. };
  28634. Mesh.prototype._queueLoad = function (scene) {
  28635. var _this = this;
  28636. scene._addPendingData(this);
  28637. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28638. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28639. if (data instanceof ArrayBuffer) {
  28640. _this._delayLoadingFunction(data, _this);
  28641. }
  28642. else {
  28643. _this._delayLoadingFunction(JSON.parse(data), _this);
  28644. }
  28645. _this.instances.forEach(function (instance) {
  28646. instance._syncSubMeshes();
  28647. });
  28648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28649. scene._removePendingData(_this);
  28650. }, function () { }, scene.database, getBinaryData);
  28651. return this;
  28652. };
  28653. /**
  28654. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28655. */
  28656. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28658. return false;
  28659. }
  28660. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28661. return false;
  28662. }
  28663. this._checkDelayState();
  28664. return true;
  28665. };
  28666. /**
  28667. * Sets the mesh material by the material or multiMaterial `id` property.
  28668. * The material `id` is a string identifying the material or the multiMaterial.
  28669. * This method returns the Mesh.
  28670. */
  28671. Mesh.prototype.setMaterialByID = function (id) {
  28672. var materials = this.getScene().materials;
  28673. var index;
  28674. for (index = materials.length - 1; index > -1; index--) {
  28675. if (materials[index].id === id) {
  28676. this.material = materials[index];
  28677. return this;
  28678. }
  28679. }
  28680. // Multi
  28681. var multiMaterials = this.getScene().multiMaterials;
  28682. for (index = multiMaterials.length - 1; index > -1; index--) {
  28683. if (multiMaterials[index].id === id) {
  28684. this.material = multiMaterials[index];
  28685. return this;
  28686. }
  28687. }
  28688. return this;
  28689. };
  28690. /**
  28691. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28692. */
  28693. Mesh.prototype.getAnimatables = function () {
  28694. var results = new Array();
  28695. if (this.material) {
  28696. results.push(this.material);
  28697. }
  28698. if (this.skeleton) {
  28699. results.push(this.skeleton);
  28700. }
  28701. return results;
  28702. };
  28703. /**
  28704. * Modifies the mesh geometry according to the passed transformation matrix.
  28705. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28706. * The mesh normals are modified accordingly the same transformation.
  28707. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28708. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28709. * Returns the Mesh.
  28710. */
  28711. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28712. // Position
  28713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28714. return this;
  28715. }
  28716. var submeshes = this.subMeshes.splice(0);
  28717. this._resetPointsArrayCache();
  28718. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28719. var temp = new Array();
  28720. var index;
  28721. for (index = 0; index < data.length; index += 3) {
  28722. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28723. }
  28724. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28725. // Normals
  28726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28727. return this;
  28728. }
  28729. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28730. temp = [];
  28731. for (index = 0; index < data.length; index += 3) {
  28732. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28733. }
  28734. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28735. // flip faces?
  28736. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28737. this.flipFaces();
  28738. }
  28739. // Restore submeshes
  28740. this.releaseSubMeshes();
  28741. this.subMeshes = submeshes;
  28742. return this;
  28743. };
  28744. /**
  28745. * Modifies the mesh geometry according to its own current World Matrix.
  28746. * The mesh World Matrix is then reset.
  28747. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28748. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28749. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28750. * Returns the Mesh.
  28751. */
  28752. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28753. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28754. this.scaling.copyFromFloats(1, 1, 1);
  28755. this.position.copyFromFloats(0, 0, 0);
  28756. this.rotation.copyFromFloats(0, 0, 0);
  28757. //only if quaternion is already set
  28758. if (this.rotationQuaternion) {
  28759. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28760. }
  28761. this._worldMatrix = BABYLON.Matrix.Identity();
  28762. return this;
  28763. };
  28764. Object.defineProperty(Mesh.prototype, "_positions", {
  28765. // Cache
  28766. get: function () {
  28767. if (this._geometry) {
  28768. return this._geometry._positions;
  28769. }
  28770. return null;
  28771. },
  28772. enumerable: true,
  28773. configurable: true
  28774. });
  28775. Mesh.prototype._resetPointsArrayCache = function () {
  28776. if (this._geometry) {
  28777. this._geometry._resetPointsArrayCache();
  28778. }
  28779. return this;
  28780. };
  28781. Mesh.prototype._generatePointsArray = function () {
  28782. if (this._geometry) {
  28783. return this._geometry._generatePointsArray();
  28784. }
  28785. return false;
  28786. };
  28787. /**
  28788. * Returns a new Mesh object generated from the current mesh properties.
  28789. * This method must not get confused with createInstance().
  28790. * The parameter `name` is a string, the name given to the new mesh.
  28791. * The optional parameter `newParent` can be any Node object (default `null`).
  28792. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28793. * 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.
  28794. */
  28795. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28796. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28797. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28798. };
  28799. /**
  28800. * Releases resources associated with this mesh.
  28801. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28802. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28803. */
  28804. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28805. var _this = this;
  28806. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28807. this.morphTargetManager = null;
  28808. if (this._geometry) {
  28809. this._geometry.releaseForMesh(this, true);
  28810. }
  28811. // Sources
  28812. var meshes = this.getScene().meshes;
  28813. meshes.forEach(function (abstractMesh) {
  28814. var mesh = abstractMesh;
  28815. if (mesh._source && mesh._source === _this) {
  28816. mesh._source = null;
  28817. }
  28818. });
  28819. this._source = null;
  28820. // Instances
  28821. if (this._instancesBuffer) {
  28822. this._instancesBuffer.dispose();
  28823. this._instancesBuffer = null;
  28824. }
  28825. while (this.instances.length) {
  28826. this.instances[0].dispose();
  28827. }
  28828. // Effect layers.
  28829. var effectLayers = this.getScene().effectLayers;
  28830. for (var i = 0; i < effectLayers.length; i++) {
  28831. var effectLayer = effectLayers[i];
  28832. if (effectLayer) {
  28833. effectLayer._disposeMesh(this);
  28834. }
  28835. }
  28836. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28837. };
  28838. /**
  28839. * Modifies the mesh geometry according to a displacement map.
  28840. * 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.
  28841. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28842. * This method returns nothing.
  28843. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28844. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28845. * 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.
  28846. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28847. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28848. *
  28849. * Returns the Mesh.
  28850. */
  28851. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28852. var _this = this;
  28853. var scene = this.getScene();
  28854. var onload = function (img) {
  28855. // Getting height map data
  28856. var canvas = document.createElement("canvas");
  28857. var context = canvas.getContext("2d");
  28858. var heightMapWidth = img.width;
  28859. var heightMapHeight = img.height;
  28860. canvas.width = heightMapWidth;
  28861. canvas.height = heightMapHeight;
  28862. context.drawImage(img, 0, 0);
  28863. // Create VertexData from map data
  28864. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28865. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28866. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28867. //execute success callback, if set
  28868. if (onSuccess) {
  28869. onSuccess(_this);
  28870. }
  28871. };
  28872. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28873. return this;
  28874. };
  28875. /**
  28876. * Modifies the mesh geometry according to a displacementMap buffer.
  28877. * 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.
  28878. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28879. * This method returns nothing.
  28880. * 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.
  28881. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28882. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28883. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28884. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28885. *
  28886. * Returns the Mesh.
  28887. */
  28888. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28889. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28890. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28891. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28892. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28893. return this;
  28894. }
  28895. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28896. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28897. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28898. var position = BABYLON.Vector3.Zero();
  28899. var normal = BABYLON.Vector3.Zero();
  28900. var uv = BABYLON.Vector2.Zero();
  28901. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28902. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28903. for (var index = 0; index < positions.length; index += 3) {
  28904. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28905. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28906. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28907. // Compute height
  28908. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28909. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28910. var pos = (u + v * heightMapWidth) * 4;
  28911. var r = buffer[pos] / 255.0;
  28912. var g = buffer[pos + 1] / 255.0;
  28913. var b = buffer[pos + 2] / 255.0;
  28914. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28915. normal.normalize();
  28916. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28917. position = position.add(normal);
  28918. position.toArray(positions, index);
  28919. }
  28920. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28921. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28922. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28923. return this;
  28924. };
  28925. /**
  28926. * Modify the mesh to get a flat shading rendering.
  28927. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28928. * This method returns the Mesh.
  28929. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28930. */
  28931. Mesh.prototype.convertToFlatShadedMesh = function () {
  28932. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28933. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28934. var kinds = this.getVerticesDataKinds();
  28935. var vbs = {};
  28936. var data = {};
  28937. var newdata = {};
  28938. var updatableNormals = false;
  28939. var kindIndex;
  28940. var kind;
  28941. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28942. kind = kinds[kindIndex];
  28943. var vertexBuffer = this.getVertexBuffer(kind);
  28944. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28945. updatableNormals = vertexBuffer.isUpdatable();
  28946. kinds.splice(kindIndex, 1);
  28947. kindIndex--;
  28948. continue;
  28949. }
  28950. vbs[kind] = vertexBuffer;
  28951. data[kind] = vbs[kind].getData();
  28952. newdata[kind] = [];
  28953. }
  28954. // Save previous submeshes
  28955. var previousSubmeshes = this.subMeshes.slice(0);
  28956. var indices = this.getIndices();
  28957. var totalIndices = this.getTotalIndices();
  28958. // Generating unique vertices per face
  28959. var index;
  28960. for (index = 0; index < totalIndices; index++) {
  28961. var vertexIndex = indices[index];
  28962. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28963. kind = kinds[kindIndex];
  28964. var stride = vbs[kind].getStrideSize();
  28965. for (var offset = 0; offset < stride; offset++) {
  28966. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28967. }
  28968. }
  28969. }
  28970. // Updating faces & normal
  28971. var normals = [];
  28972. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28973. for (index = 0; index < totalIndices; index += 3) {
  28974. indices[index] = index;
  28975. indices[index + 1] = index + 1;
  28976. indices[index + 2] = index + 2;
  28977. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28978. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28979. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28980. var p1p2 = p1.subtract(p2);
  28981. var p3p2 = p3.subtract(p2);
  28982. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28983. // Store same normals for every vertex
  28984. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28985. normals.push(normal.x);
  28986. normals.push(normal.y);
  28987. normals.push(normal.z);
  28988. }
  28989. }
  28990. this.setIndices(indices);
  28991. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28992. // Updating vertex buffers
  28993. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28994. kind = kinds[kindIndex];
  28995. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28996. }
  28997. // Updating submeshes
  28998. this.releaseSubMeshes();
  28999. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29000. var previousOne = previousSubmeshes[submeshIndex];
  29001. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29002. }
  29003. this.synchronizeInstances();
  29004. return this;
  29005. };
  29006. /**
  29007. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29008. * In other words, more vertices, no more indices and a single bigger VBO.
  29009. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29010. * Returns the Mesh.
  29011. */
  29012. Mesh.prototype.convertToUnIndexedMesh = function () {
  29013. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29014. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29015. var kinds = this.getVerticesDataKinds();
  29016. var vbs = {};
  29017. var data = {};
  29018. var newdata = {};
  29019. var kindIndex;
  29020. var kind;
  29021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29022. kind = kinds[kindIndex];
  29023. var vertexBuffer = this.getVertexBuffer(kind);
  29024. vbs[kind] = vertexBuffer;
  29025. data[kind] = vbs[kind].getData();
  29026. newdata[kind] = [];
  29027. }
  29028. // Save previous submeshes
  29029. var previousSubmeshes = this.subMeshes.slice(0);
  29030. var indices = this.getIndices();
  29031. var totalIndices = this.getTotalIndices();
  29032. // Generating unique vertices per face
  29033. var index;
  29034. for (index = 0; index < totalIndices; index++) {
  29035. var vertexIndex = indices[index];
  29036. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29037. kind = kinds[kindIndex];
  29038. var stride = vbs[kind].getStrideSize();
  29039. for (var offset = 0; offset < stride; offset++) {
  29040. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29041. }
  29042. }
  29043. }
  29044. // Updating indices
  29045. for (index = 0; index < totalIndices; index += 3) {
  29046. indices[index] = index;
  29047. indices[index + 1] = index + 1;
  29048. indices[index + 2] = index + 2;
  29049. }
  29050. this.setIndices(indices);
  29051. // Updating vertex buffers
  29052. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29053. kind = kinds[kindIndex];
  29054. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29055. }
  29056. // Updating submeshes
  29057. this.releaseSubMeshes();
  29058. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29059. var previousOne = previousSubmeshes[submeshIndex];
  29060. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29061. }
  29062. this._unIndexed = true;
  29063. this.synchronizeInstances();
  29064. return this;
  29065. };
  29066. /**
  29067. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29068. * This method returns the Mesh.
  29069. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29070. */
  29071. Mesh.prototype.flipFaces = function (flipNormals) {
  29072. if (flipNormals === void 0) { flipNormals = false; }
  29073. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29074. var i;
  29075. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29076. for (i = 0; i < vertex_data.normals.length; i++) {
  29077. vertex_data.normals[i] *= -1;
  29078. }
  29079. }
  29080. if (vertex_data.indices) {
  29081. var temp;
  29082. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29083. // reassign indices
  29084. temp = vertex_data.indices[i + 1];
  29085. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29086. vertex_data.indices[i + 2] = temp;
  29087. }
  29088. }
  29089. vertex_data.applyToMesh(this);
  29090. return this;
  29091. };
  29092. // Instances
  29093. /**
  29094. * Creates a new InstancedMesh object from the mesh model.
  29095. * An instance shares the same properties and the same material than its model.
  29096. * Only these properties of each instance can then be set individually :
  29097. * - position
  29098. * - rotation
  29099. * - rotationQuaternion
  29100. * - setPivotMatrix
  29101. * - scaling
  29102. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29103. * Warning : this method is not supported for Line mesh and LineSystem
  29104. */
  29105. Mesh.prototype.createInstance = function (name) {
  29106. return new BABYLON.InstancedMesh(name, this);
  29107. };
  29108. /**
  29109. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29110. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29111. * This method returns the Mesh.
  29112. */
  29113. Mesh.prototype.synchronizeInstances = function () {
  29114. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29115. var instance = this.instances[instanceIndex];
  29116. instance._syncSubMeshes();
  29117. }
  29118. return this;
  29119. };
  29120. /**
  29121. * Simplify the mesh according to the given array of settings.
  29122. * Function will return immediately and will simplify async. It returns the Mesh.
  29123. * @param settings a collection of simplification settings.
  29124. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29125. * @param type the type of simplification to run.
  29126. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29127. */
  29128. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29129. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29130. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29131. this.getScene().simplificationQueue.addTask({
  29132. settings: settings,
  29133. parallelProcessing: parallelProcessing,
  29134. mesh: this,
  29135. simplificationType: simplificationType,
  29136. successCallback: successCallback
  29137. });
  29138. return this;
  29139. };
  29140. /**
  29141. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29142. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29143. * This should be used together with the simplification to avoid disappearing triangles.
  29144. * Returns the Mesh.
  29145. * @param successCallback an optional success callback to be called after the optimization finished.
  29146. */
  29147. Mesh.prototype.optimizeIndices = function (successCallback) {
  29148. var _this = this;
  29149. var indices = this.getIndices();
  29150. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29151. if (!positions || !indices) {
  29152. return this;
  29153. }
  29154. var vectorPositions = new Array();
  29155. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29156. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29157. }
  29158. var dupes = new Array();
  29159. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29160. var realPos = vectorPositions.length - 1 - iteration;
  29161. var testedPosition = vectorPositions[realPos];
  29162. for (var j = 0; j < realPos; ++j) {
  29163. var againstPosition = vectorPositions[j];
  29164. if (testedPosition.equals(againstPosition)) {
  29165. dupes[realPos] = j;
  29166. break;
  29167. }
  29168. }
  29169. }, function () {
  29170. for (var i = 0; i < indices.length; ++i) {
  29171. indices[i] = dupes[indices[i]] || indices[i];
  29172. }
  29173. //indices are now reordered
  29174. var originalSubMeshes = _this.subMeshes.slice(0);
  29175. _this.setIndices(indices);
  29176. _this.subMeshes = originalSubMeshes;
  29177. if (successCallback) {
  29178. successCallback(_this);
  29179. }
  29180. });
  29181. return this;
  29182. };
  29183. Mesh.prototype.serialize = function (serializationObject) {
  29184. serializationObject.name = this.name;
  29185. serializationObject.id = this.id;
  29186. serializationObject.type = this.getClassName();
  29187. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29188. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29189. }
  29190. serializationObject.position = this.position.asArray();
  29191. if (this.rotationQuaternion) {
  29192. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29193. }
  29194. else if (this.rotation) {
  29195. serializationObject.rotation = this.rotation.asArray();
  29196. }
  29197. serializationObject.scaling = this.scaling.asArray();
  29198. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29199. serializationObject.isEnabled = this.isEnabled(false);
  29200. serializationObject.isVisible = this.isVisible;
  29201. serializationObject.infiniteDistance = this.infiniteDistance;
  29202. serializationObject.pickable = this.isPickable;
  29203. serializationObject.receiveShadows = this.receiveShadows;
  29204. serializationObject.billboardMode = this.billboardMode;
  29205. serializationObject.visibility = this.visibility;
  29206. serializationObject.checkCollisions = this.checkCollisions;
  29207. serializationObject.isBlocker = this.isBlocker;
  29208. // Parent
  29209. if (this.parent) {
  29210. serializationObject.parentId = this.parent.id;
  29211. }
  29212. // Geometry
  29213. serializationObject.isUnIndexed = this.isUnIndexed;
  29214. var geometry = this._geometry;
  29215. if (geometry) {
  29216. var geometryId = geometry.id;
  29217. serializationObject.geometryId = geometryId;
  29218. // SubMeshes
  29219. serializationObject.subMeshes = [];
  29220. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29221. var subMesh = this.subMeshes[subIndex];
  29222. serializationObject.subMeshes.push({
  29223. materialIndex: subMesh.materialIndex,
  29224. verticesStart: subMesh.verticesStart,
  29225. verticesCount: subMesh.verticesCount,
  29226. indexStart: subMesh.indexStart,
  29227. indexCount: subMesh.indexCount
  29228. });
  29229. }
  29230. }
  29231. // Material
  29232. if (this.material) {
  29233. serializationObject.materialId = this.material.id;
  29234. }
  29235. else {
  29236. this.material = null;
  29237. }
  29238. // Morph targets
  29239. if (this.morphTargetManager) {
  29240. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29241. }
  29242. // Skeleton
  29243. if (this.skeleton) {
  29244. serializationObject.skeletonId = this.skeleton.id;
  29245. }
  29246. // Physics
  29247. //TODO implement correct serialization for physics impostors.
  29248. var impostor = this.getPhysicsImpostor();
  29249. if (impostor) {
  29250. serializationObject.physicsMass = impostor.getParam("mass");
  29251. serializationObject.physicsFriction = impostor.getParam("friction");
  29252. serializationObject.physicsRestitution = impostor.getParam("mass");
  29253. serializationObject.physicsImpostor = impostor.type;
  29254. }
  29255. // Metadata
  29256. if (this.metadata) {
  29257. serializationObject.metadata = this.metadata;
  29258. }
  29259. // Instances
  29260. serializationObject.instances = [];
  29261. for (var index = 0; index < this.instances.length; index++) {
  29262. var instance = this.instances[index];
  29263. var serializationInstance = {
  29264. name: instance.name,
  29265. id: instance.id,
  29266. position: instance.position.asArray(),
  29267. scaling: instance.scaling.asArray()
  29268. };
  29269. if (instance.rotationQuaternion) {
  29270. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29271. }
  29272. else if (instance.rotation) {
  29273. serializationInstance.rotation = instance.rotation.asArray();
  29274. }
  29275. serializationObject.instances.push(serializationInstance);
  29276. // Animations
  29277. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29278. serializationInstance.ranges = instance.serializeAnimationRanges();
  29279. }
  29280. //
  29281. // Animations
  29282. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29283. serializationObject.ranges = this.serializeAnimationRanges();
  29284. // Layer mask
  29285. serializationObject.layerMask = this.layerMask;
  29286. // Alpha
  29287. serializationObject.alphaIndex = this.alphaIndex;
  29288. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29289. // Overlay
  29290. serializationObject.overlayAlpha = this.overlayAlpha;
  29291. serializationObject.overlayColor = this.overlayColor.asArray();
  29292. serializationObject.renderOverlay = this.renderOverlay;
  29293. // Fog
  29294. serializationObject.applyFog = this.applyFog;
  29295. // Action Manager
  29296. if (this.actionManager) {
  29297. serializationObject.actions = this.actionManager.serialize(this.name);
  29298. }
  29299. };
  29300. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29301. if (!this.geometry) {
  29302. return;
  29303. }
  29304. this._markSubMeshesAsAttributesDirty();
  29305. var morphTargetManager = this._morphTargetManager;
  29306. if (morphTargetManager && morphTargetManager.vertexCount) {
  29307. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29308. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29309. this.morphTargetManager = null;
  29310. return;
  29311. }
  29312. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29313. var morphTarget = morphTargetManager.getActiveTarget(index);
  29314. var positions = morphTarget.getPositions();
  29315. if (!positions) {
  29316. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29317. return;
  29318. }
  29319. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29320. var normals = morphTarget.getNormals();
  29321. if (normals) {
  29322. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29323. }
  29324. var tangents = morphTarget.getTangents();
  29325. if (tangents) {
  29326. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29327. }
  29328. }
  29329. }
  29330. else {
  29331. var index = 0;
  29332. // Positions
  29333. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29334. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29335. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29336. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29337. }
  29338. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29339. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29340. }
  29341. index++;
  29342. }
  29343. }
  29344. };
  29345. // Statics
  29346. /**
  29347. * Returns a new Mesh object parsed from the source provided.
  29348. * The parameter `parsedMesh` is the source.
  29349. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29350. */
  29351. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29352. var mesh;
  29353. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29354. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29355. }
  29356. else {
  29357. mesh = new Mesh(parsedMesh.name, scene);
  29358. }
  29359. mesh.id = parsedMesh.id;
  29360. if (BABYLON.Tags) {
  29361. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29362. }
  29363. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29364. if (parsedMesh.metadata !== undefined) {
  29365. mesh.metadata = parsedMesh.metadata;
  29366. }
  29367. if (parsedMesh.rotationQuaternion) {
  29368. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29369. }
  29370. else if (parsedMesh.rotation) {
  29371. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29372. }
  29373. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29374. if (parsedMesh.localMatrix) {
  29375. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29376. }
  29377. else if (parsedMesh.pivotMatrix) {
  29378. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29379. }
  29380. mesh.setEnabled(parsedMesh.isEnabled);
  29381. mesh.isVisible = parsedMesh.isVisible;
  29382. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29383. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29384. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29385. if (parsedMesh.applyFog !== undefined) {
  29386. mesh.applyFog = parsedMesh.applyFog;
  29387. }
  29388. if (parsedMesh.pickable !== undefined) {
  29389. mesh.isPickable = parsedMesh.pickable;
  29390. }
  29391. if (parsedMesh.alphaIndex !== undefined) {
  29392. mesh.alphaIndex = parsedMesh.alphaIndex;
  29393. }
  29394. mesh.receiveShadows = parsedMesh.receiveShadows;
  29395. mesh.billboardMode = parsedMesh.billboardMode;
  29396. if (parsedMesh.visibility !== undefined) {
  29397. mesh.visibility = parsedMesh.visibility;
  29398. }
  29399. mesh.checkCollisions = parsedMesh.checkCollisions;
  29400. if (parsedMesh.isBlocker !== undefined) {
  29401. mesh.isBlocker = parsedMesh.isBlocker;
  29402. }
  29403. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29404. // freezeWorldMatrix
  29405. if (parsedMesh.freezeWorldMatrix) {
  29406. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29407. }
  29408. // Parent
  29409. if (parsedMesh.parentId) {
  29410. mesh._waitingParentId = parsedMesh.parentId;
  29411. }
  29412. // Actions
  29413. if (parsedMesh.actions !== undefined) {
  29414. mesh._waitingActions = parsedMesh.actions;
  29415. }
  29416. // Overlay
  29417. if (parsedMesh.overlayAlpha !== undefined) {
  29418. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29419. }
  29420. if (parsedMesh.overlayColor !== undefined) {
  29421. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29422. }
  29423. if (parsedMesh.renderOverlay !== undefined) {
  29424. mesh.renderOverlay = parsedMesh.renderOverlay;
  29425. }
  29426. // Geometry
  29427. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29428. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29429. if (parsedMesh.delayLoadingFile) {
  29430. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29431. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29432. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29433. if (parsedMesh._binaryInfo) {
  29434. mesh._binaryInfo = parsedMesh._binaryInfo;
  29435. }
  29436. mesh._delayInfo = [];
  29437. if (parsedMesh.hasUVs) {
  29438. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29439. }
  29440. if (parsedMesh.hasUVs2) {
  29441. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29442. }
  29443. if (parsedMesh.hasUVs3) {
  29444. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29445. }
  29446. if (parsedMesh.hasUVs4) {
  29447. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29448. }
  29449. if (parsedMesh.hasUVs5) {
  29450. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29451. }
  29452. if (parsedMesh.hasUVs6) {
  29453. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29454. }
  29455. if (parsedMesh.hasColors) {
  29456. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29457. }
  29458. if (parsedMesh.hasMatricesIndices) {
  29459. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29460. }
  29461. if (parsedMesh.hasMatricesWeights) {
  29462. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29463. }
  29464. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29465. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29466. mesh._checkDelayState();
  29467. }
  29468. }
  29469. else {
  29470. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29471. }
  29472. // Material
  29473. if (parsedMesh.materialId) {
  29474. mesh.setMaterialByID(parsedMesh.materialId);
  29475. }
  29476. else {
  29477. mesh.material = null;
  29478. }
  29479. // Morph targets
  29480. if (parsedMesh.morphTargetManagerId > -1) {
  29481. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29482. }
  29483. // Skeleton
  29484. if (parsedMesh.skeletonId > -1) {
  29485. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29486. if (parsedMesh.numBoneInfluencers) {
  29487. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29488. }
  29489. }
  29490. // Animations
  29491. if (parsedMesh.animations) {
  29492. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29493. var parsedAnimation = parsedMesh.animations[animationIndex];
  29494. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29495. }
  29496. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29497. }
  29498. if (parsedMesh.autoAnimate) {
  29499. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29500. }
  29501. // Layer Mask
  29502. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29503. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29504. }
  29505. else {
  29506. mesh.layerMask = 0x0FFFFFFF;
  29507. }
  29508. // Physics
  29509. if (parsedMesh.physicsImpostor) {
  29510. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29511. mass: parsedMesh.physicsMass,
  29512. friction: parsedMesh.physicsFriction,
  29513. restitution: parsedMesh.physicsRestitution
  29514. }, scene);
  29515. }
  29516. // Instances
  29517. if (parsedMesh.instances) {
  29518. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29519. var parsedInstance = parsedMesh.instances[index];
  29520. var instance = mesh.createInstance(parsedInstance.name);
  29521. if (parsedInstance.id) {
  29522. instance.id = parsedInstance.id;
  29523. }
  29524. if (BABYLON.Tags) {
  29525. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29526. }
  29527. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29528. if (parsedInstance.parentId) {
  29529. instance._waitingParentId = parsedInstance.parentId;
  29530. }
  29531. if (parsedInstance.rotationQuaternion) {
  29532. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29533. }
  29534. else if (parsedInstance.rotation) {
  29535. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29536. }
  29537. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29538. instance.checkCollisions = mesh.checkCollisions;
  29539. if (parsedMesh.animations) {
  29540. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29541. parsedAnimation = parsedMesh.animations[animationIndex];
  29542. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29543. }
  29544. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29545. }
  29546. }
  29547. }
  29548. return mesh;
  29549. };
  29550. /**
  29551. * Creates a ribbon mesh.
  29552. * Please consider using the same method from the MeshBuilder class instead.
  29553. * 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.
  29554. *
  29555. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29556. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29557. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29558. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29559. * 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.
  29560. * 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.
  29561. * 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
  29562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29565. */
  29566. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29567. if (closeArray === void 0) { closeArray = false; }
  29568. if (updatable === void 0) { updatable = false; }
  29569. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29570. pathArray: pathArray,
  29571. closeArray: closeArray,
  29572. closePath: closePath,
  29573. offset: offset,
  29574. updatable: updatable,
  29575. sideOrientation: sideOrientation,
  29576. instance: instance
  29577. }, scene);
  29578. };
  29579. /**
  29580. * Creates a plane polygonal mesh. By default, this is a disc.
  29581. * Please consider using the same method from the MeshBuilder class instead.
  29582. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29583. * 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.
  29584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29587. */
  29588. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29589. if (scene === void 0) { scene = null; }
  29590. var options = {
  29591. radius: radius,
  29592. tessellation: tessellation,
  29593. sideOrientation: sideOrientation,
  29594. updatable: updatable
  29595. };
  29596. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29597. };
  29598. /**
  29599. * Creates a box mesh.
  29600. * Please consider using the same method from the MeshBuilder class instead.
  29601. * The parameter `size` sets the size (float) of each box side (default 1).
  29602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29605. */
  29606. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29607. if (scene === void 0) { scene = null; }
  29608. var options = {
  29609. size: size,
  29610. sideOrientation: sideOrientation,
  29611. updatable: updatable
  29612. };
  29613. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29614. };
  29615. /**
  29616. * Creates a sphere mesh.
  29617. * Please consider using the same method from the MeshBuilder class instead.
  29618. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29619. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29623. */
  29624. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29625. var options = {
  29626. segments: segments,
  29627. diameterX: diameter,
  29628. diameterY: diameter,
  29629. diameterZ: diameter,
  29630. sideOrientation: sideOrientation,
  29631. updatable: updatable
  29632. };
  29633. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates a cylinder or a cone mesh.
  29637. * Please consider using the same method from the MeshBuilder class instead.
  29638. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29639. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29640. * 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.
  29641. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29642. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29646. */
  29647. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29648. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29649. if (scene !== undefined) {
  29650. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29651. updatable = scene;
  29652. }
  29653. scene = subdivisions;
  29654. subdivisions = 1;
  29655. }
  29656. var options = {
  29657. height: height,
  29658. diameterTop: diameterTop,
  29659. diameterBottom: diameterBottom,
  29660. tessellation: tessellation,
  29661. subdivisions: subdivisions,
  29662. sideOrientation: sideOrientation,
  29663. updatable: updatable
  29664. };
  29665. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29666. };
  29667. // Torus (Code from SharpDX.org)
  29668. /**
  29669. * Creates a torus mesh.
  29670. * Please consider using the same method from the MeshBuilder class instead.
  29671. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29672. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29673. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29677. */
  29678. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29679. var options = {
  29680. diameter: diameter,
  29681. thickness: thickness,
  29682. tessellation: tessellation,
  29683. sideOrientation: sideOrientation,
  29684. updatable: updatable
  29685. };
  29686. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29687. };
  29688. /**
  29689. * Creates a torus knot mesh.
  29690. * Please consider using the same method from the MeshBuilder class instead.
  29691. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29692. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29693. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29694. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29698. */
  29699. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29700. var options = {
  29701. radius: radius,
  29702. tube: tube,
  29703. radialSegments: radialSegments,
  29704. tubularSegments: tubularSegments,
  29705. p: p,
  29706. q: q,
  29707. sideOrientation: sideOrientation,
  29708. updatable: updatable
  29709. };
  29710. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29711. };
  29712. /**
  29713. * Creates a line mesh.
  29714. * Please consider using the same method from the MeshBuilder class instead.
  29715. * 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.
  29716. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29717. * The parameter `points` is an array successive Vector3.
  29718. * 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
  29719. * When updating an instance, remember that only point positions can change, not the number of points.
  29720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29721. */
  29722. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29723. if (scene === void 0) { scene = null; }
  29724. if (updatable === void 0) { updatable = false; }
  29725. if (instance === void 0) { instance = null; }
  29726. var options = {
  29727. points: points,
  29728. updatable: updatable,
  29729. instance: instance
  29730. };
  29731. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29732. };
  29733. /**
  29734. * Creates a dashed line mesh.
  29735. * Please consider using the same method from the MeshBuilder class instead.
  29736. * 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.
  29737. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29738. * The parameter `points` is an array successive Vector3.
  29739. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29740. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29741. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29742. * 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
  29743. * When updating an instance, remember that only point positions can change, not the number of points.
  29744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29745. */
  29746. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29747. if (scene === void 0) { scene = null; }
  29748. var options = {
  29749. points: points,
  29750. dashSize: dashSize,
  29751. gapSize: gapSize,
  29752. dashNb: dashNb,
  29753. updatable: updatable,
  29754. instance: instance
  29755. };
  29756. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29757. };
  29758. /**
  29759. * Creates a polygon mesh.
  29760. * Please consider using the same method from the MeshBuilder class instead.
  29761. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29762. * 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.
  29763. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  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. * Remember you can only change the shape positions, not their number when updating a polygon.
  29766. */
  29767. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29768. var options = {
  29769. shape: shape,
  29770. holes: holes,
  29771. updatable: updatable,
  29772. sideOrientation: sideOrientation
  29773. };
  29774. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29775. };
  29776. /**
  29777. * Creates an extruded polygon mesh, with depth in the Y direction.
  29778. * Please consider using the same method from the MeshBuilder class instead.
  29779. */
  29780. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29781. var options = {
  29782. shape: shape,
  29783. holes: holes,
  29784. depth: depth,
  29785. updatable: updatable,
  29786. sideOrientation: sideOrientation
  29787. };
  29788. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29789. };
  29790. /**
  29791. * Creates an extruded shape mesh.
  29792. * 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.
  29793. * Please consider using the same method from the MeshBuilder class instead.
  29794. *
  29795. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29796. * 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
  29797. * extruded along the Z axis.
  29798. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29799. * 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.
  29800. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29801. * 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
  29802. * 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
  29803. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29807. */
  29808. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29809. if (scene === void 0) { scene = null; }
  29810. var options = {
  29811. shape: shape,
  29812. path: path,
  29813. scale: scale,
  29814. rotation: rotation,
  29815. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29816. sideOrientation: sideOrientation,
  29817. instance: instance,
  29818. updatable: updatable
  29819. };
  29820. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29821. };
  29822. /**
  29823. * Creates an custom extruded shape mesh.
  29824. * 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.
  29825. * Please consider using the same method from the MeshBuilder class instead.
  29826. *
  29827. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29828. * 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
  29829. * extruded along the Z axis.
  29830. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29831. * 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
  29832. * and the distance of this point from the begining of the path :
  29833. * ```javascript
  29834. * var rotationFunction = function(i, distance) {
  29835. * // do things
  29836. * return rotationValue; }
  29837. * ```
  29838. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29839. * 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
  29840. * and the distance of this point from the begining of the path :
  29841. * ```javascript
  29842. * var scaleFunction = function(i, distance) {
  29843. * // do things
  29844. * return scaleValue;}
  29845. * ```
  29846. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29847. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29848. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29849. * 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
  29850. * 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
  29851. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29855. */
  29856. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29857. var options = {
  29858. shape: shape,
  29859. path: path,
  29860. scaleFunction: scaleFunction,
  29861. rotationFunction: rotationFunction,
  29862. ribbonCloseArray: ribbonCloseArray,
  29863. ribbonClosePath: ribbonClosePath,
  29864. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29865. sideOrientation: sideOrientation,
  29866. instance: instance,
  29867. updatable: updatable
  29868. };
  29869. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29870. };
  29871. /**
  29872. * Creates lathe mesh.
  29873. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29874. * Please consider using the same method from the MeshBuilder class instead.
  29875. * 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
  29876. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29877. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29878. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29882. */
  29883. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29884. var options = {
  29885. shape: shape,
  29886. radius: radius,
  29887. tessellation: tessellation,
  29888. sideOrientation: sideOrientation,
  29889. updatable: updatable
  29890. };
  29891. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29892. };
  29893. /**
  29894. * Creates a plane mesh.
  29895. * Please consider using the same method from the MeshBuilder class instead.
  29896. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29897. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29900. */
  29901. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29902. var options = {
  29903. size: size,
  29904. width: size,
  29905. height: size,
  29906. sideOrientation: sideOrientation,
  29907. updatable: updatable
  29908. };
  29909. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29910. };
  29911. /**
  29912. * Creates a ground mesh.
  29913. * Please consider using the same method from the MeshBuilder class instead.
  29914. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29915. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29917. */
  29918. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29919. var options = {
  29920. width: width,
  29921. height: height,
  29922. subdivisions: subdivisions,
  29923. updatable: updatable
  29924. };
  29925. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29926. };
  29927. /**
  29928. * Creates a tiled ground mesh.
  29929. * Please consider using the same method from the MeshBuilder class instead.
  29930. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29931. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29932. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29933. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29934. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29935. * numbers of subdivisions on the ground width and height of each tile.
  29936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29937. */
  29938. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29939. var options = {
  29940. xmin: xmin,
  29941. zmin: zmin,
  29942. xmax: xmax,
  29943. zmax: zmax,
  29944. subdivisions: subdivisions,
  29945. precision: precision,
  29946. updatable: updatable
  29947. };
  29948. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29949. };
  29950. /**
  29951. * Creates a ground mesh from a height map.
  29952. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29953. * Please consider using the same method from the MeshBuilder class instead.
  29954. * The parameter `url` sets the URL of the height map image resource.
  29955. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29956. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29957. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29958. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29959. * 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).
  29960. * This function is passed the newly built mesh :
  29961. * ```javascript
  29962. * function(mesh) { // do things
  29963. * return; }
  29964. * ```
  29965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29966. */
  29967. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29968. var options = {
  29969. width: width,
  29970. height: height,
  29971. subdivisions: subdivisions,
  29972. minHeight: minHeight,
  29973. maxHeight: maxHeight,
  29974. updatable: updatable,
  29975. onReady: onReady
  29976. };
  29977. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29978. };
  29979. /**
  29980. * Creates a tube mesh.
  29981. * 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.
  29982. * Please consider using the same method from the MeshBuilder class instead.
  29983. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29984. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29985. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29986. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29987. * 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.
  29988. * It must return a radius value (positive float) :
  29989. * ```javascript
  29990. * var radiusFunction = function(i, distance) {
  29991. * // do things
  29992. * return radius; }
  29993. * ```
  29994. * 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
  29995. * 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
  29996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29999. */
  30000. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30001. var options = {
  30002. path: path,
  30003. radius: radius,
  30004. tessellation: tessellation,
  30005. radiusFunction: radiusFunction,
  30006. arc: 1,
  30007. cap: cap,
  30008. updatable: updatable,
  30009. sideOrientation: sideOrientation,
  30010. instance: instance
  30011. };
  30012. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30013. };
  30014. /**
  30015. * Creates a polyhedron mesh.
  30016. * Please consider using the same method from the MeshBuilder class instead.
  30017. * 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
  30018. * to choose the wanted type.
  30019. * The parameter `size` (positive float, default 1) sets the polygon size.
  30020. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30021. * 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`.
  30022. * 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
  30023. * 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)`).
  30024. * 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
  30025. * 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.
  30026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30029. */
  30030. Mesh.CreatePolyhedron = function (name, options, scene) {
  30031. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30032. };
  30033. /**
  30034. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30035. * Please consider using the same method from the MeshBuilder class instead.
  30036. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30037. * 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`).
  30038. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30039. * 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.
  30040. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30041. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30043. */
  30044. Mesh.CreateIcoSphere = function (name, options, scene) {
  30045. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30046. };
  30047. /**
  30048. * Creates a decal mesh.
  30049. * Please consider using the same method from the MeshBuilder class instead.
  30050. * 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.
  30051. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30052. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30053. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30054. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30055. */
  30056. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30057. var options = {
  30058. position: position,
  30059. normal: normal,
  30060. size: size,
  30061. angle: angle
  30062. };
  30063. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30064. };
  30065. // Skeletons
  30066. /**
  30067. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30068. */
  30069. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30070. if (!this._sourcePositions) {
  30071. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30072. if (!source) {
  30073. return this._sourcePositions;
  30074. }
  30075. this._sourcePositions = new Float32Array(source);
  30076. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30077. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30078. }
  30079. }
  30080. return this._sourcePositions;
  30081. };
  30082. /**
  30083. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30084. */
  30085. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30086. if (!this._sourceNormals) {
  30087. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30088. if (!source) {
  30089. return this._sourceNormals;
  30090. }
  30091. this._sourceNormals = new Float32Array(source);
  30092. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30093. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30094. }
  30095. }
  30096. return this._sourceNormals;
  30097. };
  30098. /**
  30099. * Updates the vertex buffer by applying transformation from the bones.
  30100. * Returns the Mesh.
  30101. *
  30102. * @param {skeleton} skeleton to apply
  30103. */
  30104. Mesh.prototype.applySkeleton = function (skeleton) {
  30105. if (!this.geometry) {
  30106. return this;
  30107. }
  30108. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30109. return this;
  30110. }
  30111. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30112. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30113. return this;
  30114. }
  30115. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30116. return this;
  30117. }
  30118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30119. return this;
  30120. }
  30121. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30122. return this;
  30123. }
  30124. if (!this._sourcePositions) {
  30125. var submeshes = this.subMeshes.slice();
  30126. this.setPositionsForCPUSkinning();
  30127. this.subMeshes = submeshes;
  30128. }
  30129. if (!this._sourceNormals) {
  30130. this.setNormalsForCPUSkinning();
  30131. }
  30132. // positionsData checks for not being Float32Array will only pass at most once
  30133. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30134. if (!positionsData) {
  30135. return this;
  30136. }
  30137. if (!(positionsData instanceof Float32Array)) {
  30138. positionsData = new Float32Array(positionsData);
  30139. }
  30140. // normalsData checks for not being Float32Array will only pass at most once
  30141. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30142. if (!normalsData) {
  30143. return this;
  30144. }
  30145. if (!(normalsData instanceof Float32Array)) {
  30146. normalsData = new Float32Array(normalsData);
  30147. }
  30148. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30149. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30150. if (!matricesWeightsData || !matricesIndicesData) {
  30151. return this;
  30152. }
  30153. var needExtras = this.numBoneInfluencers > 4;
  30154. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30155. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30156. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30157. var tempVector3 = BABYLON.Vector3.Zero();
  30158. var finalMatrix = new BABYLON.Matrix();
  30159. var tempMatrix = new BABYLON.Matrix();
  30160. var matWeightIdx = 0;
  30161. var inf;
  30162. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30163. var weight;
  30164. for (inf = 0; inf < 4; inf++) {
  30165. weight = matricesWeightsData[matWeightIdx + inf];
  30166. if (weight > 0) {
  30167. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30168. finalMatrix.addToSelf(tempMatrix);
  30169. }
  30170. else
  30171. break;
  30172. }
  30173. if (needExtras) {
  30174. for (inf = 0; inf < 4; inf++) {
  30175. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30176. if (weight > 0) {
  30177. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30178. finalMatrix.addToSelf(tempMatrix);
  30179. }
  30180. else
  30181. break;
  30182. }
  30183. }
  30184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30185. tempVector3.toArray(positionsData, index);
  30186. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30187. tempVector3.toArray(normalsData, index);
  30188. finalMatrix.reset();
  30189. }
  30190. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30191. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30192. return this;
  30193. };
  30194. // Tools
  30195. /**
  30196. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30197. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30198. */
  30199. Mesh.MinMax = function (meshes) {
  30200. var minVector = null;
  30201. var maxVector = null;
  30202. meshes.forEach(function (mesh, index, array) {
  30203. var boundingInfo = mesh.getBoundingInfo();
  30204. var boundingBox = boundingInfo.boundingBox;
  30205. if (!minVector || !maxVector) {
  30206. minVector = boundingBox.minimumWorld;
  30207. maxVector = boundingBox.maximumWorld;
  30208. }
  30209. else {
  30210. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30211. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30212. }
  30213. });
  30214. if (!minVector || !maxVector) {
  30215. return {
  30216. min: BABYLON.Vector3.Zero(),
  30217. max: BABYLON.Vector3.Zero()
  30218. };
  30219. }
  30220. return {
  30221. min: minVector,
  30222. max: maxVector
  30223. };
  30224. };
  30225. /**
  30226. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30227. */
  30228. Mesh.Center = function (meshesOrMinMaxVector) {
  30229. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30230. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30231. };
  30232. /**
  30233. * Merge the array of meshes into a single mesh for performance reasons.
  30234. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30235. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30236. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30237. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30238. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30239. */
  30240. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30241. if (disposeSource === void 0) { disposeSource = true; }
  30242. var index;
  30243. if (!allow32BitsIndices) {
  30244. var totalVertices = 0;
  30245. // Counting vertices
  30246. for (index = 0; index < meshes.length; index++) {
  30247. if (meshes[index]) {
  30248. totalVertices += meshes[index].getTotalVertices();
  30249. if (totalVertices > 65536) {
  30250. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30251. return null;
  30252. }
  30253. }
  30254. }
  30255. }
  30256. // Merge
  30257. var vertexData = null;
  30258. var otherVertexData;
  30259. var indiceArray = new Array();
  30260. var source = null;
  30261. for (index = 0; index < meshes.length; index++) {
  30262. if (meshes[index]) {
  30263. meshes[index].computeWorldMatrix(true);
  30264. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30265. otherVertexData.transform(meshes[index].getWorldMatrix());
  30266. if (vertexData) {
  30267. vertexData.merge(otherVertexData);
  30268. }
  30269. else {
  30270. vertexData = otherVertexData;
  30271. source = meshes[index];
  30272. }
  30273. if (subdivideWithSubMeshes) {
  30274. indiceArray.push(meshes[index].getTotalIndices());
  30275. }
  30276. }
  30277. }
  30278. source = source;
  30279. if (!meshSubclass) {
  30280. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30281. }
  30282. vertexData.applyToMesh(meshSubclass);
  30283. // Setting properties
  30284. meshSubclass.material = source.material;
  30285. meshSubclass.checkCollisions = source.checkCollisions;
  30286. // Cleaning
  30287. if (disposeSource) {
  30288. for (index = 0; index < meshes.length; index++) {
  30289. if (meshes[index]) {
  30290. meshes[index].dispose();
  30291. }
  30292. }
  30293. }
  30294. // Subdivide
  30295. if (subdivideWithSubMeshes) {
  30296. //-- Suppresions du submesh global
  30297. meshSubclass.releaseSubMeshes();
  30298. index = 0;
  30299. var offset = 0;
  30300. //-- aplique la subdivision en fonction du tableau d'indices
  30301. while (index < indiceArray.length) {
  30302. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30303. offset += indiceArray[index];
  30304. index++;
  30305. }
  30306. }
  30307. return meshSubclass;
  30308. };
  30309. // Consts
  30310. Mesh._FRONTSIDE = 0;
  30311. Mesh._BACKSIDE = 1;
  30312. Mesh._DOUBLESIDE = 2;
  30313. Mesh._DEFAULTSIDE = 0;
  30314. Mesh._NO_CAP = 0;
  30315. Mesh._CAP_START = 1;
  30316. Mesh._CAP_END = 2;
  30317. Mesh._CAP_ALL = 3;
  30318. return Mesh;
  30319. }(BABYLON.AbstractMesh));
  30320. BABYLON.Mesh = Mesh;
  30321. })(BABYLON || (BABYLON = {}));
  30322. //# sourceMappingURL=babylon.mesh.js.map
  30323. var BABYLON;
  30324. (function (BABYLON) {
  30325. var BaseSubMesh = /** @class */ (function () {
  30326. function BaseSubMesh() {
  30327. }
  30328. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30329. get: function () {
  30330. return this._materialEffect;
  30331. },
  30332. enumerable: true,
  30333. configurable: true
  30334. });
  30335. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30336. if (defines === void 0) { defines = null; }
  30337. if (this._materialEffect === effect) {
  30338. if (!effect) {
  30339. this._materialDefines = null;
  30340. }
  30341. return;
  30342. }
  30343. this._materialDefines = defines;
  30344. this._materialEffect = effect;
  30345. };
  30346. return BaseSubMesh;
  30347. }());
  30348. BABYLON.BaseSubMesh = BaseSubMesh;
  30349. var SubMesh = /** @class */ (function (_super) {
  30350. __extends(SubMesh, _super);
  30351. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30352. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30353. var _this = _super.call(this) || this;
  30354. _this.materialIndex = materialIndex;
  30355. _this.verticesStart = verticesStart;
  30356. _this.verticesCount = verticesCount;
  30357. _this.indexStart = indexStart;
  30358. _this.indexCount = indexCount;
  30359. _this._renderId = 0;
  30360. _this._mesh = mesh;
  30361. _this._renderingMesh = renderingMesh || mesh;
  30362. mesh.subMeshes.push(_this);
  30363. _this._trianglePlanes = [];
  30364. _this._id = mesh.subMeshes.length - 1;
  30365. if (createBoundingBox) {
  30366. _this.refreshBoundingInfo();
  30367. mesh.computeWorldMatrix(true);
  30368. }
  30369. return _this;
  30370. }
  30371. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30372. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30373. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30374. };
  30375. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30376. get: function () {
  30377. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30378. },
  30379. enumerable: true,
  30380. configurable: true
  30381. });
  30382. /**
  30383. * Returns the submesh BoudingInfo object.
  30384. */
  30385. SubMesh.prototype.getBoundingInfo = function () {
  30386. if (this.IsGlobal) {
  30387. return this._mesh.getBoundingInfo();
  30388. }
  30389. return this._boundingInfo;
  30390. };
  30391. /**
  30392. * Sets the submesh BoundingInfo.
  30393. * Return the SubMesh.
  30394. */
  30395. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30396. this._boundingInfo = boundingInfo;
  30397. return this;
  30398. };
  30399. /**
  30400. * Returns the mesh of the current submesh.
  30401. */
  30402. SubMesh.prototype.getMesh = function () {
  30403. return this._mesh;
  30404. };
  30405. /**
  30406. * Returns the rendering mesh of the submesh.
  30407. */
  30408. SubMesh.prototype.getRenderingMesh = function () {
  30409. return this._renderingMesh;
  30410. };
  30411. /**
  30412. * Returns the submesh material.
  30413. */
  30414. SubMesh.prototype.getMaterial = function () {
  30415. var rootMaterial = this._renderingMesh.material;
  30416. if (rootMaterial === null || rootMaterial === undefined) {
  30417. return this._mesh.getScene().defaultMaterial;
  30418. }
  30419. else if (rootMaterial.getSubMaterial) {
  30420. var multiMaterial = rootMaterial;
  30421. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30422. if (this._currentMaterial !== effectiveMaterial) {
  30423. this._currentMaterial = effectiveMaterial;
  30424. this._materialDefines = null;
  30425. }
  30426. return effectiveMaterial;
  30427. }
  30428. return rootMaterial;
  30429. };
  30430. // Methods
  30431. /**
  30432. * Sets a new updated BoundingInfo object to the submesh.
  30433. * Returns the SubMesh.
  30434. */
  30435. SubMesh.prototype.refreshBoundingInfo = function () {
  30436. this._lastColliderWorldVertices = null;
  30437. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30438. return this;
  30439. }
  30440. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30441. if (!data) {
  30442. this._boundingInfo = this._mesh.getBoundingInfo();
  30443. return this;
  30444. }
  30445. var indices = this._renderingMesh.getIndices();
  30446. var extend;
  30447. //is this the only submesh?
  30448. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30449. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30450. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30451. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30452. }
  30453. else {
  30454. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30455. }
  30456. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30457. return this;
  30458. };
  30459. SubMesh.prototype._checkCollision = function (collider) {
  30460. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30461. return boundingInfo._checkCollision(collider);
  30462. };
  30463. /**
  30464. * Updates the submesh BoundingInfo.
  30465. * Returns the Submesh.
  30466. */
  30467. SubMesh.prototype.updateBoundingInfo = function (world) {
  30468. var boundingInfo = this.getBoundingInfo();
  30469. if (!boundingInfo) {
  30470. this.refreshBoundingInfo();
  30471. boundingInfo = this.getBoundingInfo();
  30472. }
  30473. boundingInfo.update(world);
  30474. return this;
  30475. };
  30476. /**
  30477. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30478. * Boolean returned.
  30479. */
  30480. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30481. var boundingInfo = this.getBoundingInfo();
  30482. if (!boundingInfo) {
  30483. return false;
  30484. }
  30485. return boundingInfo.isInFrustum(frustumPlanes);
  30486. };
  30487. /**
  30488. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30489. * Boolean returned.
  30490. */
  30491. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30492. var boundingInfo = this.getBoundingInfo();
  30493. if (!boundingInfo) {
  30494. return false;
  30495. }
  30496. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30497. };
  30498. /**
  30499. * Renders the submesh.
  30500. * Returns it.
  30501. */
  30502. SubMesh.prototype.render = function (enableAlphaMode) {
  30503. this._renderingMesh.render(this, enableAlphaMode);
  30504. return this;
  30505. };
  30506. /**
  30507. * Returns a new Index Buffer.
  30508. * Type returned : WebGLBuffer.
  30509. */
  30510. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30511. if (!this._linesIndexBuffer) {
  30512. var linesIndices = [];
  30513. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30514. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30515. }
  30516. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30517. this.linesIndexCount = linesIndices.length;
  30518. }
  30519. return this._linesIndexBuffer;
  30520. };
  30521. /**
  30522. * True is the passed Ray intersects the submesh bounding box.
  30523. * Boolean returned.
  30524. */
  30525. SubMesh.prototype.canIntersects = function (ray) {
  30526. var boundingInfo = this.getBoundingInfo();
  30527. if (!boundingInfo) {
  30528. return false;
  30529. }
  30530. return ray.intersectsBox(boundingInfo.boundingBox);
  30531. };
  30532. /**
  30533. * Returns an object IntersectionInfo.
  30534. */
  30535. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30536. var intersectInfo = null;
  30537. // LineMesh first as it's also a Mesh...
  30538. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30539. var lineMesh = this._mesh;
  30540. // Line test
  30541. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30542. var p0 = positions[indices[index]];
  30543. var p1 = positions[indices[index + 1]];
  30544. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30545. if (length < 0) {
  30546. continue;
  30547. }
  30548. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30549. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30550. if (fastCheck) {
  30551. break;
  30552. }
  30553. }
  30554. }
  30555. }
  30556. else {
  30557. // Triangles test
  30558. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30559. var p0 = positions[indices[index]];
  30560. var p1 = positions[indices[index + 1]];
  30561. var p2 = positions[indices[index + 2]];
  30562. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30563. if (currentIntersectInfo) {
  30564. if (currentIntersectInfo.distance < 0) {
  30565. continue;
  30566. }
  30567. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30568. intersectInfo = currentIntersectInfo;
  30569. intersectInfo.faceId = index / 3;
  30570. if (fastCheck) {
  30571. break;
  30572. }
  30573. }
  30574. }
  30575. }
  30576. }
  30577. return intersectInfo;
  30578. };
  30579. SubMesh.prototype._rebuild = function () {
  30580. if (this._linesIndexBuffer) {
  30581. this._linesIndexBuffer = null;
  30582. }
  30583. };
  30584. // Clone
  30585. /**
  30586. * Creates a new Submesh from the passed Mesh.
  30587. */
  30588. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30589. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30590. if (!this.IsGlobal) {
  30591. var boundingInfo = this.getBoundingInfo();
  30592. if (!boundingInfo) {
  30593. return result;
  30594. }
  30595. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30596. }
  30597. return result;
  30598. };
  30599. // Dispose
  30600. /**
  30601. * Disposes the Submesh.
  30602. * Returns nothing.
  30603. */
  30604. SubMesh.prototype.dispose = function () {
  30605. if (this._linesIndexBuffer) {
  30606. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30607. this._linesIndexBuffer = null;
  30608. }
  30609. // Remove from mesh
  30610. var index = this._mesh.subMeshes.indexOf(this);
  30611. this._mesh.subMeshes.splice(index, 1);
  30612. };
  30613. // Statics
  30614. /**
  30615. * Creates a new Submesh from the passed parameters :
  30616. * - materialIndex (integer) : the index of the main mesh material.
  30617. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30618. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30619. * - mesh (Mesh) : the main mesh to create the submesh from.
  30620. * - renderingMesh (optional Mesh) : rendering mesh.
  30621. */
  30622. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30623. var minVertexIndex = Number.MAX_VALUE;
  30624. var maxVertexIndex = -Number.MAX_VALUE;
  30625. renderingMesh = (renderingMesh || mesh);
  30626. var indices = renderingMesh.getIndices();
  30627. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30628. var vertexIndex = indices[index];
  30629. if (vertexIndex < minVertexIndex)
  30630. minVertexIndex = vertexIndex;
  30631. if (vertexIndex > maxVertexIndex)
  30632. maxVertexIndex = vertexIndex;
  30633. }
  30634. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30635. };
  30636. return SubMesh;
  30637. }(BaseSubMesh));
  30638. BABYLON.SubMesh = SubMesh;
  30639. })(BABYLON || (BABYLON = {}));
  30640. //# sourceMappingURL=babylon.subMesh.js.map
  30641. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30642. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30643. s = arguments[i];
  30644. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30645. t[p] = s[p];
  30646. }
  30647. return t;
  30648. };
  30649. var BABYLON;
  30650. (function (BABYLON) {
  30651. /**
  30652. * Manages the defines for the Material.
  30653. */
  30654. var MaterialDefines = /** @class */ (function () {
  30655. function MaterialDefines() {
  30656. this._isDirty = true;
  30657. this._areLightsDirty = true;
  30658. this._areAttributesDirty = true;
  30659. this._areTexturesDirty = true;
  30660. this._areFresnelDirty = true;
  30661. this._areMiscDirty = true;
  30662. this._areImageProcessingDirty = true;
  30663. this._normals = false;
  30664. this._uvs = false;
  30665. this._needNormals = false;
  30666. this._needUVs = false;
  30667. }
  30668. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30669. /**
  30670. * Specifies if the material needs to be re-calculated.
  30671. */
  30672. get: function () {
  30673. return this._isDirty;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. /**
  30679. * Marks the material to indicate that it has been re-calculated.
  30680. */
  30681. MaterialDefines.prototype.markAsProcessed = function () {
  30682. this._isDirty = false;
  30683. this._areAttributesDirty = false;
  30684. this._areTexturesDirty = false;
  30685. this._areFresnelDirty = false;
  30686. this._areLightsDirty = false;
  30687. this._areMiscDirty = false;
  30688. this._areImageProcessingDirty = false;
  30689. };
  30690. /**
  30691. * Marks the material to indicate that it needs to be re-calculated.
  30692. */
  30693. MaterialDefines.prototype.markAsUnprocessed = function () {
  30694. this._isDirty = true;
  30695. };
  30696. /**
  30697. * Marks the material to indicate all of its defines need to be re-calculated.
  30698. */
  30699. MaterialDefines.prototype.markAllAsDirty = function () {
  30700. this._areTexturesDirty = true;
  30701. this._areAttributesDirty = true;
  30702. this._areLightsDirty = true;
  30703. this._areFresnelDirty = true;
  30704. this._areMiscDirty = true;
  30705. this._areImageProcessingDirty = true;
  30706. this._isDirty = true;
  30707. };
  30708. /**
  30709. * Marks the material to indicate that image processing needs to be re-calculated.
  30710. */
  30711. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30712. this._areImageProcessingDirty = true;
  30713. this._isDirty = true;
  30714. };
  30715. /**
  30716. * Marks the material to indicate the lights need to be re-calculated.
  30717. */
  30718. MaterialDefines.prototype.markAsLightDirty = function () {
  30719. this._areLightsDirty = true;
  30720. this._isDirty = true;
  30721. };
  30722. /**
  30723. * Marks the attribute state as changed.
  30724. */
  30725. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30726. this._areAttributesDirty = true;
  30727. this._isDirty = true;
  30728. };
  30729. /**
  30730. * Marks the texture state as changed.
  30731. */
  30732. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30733. this._areTexturesDirty = true;
  30734. this._isDirty = true;
  30735. };
  30736. /**
  30737. * Marks the fresnel state as changed.
  30738. */
  30739. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30740. this._areFresnelDirty = true;
  30741. this._isDirty = true;
  30742. };
  30743. /**
  30744. * Marks the misc state as changed.
  30745. */
  30746. MaterialDefines.prototype.markAsMiscDirty = function () {
  30747. this._areMiscDirty = true;
  30748. this._isDirty = true;
  30749. };
  30750. /**
  30751. * Rebuilds the material defines.
  30752. */
  30753. MaterialDefines.prototype.rebuild = function () {
  30754. if (this._keys) {
  30755. delete this._keys;
  30756. }
  30757. this._keys = [];
  30758. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30759. var key = _a[_i];
  30760. if (key[0] === "_") {
  30761. continue;
  30762. }
  30763. this._keys.push(key);
  30764. }
  30765. };
  30766. /**
  30767. * Specifies if two material defines are equal.
  30768. * @param other - A material define instance to compare to.
  30769. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30770. */
  30771. MaterialDefines.prototype.isEqual = function (other) {
  30772. if (this._keys.length !== other._keys.length) {
  30773. return false;
  30774. }
  30775. for (var index = 0; index < this._keys.length; index++) {
  30776. var prop = this._keys[index];
  30777. if (this[prop] !== other[prop]) {
  30778. return false;
  30779. }
  30780. }
  30781. return true;
  30782. };
  30783. /**
  30784. * Clones this instance's defines to another instance.
  30785. * @param other - material defines to clone values to.
  30786. */
  30787. MaterialDefines.prototype.cloneTo = function (other) {
  30788. if (this._keys.length !== other._keys.length) {
  30789. other._keys = this._keys.slice(0);
  30790. }
  30791. for (var index = 0; index < this._keys.length; index++) {
  30792. var prop = this._keys[index];
  30793. other[prop] = this[prop];
  30794. }
  30795. };
  30796. /**
  30797. * Resets the material define values.
  30798. */
  30799. MaterialDefines.prototype.reset = function () {
  30800. for (var index = 0; index < this._keys.length; index++) {
  30801. var prop = this._keys[index];
  30802. if (typeof (this[prop]) === "number") {
  30803. this[prop] = 0;
  30804. }
  30805. else {
  30806. this[prop] = false;
  30807. }
  30808. }
  30809. };
  30810. /**
  30811. * Converts the material define values to a string.
  30812. * @returns - String of material define information.
  30813. */
  30814. MaterialDefines.prototype.toString = function () {
  30815. var result = "";
  30816. for (var index = 0; index < this._keys.length; index++) {
  30817. var prop = this._keys[index];
  30818. var value = this[prop];
  30819. if (typeof (value) === "number") {
  30820. result += "#define " + prop + " " + this[prop] + "\n";
  30821. }
  30822. else if (value) {
  30823. result += "#define " + prop + "\n";
  30824. }
  30825. }
  30826. return result;
  30827. };
  30828. return MaterialDefines;
  30829. }());
  30830. BABYLON.MaterialDefines = MaterialDefines;
  30831. /**
  30832. * This offers the main features of a material in BJS.
  30833. */
  30834. var Material = /** @class */ (function () {
  30835. /**
  30836. * Creates a material instance.
  30837. * @param name - The name of the material.
  30838. * @param scene - The BJS scene to reference.
  30839. * @param doNotAdd - Specifies if the material should be added to the scene.
  30840. */
  30841. function Material(name, scene, doNotAdd) {
  30842. /**
  30843. * Specifies if the ready state should be checked on each call.
  30844. */
  30845. this.checkReadyOnEveryCall = false;
  30846. /**
  30847. * Specifies if the ready state should be checked once.
  30848. */
  30849. this.checkReadyOnlyOnce = false;
  30850. /**
  30851. * The state of the material.
  30852. */
  30853. this.state = "";
  30854. /**
  30855. * The alpha value of the material.
  30856. */
  30857. this._alpha = 1.0;
  30858. /**
  30859. * Specifies if back face culling is enabled.
  30860. */
  30861. this._backFaceCulling = true;
  30862. /**
  30863. * Specifies if the material should be serialized.
  30864. */
  30865. this.doNotSerialize = false;
  30866. /**
  30867. * Specifies if the effect should be stored on sub meshes.
  30868. */
  30869. this.storeEffectOnSubMeshes = false;
  30870. /**
  30871. * An event triggered when the material is disposed.
  30872. * @type {BABYLON.Observable}
  30873. */
  30874. this.onDisposeObservable = new BABYLON.Observable();
  30875. /**
  30876. * An event triggered when the material is bound.
  30877. * @type {BABYLON.Observable}
  30878. */
  30879. this.onBindObservable = new BABYLON.Observable();
  30880. /**
  30881. * An event triggered when the material is unbound.
  30882. * @type {BABYLON.Observable}
  30883. */
  30884. this.onUnBindObservable = new BABYLON.Observable();
  30885. /**
  30886. * Stores the value of the alpha mode.
  30887. */
  30888. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30889. /**
  30890. * Stores the state of the need depth pre-pass value.
  30891. */
  30892. this._needDepthPrePass = false;
  30893. /**
  30894. * Specifies if depth writing should be disabled.
  30895. */
  30896. this.disableDepthWrite = false;
  30897. /**
  30898. * Specifies if depth writing should be forced.
  30899. */
  30900. this.forceDepthWrite = false;
  30901. /**
  30902. * Specifies if there should be a separate pass for culling.
  30903. */
  30904. this.separateCullingPass = false;
  30905. /**
  30906. * Stores the state specifing if fog should be enabled.
  30907. */
  30908. this._fogEnabled = true;
  30909. /**
  30910. * Stores the size of points.
  30911. */
  30912. this.pointSize = 1.0;
  30913. /**
  30914. * Stores the z offset value.
  30915. */
  30916. this.zOffset = 0;
  30917. /**
  30918. * Specifies if the material was previously ready.
  30919. */
  30920. this._wasPreviouslyReady = false;
  30921. /**
  30922. * Stores the fill mode state.
  30923. */
  30924. this._fillMode = Material.TriangleFillMode;
  30925. this.name = name;
  30926. this.id = name || BABYLON.Tools.RandomId();
  30927. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30928. if (this._scene.useRightHandedSystem) {
  30929. this.sideOrientation = Material.ClockWiseSideOrientation;
  30930. }
  30931. else {
  30932. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30933. }
  30934. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30935. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30936. if (!doNotAdd) {
  30937. this._scene.materials.push(this);
  30938. }
  30939. }
  30940. Object.defineProperty(Material, "TriangleFillMode", {
  30941. /**
  30942. * Returns the triangle fill mode.
  30943. */
  30944. get: function () {
  30945. return Material._TriangleFillMode;
  30946. },
  30947. enumerable: true,
  30948. configurable: true
  30949. });
  30950. Object.defineProperty(Material, "WireFrameFillMode", {
  30951. /**
  30952. * Returns the wireframe mode.
  30953. */
  30954. get: function () {
  30955. return Material._WireFrameFillMode;
  30956. },
  30957. enumerable: true,
  30958. configurable: true
  30959. });
  30960. Object.defineProperty(Material, "PointFillMode", {
  30961. /**
  30962. * Returns the point fill mode.
  30963. */
  30964. get: function () {
  30965. return Material._PointFillMode;
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Object.defineProperty(Material, "PointListDrawMode", {
  30971. /**
  30972. * Returns the point list draw mode.
  30973. */
  30974. get: function () {
  30975. return Material._PointListDrawMode;
  30976. },
  30977. enumerable: true,
  30978. configurable: true
  30979. });
  30980. Object.defineProperty(Material, "LineListDrawMode", {
  30981. /**
  30982. * Returns the line list draw mode.
  30983. */
  30984. get: function () {
  30985. return Material._LineListDrawMode;
  30986. },
  30987. enumerable: true,
  30988. configurable: true
  30989. });
  30990. Object.defineProperty(Material, "LineLoopDrawMode", {
  30991. /**
  30992. * Returns the line loop draw mode.
  30993. */
  30994. get: function () {
  30995. return Material._LineLoopDrawMode;
  30996. },
  30997. enumerable: true,
  30998. configurable: true
  30999. });
  31000. Object.defineProperty(Material, "LineStripDrawMode", {
  31001. /**
  31002. * Returns the line strip draw mode.
  31003. */
  31004. get: function () {
  31005. return Material._LineStripDrawMode;
  31006. },
  31007. enumerable: true,
  31008. configurable: true
  31009. });
  31010. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31011. /**
  31012. * Returns the triangle strip draw mode.
  31013. */
  31014. get: function () {
  31015. return Material._TriangleStripDrawMode;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31021. /**
  31022. * Returns the triangle fan draw mode.
  31023. */
  31024. get: function () {
  31025. return Material._TriangleFanDrawMode;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31031. /**
  31032. * Returns the clock-wise side orientation.
  31033. */
  31034. get: function () {
  31035. return Material._ClockWiseSideOrientation;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31041. /**
  31042. * Returns the counter clock-wise side orientation.
  31043. */
  31044. get: function () {
  31045. return Material._CounterClockWiseSideOrientation;
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. Object.defineProperty(Material, "TextureDirtyFlag", {
  31051. /**
  31052. * Returns the dirty texture flag value.
  31053. */
  31054. get: function () {
  31055. return Material._TextureDirtyFlag;
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(Material, "LightDirtyFlag", {
  31061. /**
  31062. * Returns the dirty light flag value.
  31063. */
  31064. get: function () {
  31065. return Material._LightDirtyFlag;
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31071. /**
  31072. * Returns the dirty fresnel flag value.
  31073. */
  31074. get: function () {
  31075. return Material._FresnelDirtyFlag;
  31076. },
  31077. enumerable: true,
  31078. configurable: true
  31079. });
  31080. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31081. /**
  31082. * Returns the dirty attributes flag value.
  31083. */
  31084. get: function () {
  31085. return Material._AttributesDirtyFlag;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Object.defineProperty(Material, "MiscDirtyFlag", {
  31091. /**
  31092. * Returns the dirty misc flag value.
  31093. */
  31094. get: function () {
  31095. return Material._MiscDirtyFlag;
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(Material.prototype, "alpha", {
  31101. /**
  31102. * Gets the alpha value of the material.
  31103. */
  31104. get: function () {
  31105. return this._alpha;
  31106. },
  31107. /**
  31108. * Sets the alpha value of the material.
  31109. */
  31110. set: function (value) {
  31111. if (this._alpha === value) {
  31112. return;
  31113. }
  31114. this._alpha = value;
  31115. this.markAsDirty(Material.MiscDirtyFlag);
  31116. },
  31117. enumerable: true,
  31118. configurable: true
  31119. });
  31120. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31121. /**
  31122. * Gets the back-face culling state.
  31123. */
  31124. get: function () {
  31125. return this._backFaceCulling;
  31126. },
  31127. /**
  31128. * Sets the back-face culling state.
  31129. */
  31130. set: function (value) {
  31131. if (this._backFaceCulling === value) {
  31132. return;
  31133. }
  31134. this._backFaceCulling = value;
  31135. this.markAsDirty(Material.TextureDirtyFlag);
  31136. },
  31137. enumerable: true,
  31138. configurable: true
  31139. });
  31140. Object.defineProperty(Material.prototype, "onDispose", {
  31141. /**
  31142. * Called during a dispose event.
  31143. */
  31144. set: function (callback) {
  31145. if (this._onDisposeObserver) {
  31146. this.onDisposeObservable.remove(this._onDisposeObserver);
  31147. }
  31148. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. Object.defineProperty(Material.prototype, "onBind", {
  31154. /**
  31155. * Called during a bind event.
  31156. */
  31157. set: function (callback) {
  31158. if (this._onBindObserver) {
  31159. this.onBindObservable.remove(this._onBindObserver);
  31160. }
  31161. this._onBindObserver = this.onBindObservable.add(callback);
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Object.defineProperty(Material.prototype, "alphaMode", {
  31167. /**
  31168. * Gets the value of the alpha mode.
  31169. */
  31170. get: function () {
  31171. return this._alphaMode;
  31172. },
  31173. /**
  31174. * Sets the value of the alpha mode.
  31175. */
  31176. set: function (value) {
  31177. if (this._alphaMode === value) {
  31178. return;
  31179. }
  31180. this._alphaMode = value;
  31181. this.markAsDirty(Material.TextureDirtyFlag);
  31182. },
  31183. enumerable: true,
  31184. configurable: true
  31185. });
  31186. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31187. /**
  31188. * Gets the depth pre-pass value.
  31189. */
  31190. get: function () {
  31191. return this._needDepthPrePass;
  31192. },
  31193. /**
  31194. * Sets the need depth pre-pass value.
  31195. */
  31196. set: function (value) {
  31197. if (this._needDepthPrePass === value) {
  31198. return;
  31199. }
  31200. this._needDepthPrePass = value;
  31201. if (this._needDepthPrePass) {
  31202. this.checkReadyOnEveryCall = true;
  31203. }
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Material.prototype, "fogEnabled", {
  31209. /**
  31210. * Gets the value of the fog enabled state.
  31211. */
  31212. get: function () {
  31213. return this._fogEnabled;
  31214. },
  31215. /**
  31216. * Sets the state for enabling fog.
  31217. */
  31218. set: function (value) {
  31219. if (this._fogEnabled === value) {
  31220. return;
  31221. }
  31222. this._fogEnabled = value;
  31223. this.markAsDirty(Material.MiscDirtyFlag);
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Material.prototype, "wireframe", {
  31229. /**
  31230. * Gets a value specifying if wireframe mode is enabled.
  31231. */
  31232. get: function () {
  31233. return this._fillMode === Material.WireFrameFillMode;
  31234. },
  31235. /**
  31236. * Sets the state of wireframe mode.
  31237. */
  31238. set: function (value) {
  31239. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(Material.prototype, "pointsCloud", {
  31245. /**
  31246. * Gets the value specifying if point clouds are enabled.
  31247. */
  31248. get: function () {
  31249. return this._fillMode === Material.PointFillMode;
  31250. },
  31251. /**
  31252. * Sets the state of point cloud mode.
  31253. */
  31254. set: function (value) {
  31255. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Object.defineProperty(Material.prototype, "fillMode", {
  31261. /**
  31262. * Gets the material fill mode.
  31263. */
  31264. get: function () {
  31265. return this._fillMode;
  31266. },
  31267. /**
  31268. * Sets the material fill mode.
  31269. */
  31270. set: function (value) {
  31271. if (this._fillMode === value) {
  31272. return;
  31273. }
  31274. this._fillMode = value;
  31275. this.markAsDirty(Material.MiscDirtyFlag);
  31276. },
  31277. enumerable: true,
  31278. configurable: true
  31279. });
  31280. /**
  31281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31282. * subclasses should override adding information pertainent to themselves.
  31283. * @returns - String with material information.
  31284. */
  31285. Material.prototype.toString = function (fullDetails) {
  31286. var ret = "Name: " + this.name;
  31287. if (fullDetails) {
  31288. }
  31289. return ret;
  31290. };
  31291. /**
  31292. * Gets the class name of the material.
  31293. * @returns - String with the class name of the material.
  31294. */
  31295. Material.prototype.getClassName = function () {
  31296. return "Material";
  31297. };
  31298. Object.defineProperty(Material.prototype, "isFrozen", {
  31299. /**
  31300. * Specifies if updates for the material been locked.
  31301. */
  31302. get: function () {
  31303. return this.checkReadyOnlyOnce;
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. /**
  31309. * Locks updates for the material.
  31310. */
  31311. Material.prototype.freeze = function () {
  31312. this.checkReadyOnlyOnce = true;
  31313. };
  31314. /**
  31315. * Unlocks updates for the material.
  31316. */
  31317. Material.prototype.unfreeze = function () {
  31318. this.checkReadyOnlyOnce = false;
  31319. };
  31320. /**
  31321. * Specifies if the material is ready to be used.
  31322. * @param mesh - BJS mesh.
  31323. * @param useInstances - Specifies if instances should be used.
  31324. * @returns - Boolean indicating if the material is ready to be used.
  31325. */
  31326. Material.prototype.isReady = function (mesh, useInstances) {
  31327. return true;
  31328. };
  31329. /**
  31330. * Specifies that the submesh is ready to be used.
  31331. * @param mesh - BJS mesh.
  31332. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31333. * @param useInstances - Specifies that instances should be used.
  31334. * @returns - boolean indicating that the submesh is ready or not.
  31335. */
  31336. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31337. return false;
  31338. };
  31339. /**
  31340. * Returns the material effect.
  31341. * @returns - Nullable material effect.
  31342. */
  31343. Material.prototype.getEffect = function () {
  31344. return this._effect;
  31345. };
  31346. /**
  31347. * Returns the BJS scene.
  31348. * @returns - BJS Scene.
  31349. */
  31350. Material.prototype.getScene = function () {
  31351. return this._scene;
  31352. };
  31353. /**
  31354. * Specifies if the material will require alpha blending
  31355. * @returns - Boolean specifying if alpha blending is needed.
  31356. */
  31357. Material.prototype.needAlphaBlending = function () {
  31358. return (this.alpha < 1.0);
  31359. };
  31360. /**
  31361. * Specifies if the mesh will require alpha blending.
  31362. * @param mesh - BJS mesh.
  31363. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31364. */
  31365. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31366. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31367. };
  31368. /**
  31369. * Specifies if this material should be rendered in alpha test mode.
  31370. * @returns - Boolean specifying if an alpha test is needed.
  31371. */
  31372. Material.prototype.needAlphaTesting = function () {
  31373. return false;
  31374. };
  31375. /**
  31376. * Gets the texture used for the alpha test.
  31377. * @returns - Nullable alpha test texture.
  31378. */
  31379. Material.prototype.getAlphaTestTexture = function () {
  31380. return null;
  31381. };
  31382. /**
  31383. * Marks the material to indicate that it needs to be re-calculated.
  31384. */
  31385. Material.prototype.markDirty = function () {
  31386. this._wasPreviouslyReady = false;
  31387. };
  31388. Material.prototype._preBind = function (effect, overrideOrientation) {
  31389. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31390. var engine = this._scene.getEngine();
  31391. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31392. var reverse = orientation === Material.ClockWiseSideOrientation;
  31393. engine.enableEffect(effect ? effect : this._effect);
  31394. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31395. return reverse;
  31396. };
  31397. /**
  31398. * Binds the material to the mesh.
  31399. * @param world - World transformation matrix.
  31400. * @param mesh - Mesh to bind the material to.
  31401. */
  31402. Material.prototype.bind = function (world, mesh) {
  31403. };
  31404. /**
  31405. * Binds the submesh to the material.
  31406. * @param world - World transformation matrix.
  31407. * @param mesh - Mesh containing the submesh.
  31408. * @param subMesh - Submesh to bind the material to.
  31409. */
  31410. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31411. };
  31412. /**
  31413. * Binds the world matrix to the material.
  31414. * @param world - World transformation matrix.
  31415. */
  31416. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31417. };
  31418. /**
  31419. * Binds the scene's uniform buffer to the effect.
  31420. * @param effect - Effect to bind to the scene uniform buffer.
  31421. * @param sceneUbo - Scene uniform buffer.
  31422. */
  31423. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31424. sceneUbo.bindToEffect(effect, "Scene");
  31425. };
  31426. /**
  31427. * Binds the view matrix to the effect.
  31428. * @param effect - Effect to bind the view matrix to.
  31429. */
  31430. Material.prototype.bindView = function (effect) {
  31431. if (!this._useUBO) {
  31432. effect.setMatrix("view", this.getScene().getViewMatrix());
  31433. }
  31434. else {
  31435. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31436. }
  31437. };
  31438. /**
  31439. * Binds the view projection matrix to the effect.
  31440. * @param effect - Effect to bind the view projection matrix to.
  31441. */
  31442. Material.prototype.bindViewProjection = function (effect) {
  31443. if (!this._useUBO) {
  31444. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31445. }
  31446. else {
  31447. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31448. }
  31449. };
  31450. /**
  31451. * Specifies if material alpha testing should be turned on for the mesh.
  31452. * @param mesh - BJS mesh.
  31453. */
  31454. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31455. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31456. };
  31457. /**
  31458. * Processes to execute after binding the material to a mesh.
  31459. * @param mesh - BJS mesh.
  31460. */
  31461. Material.prototype._afterBind = function (mesh) {
  31462. this._scene._cachedMaterial = this;
  31463. if (mesh) {
  31464. this._scene._cachedVisibility = mesh.visibility;
  31465. }
  31466. else {
  31467. this._scene._cachedVisibility = 1;
  31468. }
  31469. if (mesh) {
  31470. this.onBindObservable.notifyObservers(mesh);
  31471. }
  31472. if (this.disableDepthWrite) {
  31473. var engine = this._scene.getEngine();
  31474. this._cachedDepthWriteState = engine.getDepthWrite();
  31475. engine.setDepthWrite(false);
  31476. }
  31477. };
  31478. /**
  31479. * Unbinds the material from the mesh.
  31480. */
  31481. Material.prototype.unbind = function () {
  31482. this.onUnBindObservable.notifyObservers(this);
  31483. if (this.disableDepthWrite) {
  31484. var engine = this._scene.getEngine();
  31485. engine.setDepthWrite(this._cachedDepthWriteState);
  31486. }
  31487. };
  31488. /**
  31489. * Gets the active textures from the material.
  31490. * @returns - Array of textures.
  31491. */
  31492. Material.prototype.getActiveTextures = function () {
  31493. return [];
  31494. };
  31495. /**
  31496. * Specifies if the material uses a texture.
  31497. * @param texture - Texture to check against the material.
  31498. * @returns - Boolean specifying if the material uses the texture.
  31499. */
  31500. Material.prototype.hasTexture = function (texture) {
  31501. return false;
  31502. };
  31503. /**
  31504. * Makes a duplicate of the material, and gives it a new name.
  31505. * @param name - Name to call the duplicated material.
  31506. * @returns - Nullable cloned material
  31507. */
  31508. Material.prototype.clone = function (name) {
  31509. return null;
  31510. };
  31511. /**
  31512. * Gets the meshes bound to the material.
  31513. * @returns - Array of meshes bound to the material.
  31514. */
  31515. Material.prototype.getBindedMeshes = function () {
  31516. var result = new Array();
  31517. for (var index = 0; index < this._scene.meshes.length; index++) {
  31518. var mesh = this._scene.meshes[index];
  31519. if (mesh.material === this) {
  31520. result.push(mesh);
  31521. }
  31522. }
  31523. return result;
  31524. };
  31525. /**
  31526. * Force shader compilation
  31527. * @param mesh - BJS mesh.
  31528. * @param onCompiled - function to execute once the material is compiled.
  31529. * @param options - options to pass to this function.
  31530. */
  31531. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31532. var _this = this;
  31533. var localOptions = __assign({ clipPlane: false }, options);
  31534. var subMesh = new BABYLON.BaseSubMesh();
  31535. var scene = this.getScene();
  31536. var checkReady = function () {
  31537. if (!_this._scene || !_this._scene.getEngine()) {
  31538. return;
  31539. }
  31540. if (subMesh._materialDefines) {
  31541. subMesh._materialDefines._renderId = -1;
  31542. }
  31543. var clipPlaneState = scene.clipPlane;
  31544. if (localOptions.clipPlane) {
  31545. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31546. }
  31547. if (_this.storeEffectOnSubMeshes) {
  31548. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31549. if (onCompiled) {
  31550. onCompiled(_this);
  31551. }
  31552. }
  31553. else {
  31554. setTimeout(checkReady, 16);
  31555. }
  31556. }
  31557. else {
  31558. if (_this.isReady(mesh)) {
  31559. if (onCompiled) {
  31560. onCompiled(_this);
  31561. }
  31562. }
  31563. else {
  31564. setTimeout(checkReady, 16);
  31565. }
  31566. }
  31567. if (localOptions.clipPlane) {
  31568. scene.clipPlane = clipPlaneState;
  31569. }
  31570. };
  31571. checkReady();
  31572. };
  31573. /**
  31574. * Force shader compilation.
  31575. * @param mesh The mesh that will use this material
  31576. * @param options Additional options for compiling the shaders
  31577. * @returns A promise that resolves when the compilation completes
  31578. */
  31579. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31580. var _this = this;
  31581. return new Promise(function (resolve) {
  31582. _this.forceCompilation(mesh, function () {
  31583. resolve();
  31584. }, options);
  31585. });
  31586. };
  31587. /**
  31588. * Marks a define in the material to indicate that it needs to be re-computed.
  31589. * @param flag - Material define flag.
  31590. */
  31591. Material.prototype.markAsDirty = function (flag) {
  31592. if (flag & Material.TextureDirtyFlag) {
  31593. this._markAllSubMeshesAsTexturesDirty();
  31594. }
  31595. if (flag & Material.LightDirtyFlag) {
  31596. this._markAllSubMeshesAsLightsDirty();
  31597. }
  31598. if (flag & Material.FresnelDirtyFlag) {
  31599. this._markAllSubMeshesAsFresnelDirty();
  31600. }
  31601. if (flag & Material.AttributesDirtyFlag) {
  31602. this._markAllSubMeshesAsAttributesDirty();
  31603. }
  31604. if (flag & Material.MiscDirtyFlag) {
  31605. this._markAllSubMeshesAsMiscDirty();
  31606. }
  31607. this.getScene().resetCachedMaterial();
  31608. };
  31609. /**
  31610. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31611. * @param func - function which checks material defines against the submeshes.
  31612. */
  31613. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31614. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31615. var mesh = _a[_i];
  31616. if (!mesh.subMeshes) {
  31617. continue;
  31618. }
  31619. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31620. var subMesh = _c[_b];
  31621. if (subMesh.getMaterial() !== this) {
  31622. continue;
  31623. }
  31624. if (!subMesh._materialDefines) {
  31625. continue;
  31626. }
  31627. func(subMesh._materialDefines);
  31628. }
  31629. }
  31630. };
  31631. /**
  31632. * Indicates that image processing needs to be re-calculated for all submeshes.
  31633. */
  31634. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31635. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31636. };
  31637. /**
  31638. * Indicates that textures need to be re-calculated for all submeshes.
  31639. */
  31640. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31641. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31642. };
  31643. /**
  31644. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31645. */
  31646. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31647. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31648. };
  31649. /**
  31650. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31651. */
  31652. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31653. this._markAllSubMeshesAsDirty(function (defines) {
  31654. defines.markAsFresnelDirty();
  31655. defines.markAsMiscDirty();
  31656. });
  31657. };
  31658. /**
  31659. * Indicates that lights need to be re-calculated for all submeshes.
  31660. */
  31661. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31662. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31663. };
  31664. /**
  31665. * Indicates that attributes need to be re-calculated for all submeshes.
  31666. */
  31667. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31668. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31669. };
  31670. /**
  31671. * Indicates that misc needs to be re-calculated for all submeshes.
  31672. */
  31673. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31674. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31675. };
  31676. /**
  31677. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31678. */
  31679. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31680. this._markAllSubMeshesAsDirty(function (defines) {
  31681. defines.markAsTexturesDirty();
  31682. defines.markAsMiscDirty();
  31683. });
  31684. };
  31685. /**
  31686. * Disposes the material.
  31687. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31688. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31689. */
  31690. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31691. // Animations
  31692. this.getScene().stopAnimation(this);
  31693. // Remove from scene
  31694. var index = this._scene.materials.indexOf(this);
  31695. if (index >= 0) {
  31696. this._scene.materials.splice(index, 1);
  31697. }
  31698. // Remove from meshes
  31699. for (index = 0; index < this._scene.meshes.length; index++) {
  31700. var mesh = this._scene.meshes[index];
  31701. if (mesh.material === this) {
  31702. mesh.material = null;
  31703. if (mesh.geometry) {
  31704. var geometry = (mesh.geometry);
  31705. if (this.storeEffectOnSubMeshes) {
  31706. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31707. var subMesh = _a[_i];
  31708. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31709. if (forceDisposeEffect && subMesh._materialEffect) {
  31710. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31711. }
  31712. }
  31713. }
  31714. else {
  31715. geometry._releaseVertexArrayObject(this._effect);
  31716. }
  31717. }
  31718. }
  31719. }
  31720. this._uniformBuffer.dispose();
  31721. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31722. if (forceDisposeEffect && this._effect) {
  31723. if (!this.storeEffectOnSubMeshes) {
  31724. this._scene.getEngine()._releaseEffect(this._effect);
  31725. }
  31726. this._effect = null;
  31727. }
  31728. // Callback
  31729. this.onDisposeObservable.notifyObservers(this);
  31730. this.onDisposeObservable.clear();
  31731. this.onBindObservable.clear();
  31732. this.onUnBindObservable.clear();
  31733. };
  31734. /**
  31735. * Serializes this material.
  31736. * @returns - serialized material object.
  31737. */
  31738. Material.prototype.serialize = function () {
  31739. return BABYLON.SerializationHelper.Serialize(this);
  31740. };
  31741. /**
  31742. * Creates a MultiMaterial from parse MultiMaterial data.
  31743. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31744. * @param scene - BJS scene.
  31745. * @returns - MultiMaterial.
  31746. */
  31747. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31748. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31749. multiMaterial.id = parsedMultiMaterial.id;
  31750. if (BABYLON.Tags) {
  31751. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31752. }
  31753. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31754. var subMatId = parsedMultiMaterial.materials[matIndex];
  31755. if (subMatId) {
  31756. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31757. }
  31758. else {
  31759. multiMaterial.subMaterials.push(null);
  31760. }
  31761. }
  31762. return multiMaterial;
  31763. };
  31764. /**
  31765. * Creates a material from parsed material data.
  31766. * @param parsedMaterial - Parsed material data.
  31767. * @param scene - BJS scene.
  31768. * @param rootUrl - Root URL containing the material information.
  31769. * @returns - Parsed material.
  31770. */
  31771. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31772. if (!parsedMaterial.customType) {
  31773. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31774. }
  31775. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31776. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31777. if (!BABYLON.LegacyPBRMaterial) {
  31778. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31779. return;
  31780. }
  31781. }
  31782. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31783. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31784. ;
  31785. };
  31786. // Triangle views
  31787. Material._TriangleFillMode = 0;
  31788. Material._WireFrameFillMode = 1;
  31789. Material._PointFillMode = 2;
  31790. // Draw modes
  31791. Material._PointListDrawMode = 3;
  31792. Material._LineListDrawMode = 4;
  31793. Material._LineLoopDrawMode = 5;
  31794. Material._LineStripDrawMode = 6;
  31795. Material._TriangleStripDrawMode = 7;
  31796. Material._TriangleFanDrawMode = 8;
  31797. /**
  31798. * Stores the clock-wise side orientation.
  31799. */
  31800. Material._ClockWiseSideOrientation = 0;
  31801. /**
  31802. * Stores the counter clock-wise side orientation.
  31803. */
  31804. Material._CounterClockWiseSideOrientation = 1;
  31805. /**
  31806. * The dirty texture flag value.
  31807. */
  31808. Material._TextureDirtyFlag = 1;
  31809. /**
  31810. * The dirty light flag value.
  31811. */
  31812. Material._LightDirtyFlag = 2;
  31813. /**
  31814. * The dirty fresnel flag value.
  31815. */
  31816. Material._FresnelDirtyFlag = 4;
  31817. /**
  31818. * The dirty attribute flag value.
  31819. */
  31820. Material._AttributesDirtyFlag = 8;
  31821. /**
  31822. * The dirty misc flag value.
  31823. */
  31824. Material._MiscDirtyFlag = 16;
  31825. __decorate([
  31826. BABYLON.serialize()
  31827. ], Material.prototype, "id", void 0);
  31828. __decorate([
  31829. BABYLON.serialize()
  31830. ], Material.prototype, "name", void 0);
  31831. __decorate([
  31832. BABYLON.serialize()
  31833. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31834. __decorate([
  31835. BABYLON.serialize()
  31836. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31837. __decorate([
  31838. BABYLON.serialize()
  31839. ], Material.prototype, "state", void 0);
  31840. __decorate([
  31841. BABYLON.serialize("alpha")
  31842. ], Material.prototype, "_alpha", void 0);
  31843. __decorate([
  31844. BABYLON.serialize("backFaceCulling")
  31845. ], Material.prototype, "_backFaceCulling", void 0);
  31846. __decorate([
  31847. BABYLON.serialize()
  31848. ], Material.prototype, "sideOrientation", void 0);
  31849. __decorate([
  31850. BABYLON.serialize("alphaMode")
  31851. ], Material.prototype, "_alphaMode", void 0);
  31852. __decorate([
  31853. BABYLON.serialize()
  31854. ], Material.prototype, "_needDepthPrePass", void 0);
  31855. __decorate([
  31856. BABYLON.serialize()
  31857. ], Material.prototype, "disableDepthWrite", void 0);
  31858. __decorate([
  31859. BABYLON.serialize()
  31860. ], Material.prototype, "forceDepthWrite", void 0);
  31861. __decorate([
  31862. BABYLON.serialize()
  31863. ], Material.prototype, "separateCullingPass", void 0);
  31864. __decorate([
  31865. BABYLON.serialize("fogEnabled")
  31866. ], Material.prototype, "_fogEnabled", void 0);
  31867. __decorate([
  31868. BABYLON.serialize()
  31869. ], Material.prototype, "pointSize", void 0);
  31870. __decorate([
  31871. BABYLON.serialize()
  31872. ], Material.prototype, "zOffset", void 0);
  31873. __decorate([
  31874. BABYLON.serialize()
  31875. ], Material.prototype, "wireframe", null);
  31876. __decorate([
  31877. BABYLON.serialize()
  31878. ], Material.prototype, "pointsCloud", null);
  31879. __decorate([
  31880. BABYLON.serialize()
  31881. ], Material.prototype, "fillMode", null);
  31882. return Material;
  31883. }());
  31884. BABYLON.Material = Material;
  31885. })(BABYLON || (BABYLON = {}));
  31886. //# sourceMappingURL=babylon.material.js.map
  31887. var BABYLON;
  31888. (function (BABYLON) {
  31889. var UniformBuffer = /** @class */ (function () {
  31890. /**
  31891. * Uniform buffer objects.
  31892. *
  31893. * Handles blocks of uniform on the GPU.
  31894. *
  31895. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31896. *
  31897. * For more information, please refer to :
  31898. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31899. */
  31900. function UniformBuffer(engine, data, dynamic) {
  31901. this._engine = engine;
  31902. this._noUBO = !engine.supportsUniformBuffers;
  31903. this._dynamic = dynamic;
  31904. this._data = data || [];
  31905. this._uniformLocations = {};
  31906. this._uniformSizes = {};
  31907. this._uniformLocationPointer = 0;
  31908. this._needSync = false;
  31909. if (this._noUBO) {
  31910. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31911. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31912. this.updateFloat = this._updateFloatForEffect;
  31913. this.updateFloat2 = this._updateFloat2ForEffect;
  31914. this.updateFloat3 = this._updateFloat3ForEffect;
  31915. this.updateFloat4 = this._updateFloat4ForEffect;
  31916. this.updateMatrix = this._updateMatrixForEffect;
  31917. this.updateVector3 = this._updateVector3ForEffect;
  31918. this.updateVector4 = this._updateVector4ForEffect;
  31919. this.updateColor3 = this._updateColor3ForEffect;
  31920. this.updateColor4 = this._updateColor4ForEffect;
  31921. }
  31922. else {
  31923. this._engine._uniformBuffers.push(this);
  31924. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31925. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31926. this.updateFloat = this._updateFloatForUniform;
  31927. this.updateFloat2 = this._updateFloat2ForUniform;
  31928. this.updateFloat3 = this._updateFloat3ForUniform;
  31929. this.updateFloat4 = this._updateFloat4ForUniform;
  31930. this.updateMatrix = this._updateMatrixForUniform;
  31931. this.updateVector3 = this._updateVector3ForUniform;
  31932. this.updateVector4 = this._updateVector4ForUniform;
  31933. this.updateColor3 = this._updateColor3ForUniform;
  31934. this.updateColor4 = this._updateColor4ForUniform;
  31935. }
  31936. }
  31937. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31938. // Properties
  31939. /**
  31940. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31941. * or just falling back on setUniformXXX calls.
  31942. */
  31943. get: function () {
  31944. return !this._noUBO;
  31945. },
  31946. enumerable: true,
  31947. configurable: true
  31948. });
  31949. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31950. /**
  31951. * Indicates if the WebGL underlying uniform buffer is in sync
  31952. * with the javascript cache data.
  31953. */
  31954. get: function () {
  31955. return !this._needSync;
  31956. },
  31957. enumerable: true,
  31958. configurable: true
  31959. });
  31960. /**
  31961. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31962. * Also, a dynamic UniformBuffer will disable cache verification and always
  31963. * update the underlying WebGL uniform buffer to the GPU.
  31964. */
  31965. UniformBuffer.prototype.isDynamic = function () {
  31966. return this._dynamic !== undefined;
  31967. };
  31968. /**
  31969. * The data cache on JS side.
  31970. */
  31971. UniformBuffer.prototype.getData = function () {
  31972. return this._bufferData;
  31973. };
  31974. /**
  31975. * The underlying WebGL Uniform buffer.
  31976. */
  31977. UniformBuffer.prototype.getBuffer = function () {
  31978. return this._buffer;
  31979. };
  31980. /**
  31981. * std140 layout specifies how to align data within an UBO structure.
  31982. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31983. * for specs.
  31984. */
  31985. UniformBuffer.prototype._fillAlignment = function (size) {
  31986. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31987. // and 4x4 matrices
  31988. // TODO : change if other types are used
  31989. var alignment;
  31990. if (size <= 2) {
  31991. alignment = size;
  31992. }
  31993. else {
  31994. alignment = 4;
  31995. }
  31996. if ((this._uniformLocationPointer % alignment) !== 0) {
  31997. var oldPointer = this._uniformLocationPointer;
  31998. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31999. var diff = this._uniformLocationPointer - oldPointer;
  32000. for (var i = 0; i < diff; i++) {
  32001. this._data.push(0);
  32002. }
  32003. }
  32004. };
  32005. /**
  32006. * Adds an uniform in the buffer.
  32007. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32008. * for the layout to be correct !
  32009. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32010. * @param {number|number[]} size Data size, or data directly.
  32011. */
  32012. UniformBuffer.prototype.addUniform = function (name, size) {
  32013. if (this._noUBO) {
  32014. return;
  32015. }
  32016. if (this._uniformLocations[name] !== undefined) {
  32017. // Already existing uniform
  32018. return;
  32019. }
  32020. // This function must be called in the order of the shader layout !
  32021. // size can be the size of the uniform, or data directly
  32022. var data;
  32023. if (size instanceof Array) {
  32024. data = size;
  32025. size = data.length;
  32026. }
  32027. else {
  32028. size = size;
  32029. data = [];
  32030. // Fill with zeros
  32031. for (var i = 0; i < size; i++) {
  32032. data.push(0);
  32033. }
  32034. }
  32035. this._fillAlignment(size);
  32036. this._uniformSizes[name] = size;
  32037. this._uniformLocations[name] = this._uniformLocationPointer;
  32038. this._uniformLocationPointer += size;
  32039. for (var i = 0; i < size; i++) {
  32040. this._data.push(data[i]);
  32041. }
  32042. this._needSync = true;
  32043. };
  32044. /**
  32045. * Wrapper for addUniform.
  32046. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32047. * @param {Matrix} mat A 4x4 matrix.
  32048. */
  32049. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32050. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32051. };
  32052. /**
  32053. * Wrapper for addUniform.
  32054. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32055. * @param {number} x
  32056. * @param {number} y
  32057. */
  32058. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32059. var temp = [x, y];
  32060. this.addUniform(name, temp);
  32061. };
  32062. /**
  32063. * Wrapper for addUniform.
  32064. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32065. * @param {number} x
  32066. * @param {number} y
  32067. * @param {number} z
  32068. */
  32069. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32070. var temp = [x, y, z];
  32071. this.addUniform(name, temp);
  32072. };
  32073. /**
  32074. * Wrapper for addUniform.
  32075. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32076. * @param {Color3} color
  32077. */
  32078. UniformBuffer.prototype.addColor3 = function (name, color) {
  32079. var temp = new Array();
  32080. color.toArray(temp);
  32081. this.addUniform(name, temp);
  32082. };
  32083. /**
  32084. * Wrapper for addUniform.
  32085. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32086. * @param {Color3} color
  32087. * @param {number} alpha
  32088. */
  32089. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32090. var temp = new Array();
  32091. color.toArray(temp);
  32092. temp.push(alpha);
  32093. this.addUniform(name, temp);
  32094. };
  32095. /**
  32096. * Wrapper for addUniform.
  32097. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32098. * @param {Vector3} vector
  32099. */
  32100. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32101. var temp = new Array();
  32102. vector.toArray(temp);
  32103. this.addUniform(name, temp);
  32104. };
  32105. /**
  32106. * Wrapper for addUniform.
  32107. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32108. */
  32109. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32110. this.addUniform(name, 12);
  32111. };
  32112. /**
  32113. * Wrapper for addUniform.
  32114. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32115. */
  32116. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32117. this.addUniform(name, 8);
  32118. };
  32119. /**
  32120. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32121. */
  32122. UniformBuffer.prototype.create = function () {
  32123. if (this._noUBO) {
  32124. return;
  32125. }
  32126. if (this._buffer) {
  32127. return; // nothing to do
  32128. }
  32129. // See spec, alignment must be filled as a vec4
  32130. this._fillAlignment(4);
  32131. this._bufferData = new Float32Array(this._data);
  32132. this._rebuild();
  32133. this._needSync = true;
  32134. };
  32135. UniformBuffer.prototype._rebuild = function () {
  32136. if (this._noUBO) {
  32137. return;
  32138. }
  32139. if (this._dynamic) {
  32140. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32141. }
  32142. else {
  32143. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32144. }
  32145. };
  32146. /**
  32147. * Updates the WebGL Uniform Buffer on the GPU.
  32148. * If the `dynamic` flag is set to true, no cache comparison is done.
  32149. * Otherwise, the buffer will be updated only if the cache differs.
  32150. */
  32151. UniformBuffer.prototype.update = function () {
  32152. if (!this._buffer) {
  32153. this.create();
  32154. return;
  32155. }
  32156. if (!this._dynamic && !this._needSync) {
  32157. return;
  32158. }
  32159. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32160. this._needSync = false;
  32161. };
  32162. /**
  32163. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32164. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32165. * @param {number[]|Float32Array} data Flattened data
  32166. * @param {number} size Size of the data.
  32167. */
  32168. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32169. var location = this._uniformLocations[uniformName];
  32170. if (location === undefined) {
  32171. if (this._buffer) {
  32172. // Cannot add an uniform if the buffer is already created
  32173. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32174. return;
  32175. }
  32176. this.addUniform(uniformName, size);
  32177. location = this._uniformLocations[uniformName];
  32178. }
  32179. if (!this._buffer) {
  32180. this.create();
  32181. }
  32182. if (!this._dynamic) {
  32183. // Cache for static uniform buffers
  32184. var changed = false;
  32185. for (var i = 0; i < size; i++) {
  32186. if (this._bufferData[location + i] !== data[i]) {
  32187. changed = true;
  32188. this._bufferData[location + i] = data[i];
  32189. }
  32190. }
  32191. this._needSync = this._needSync || changed;
  32192. }
  32193. else {
  32194. // No cache for dynamic
  32195. for (var i = 0; i < size; i++) {
  32196. this._bufferData[location + i] = data[i];
  32197. }
  32198. }
  32199. };
  32200. // Update methods
  32201. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32202. // To match std140, matrix must be realigned
  32203. for (var i = 0; i < 3; i++) {
  32204. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32205. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32206. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32207. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32208. }
  32209. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32210. };
  32211. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32212. this._currentEffect.setMatrix3x3(name, matrix);
  32213. };
  32214. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32215. this._currentEffect.setMatrix2x2(name, matrix);
  32216. };
  32217. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32218. // To match std140, matrix must be realigned
  32219. for (var i = 0; i < 2; i++) {
  32220. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32221. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32222. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32223. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32224. }
  32225. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32226. };
  32227. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32228. this._currentEffect.setFloat(name, x);
  32229. };
  32230. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32231. UniformBuffer._tempBuffer[0] = x;
  32232. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32233. };
  32234. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32235. if (suffix === void 0) { suffix = ""; }
  32236. this._currentEffect.setFloat2(name + suffix, x, y);
  32237. };
  32238. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32239. if (suffix === void 0) { suffix = ""; }
  32240. UniformBuffer._tempBuffer[0] = x;
  32241. UniformBuffer._tempBuffer[1] = y;
  32242. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32243. };
  32244. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32245. if (suffix === void 0) { suffix = ""; }
  32246. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32247. };
  32248. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32249. if (suffix === void 0) { suffix = ""; }
  32250. UniformBuffer._tempBuffer[0] = x;
  32251. UniformBuffer._tempBuffer[1] = y;
  32252. UniformBuffer._tempBuffer[2] = z;
  32253. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32254. };
  32255. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32256. if (suffix === void 0) { suffix = ""; }
  32257. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32258. };
  32259. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32260. if (suffix === void 0) { suffix = ""; }
  32261. UniformBuffer._tempBuffer[0] = x;
  32262. UniformBuffer._tempBuffer[1] = y;
  32263. UniformBuffer._tempBuffer[2] = z;
  32264. UniformBuffer._tempBuffer[3] = w;
  32265. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32266. };
  32267. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32268. this._currentEffect.setMatrix(name, mat);
  32269. };
  32270. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32271. this.updateUniform(name, mat.toArray(), 16);
  32272. };
  32273. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32274. this._currentEffect.setVector3(name, vector);
  32275. };
  32276. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32277. vector.toArray(UniformBuffer._tempBuffer);
  32278. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32279. };
  32280. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32281. this._currentEffect.setVector4(name, vector);
  32282. };
  32283. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32284. vector.toArray(UniformBuffer._tempBuffer);
  32285. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32286. };
  32287. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32288. if (suffix === void 0) { suffix = ""; }
  32289. this._currentEffect.setColor3(name + suffix, color);
  32290. };
  32291. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32292. if (suffix === void 0) { suffix = ""; }
  32293. color.toArray(UniformBuffer._tempBuffer);
  32294. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32295. };
  32296. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32297. if (suffix === void 0) { suffix = ""; }
  32298. this._currentEffect.setColor4(name + suffix, color, alpha);
  32299. };
  32300. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32301. if (suffix === void 0) { suffix = ""; }
  32302. color.toArray(UniformBuffer._tempBuffer);
  32303. UniformBuffer._tempBuffer[3] = alpha;
  32304. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32305. };
  32306. /**
  32307. * Sets a sampler uniform on the effect.
  32308. * @param {string} name Name of the sampler.
  32309. * @param {Texture} texture
  32310. */
  32311. UniformBuffer.prototype.setTexture = function (name, texture) {
  32312. this._currentEffect.setTexture(name, texture);
  32313. };
  32314. /**
  32315. * Directly updates the value of the uniform in the cache AND on the GPU.
  32316. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32317. * @param {number[]|Float32Array} data Flattened data
  32318. */
  32319. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32320. this.updateUniform(uniformName, data, data.length);
  32321. this.update();
  32322. };
  32323. /**
  32324. * Binds this uniform buffer to an effect.
  32325. * @param {Effect} effect
  32326. * @param {string} name Name of the uniform block in the shader.
  32327. */
  32328. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32329. this._currentEffect = effect;
  32330. if (this._noUBO || !this._buffer) {
  32331. return;
  32332. }
  32333. effect.bindUniformBuffer(this._buffer, name);
  32334. };
  32335. /**
  32336. * Disposes the uniform buffer.
  32337. */
  32338. UniformBuffer.prototype.dispose = function () {
  32339. if (this._noUBO) {
  32340. return;
  32341. }
  32342. var index = this._engine._uniformBuffers.indexOf(this);
  32343. if (index !== -1) {
  32344. this._engine._uniformBuffers.splice(index, 1);
  32345. }
  32346. if (!this._buffer) {
  32347. return;
  32348. }
  32349. if (this._engine._releaseBuffer(this._buffer)) {
  32350. this._buffer = null;
  32351. }
  32352. };
  32353. // Pool for avoiding memory leaks
  32354. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32355. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32356. return UniformBuffer;
  32357. }());
  32358. BABYLON.UniformBuffer = UniformBuffer;
  32359. })(BABYLON || (BABYLON = {}));
  32360. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32361. var BABYLON;
  32362. (function (BABYLON) {
  32363. var VertexData = /** @class */ (function () {
  32364. function VertexData() {
  32365. }
  32366. VertexData.prototype.set = function (data, kind) {
  32367. switch (kind) {
  32368. case BABYLON.VertexBuffer.PositionKind:
  32369. this.positions = data;
  32370. break;
  32371. case BABYLON.VertexBuffer.NormalKind:
  32372. this.normals = data;
  32373. break;
  32374. case BABYLON.VertexBuffer.TangentKind:
  32375. this.tangents = data;
  32376. break;
  32377. case BABYLON.VertexBuffer.UVKind:
  32378. this.uvs = data;
  32379. break;
  32380. case BABYLON.VertexBuffer.UV2Kind:
  32381. this.uvs2 = data;
  32382. break;
  32383. case BABYLON.VertexBuffer.UV3Kind:
  32384. this.uvs3 = data;
  32385. break;
  32386. case BABYLON.VertexBuffer.UV4Kind:
  32387. this.uvs4 = data;
  32388. break;
  32389. case BABYLON.VertexBuffer.UV5Kind:
  32390. this.uvs5 = data;
  32391. break;
  32392. case BABYLON.VertexBuffer.UV6Kind:
  32393. this.uvs6 = data;
  32394. break;
  32395. case BABYLON.VertexBuffer.ColorKind:
  32396. this.colors = data;
  32397. break;
  32398. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32399. this.matricesIndices = data;
  32400. break;
  32401. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32402. this.matricesWeights = data;
  32403. break;
  32404. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32405. this.matricesIndicesExtra = data;
  32406. break;
  32407. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32408. this.matricesWeightsExtra = data;
  32409. break;
  32410. }
  32411. };
  32412. /**
  32413. * Associates the vertexData to the passed Mesh.
  32414. * Sets it as updatable or not (default `false`).
  32415. * Returns the VertexData.
  32416. */
  32417. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32418. this._applyTo(mesh, updatable);
  32419. return this;
  32420. };
  32421. /**
  32422. * Associates the vertexData to the passed Geometry.
  32423. * Sets it as updatable or not (default `false`).
  32424. * Returns the VertexData.
  32425. */
  32426. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32427. this._applyTo(geometry, updatable);
  32428. return this;
  32429. };
  32430. /**
  32431. * Updates the associated mesh.
  32432. * Returns the VertexData.
  32433. */
  32434. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32435. this._update(mesh);
  32436. return this;
  32437. };
  32438. /**
  32439. * Updates the associated geometry.
  32440. * Returns the VertexData.
  32441. */
  32442. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32443. this._update(geometry);
  32444. return this;
  32445. };
  32446. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32447. if (updatable === void 0) { updatable = false; }
  32448. if (this.positions) {
  32449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32450. }
  32451. if (this.normals) {
  32452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32453. }
  32454. if (this.tangents) {
  32455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32456. }
  32457. if (this.uvs) {
  32458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32459. }
  32460. if (this.uvs2) {
  32461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32462. }
  32463. if (this.uvs3) {
  32464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32465. }
  32466. if (this.uvs4) {
  32467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32468. }
  32469. if (this.uvs5) {
  32470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32471. }
  32472. if (this.uvs6) {
  32473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32474. }
  32475. if (this.colors) {
  32476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32477. }
  32478. if (this.matricesIndices) {
  32479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32480. }
  32481. if (this.matricesWeights) {
  32482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32483. }
  32484. if (this.matricesIndicesExtra) {
  32485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32486. }
  32487. if (this.matricesWeightsExtra) {
  32488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32489. }
  32490. if (this.indices) {
  32491. meshOrGeometry.setIndices(this.indices, null, updatable);
  32492. }
  32493. return this;
  32494. };
  32495. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32496. if (this.positions) {
  32497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32498. }
  32499. if (this.normals) {
  32500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32501. }
  32502. if (this.tangents) {
  32503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32504. }
  32505. if (this.uvs) {
  32506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32507. }
  32508. if (this.uvs2) {
  32509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32510. }
  32511. if (this.uvs3) {
  32512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32513. }
  32514. if (this.uvs4) {
  32515. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32516. }
  32517. if (this.uvs5) {
  32518. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32519. }
  32520. if (this.uvs6) {
  32521. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32522. }
  32523. if (this.colors) {
  32524. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32525. }
  32526. if (this.matricesIndices) {
  32527. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32528. }
  32529. if (this.matricesWeights) {
  32530. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32531. }
  32532. if (this.matricesIndicesExtra) {
  32533. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32534. }
  32535. if (this.matricesWeightsExtra) {
  32536. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32537. }
  32538. if (this.indices) {
  32539. meshOrGeometry.setIndices(this.indices, null);
  32540. }
  32541. return this;
  32542. };
  32543. /**
  32544. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32545. * Returns the VertexData.
  32546. */
  32547. VertexData.prototype.transform = function (matrix) {
  32548. var transformed = BABYLON.Vector3.Zero();
  32549. var index;
  32550. if (this.positions) {
  32551. var position = BABYLON.Vector3.Zero();
  32552. for (index = 0; index < this.positions.length; index += 3) {
  32553. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32554. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32555. this.positions[index] = transformed.x;
  32556. this.positions[index + 1] = transformed.y;
  32557. this.positions[index + 2] = transformed.z;
  32558. }
  32559. }
  32560. if (this.normals) {
  32561. var normal = BABYLON.Vector3.Zero();
  32562. for (index = 0; index < this.normals.length; index += 3) {
  32563. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32564. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32565. this.normals[index] = transformed.x;
  32566. this.normals[index + 1] = transformed.y;
  32567. this.normals[index + 2] = transformed.z;
  32568. }
  32569. }
  32570. if (this.tangents) {
  32571. var tangent = BABYLON.Vector4.Zero();
  32572. var tangentTransformed = BABYLON.Vector4.Zero();
  32573. for (index = 0; index < this.tangents.length; index += 4) {
  32574. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32575. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32576. this.tangents[index] = tangentTransformed.x;
  32577. this.tangents[index + 1] = tangentTransformed.y;
  32578. this.tangents[index + 2] = tangentTransformed.z;
  32579. this.tangents[index + 3] = tangentTransformed.w;
  32580. }
  32581. }
  32582. return this;
  32583. };
  32584. /**
  32585. * Merges the passed VertexData into the current one.
  32586. * Returns the modified VertexData.
  32587. */
  32588. VertexData.prototype.merge = function (other) {
  32589. this._validate();
  32590. other._validate();
  32591. if (!this.normals !== !other.normals ||
  32592. !this.tangents !== !other.tangents ||
  32593. !this.uvs !== !other.uvs ||
  32594. !this.uvs2 !== !other.uvs2 ||
  32595. !this.uvs3 !== !other.uvs3 ||
  32596. !this.uvs4 !== !other.uvs4 ||
  32597. !this.uvs5 !== !other.uvs5 ||
  32598. !this.uvs6 !== !other.uvs6 ||
  32599. !this.colors !== !other.colors ||
  32600. !this.matricesIndices !== !other.matricesIndices ||
  32601. !this.matricesWeights !== !other.matricesWeights ||
  32602. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32603. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32604. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32605. }
  32606. if (other.indices) {
  32607. if (!this.indices) {
  32608. this.indices = [];
  32609. }
  32610. var offset = this.positions ? this.positions.length / 3 : 0;
  32611. for (var index = 0; index < other.indices.length; index++) {
  32612. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32613. this.indices.push(other.indices[index] + offset);
  32614. }
  32615. }
  32616. this.positions = this._mergeElement(this.positions, other.positions);
  32617. this.normals = this._mergeElement(this.normals, other.normals);
  32618. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32619. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32620. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32621. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32622. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32623. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32624. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32625. this.colors = this._mergeElement(this.colors, other.colors);
  32626. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32627. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32628. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32629. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32630. return this;
  32631. };
  32632. VertexData.prototype._mergeElement = function (source, other) {
  32633. if (!source) {
  32634. return other;
  32635. }
  32636. if (!other) {
  32637. return source;
  32638. }
  32639. var len = other.length + source.length;
  32640. var isSrcTypedArray = source instanceof Float32Array;
  32641. var isOthTypedArray = other instanceof Float32Array;
  32642. // use non-loop method when the source is Float32Array
  32643. if (isSrcTypedArray) {
  32644. var ret32 = new Float32Array(len);
  32645. ret32.set(source);
  32646. ret32.set(other, source.length);
  32647. return ret32;
  32648. // source is number[], when other is also use concat
  32649. }
  32650. else if (!isOthTypedArray) {
  32651. return source.concat(other);
  32652. // source is a number[], but other is a Float32Array, loop required
  32653. }
  32654. else {
  32655. var ret = source.slice(0); // copy source to a separate array
  32656. for (var i = 0, len = other.length; i < len; i++) {
  32657. ret.push(other[i]);
  32658. }
  32659. return ret;
  32660. }
  32661. };
  32662. VertexData.prototype._validate = function () {
  32663. if (!this.positions) {
  32664. throw new Error("Positions are required");
  32665. }
  32666. var getElementCount = function (kind, values) {
  32667. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32668. if ((values.length % stride) !== 0) {
  32669. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32670. }
  32671. return values.length / stride;
  32672. };
  32673. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32674. var validateElementCount = function (kind, values) {
  32675. var elementCount = getElementCount(kind, values);
  32676. if (elementCount !== positionsElementCount) {
  32677. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32678. }
  32679. };
  32680. if (this.normals)
  32681. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32682. if (this.tangents)
  32683. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32684. if (this.uvs)
  32685. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32686. if (this.uvs2)
  32687. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32688. if (this.uvs3)
  32689. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32690. if (this.uvs4)
  32691. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32692. if (this.uvs5)
  32693. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32694. if (this.uvs6)
  32695. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32696. if (this.colors)
  32697. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32698. if (this.matricesIndices)
  32699. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32700. if (this.matricesWeights)
  32701. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32702. if (this.matricesIndicesExtra)
  32703. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32704. if (this.matricesWeightsExtra)
  32705. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32706. };
  32707. /**
  32708. * Serializes the VertexData.
  32709. * Returns a serialized object.
  32710. */
  32711. VertexData.prototype.serialize = function () {
  32712. var serializationObject = this.serialize();
  32713. if (this.positions) {
  32714. serializationObject.positions = this.positions;
  32715. }
  32716. if (this.normals) {
  32717. serializationObject.normals = this.normals;
  32718. }
  32719. if (this.tangents) {
  32720. serializationObject.tangents = this.tangents;
  32721. }
  32722. if (this.uvs) {
  32723. serializationObject.uvs = this.uvs;
  32724. }
  32725. if (this.uvs2) {
  32726. serializationObject.uvs2 = this.uvs2;
  32727. }
  32728. if (this.uvs3) {
  32729. serializationObject.uvs3 = this.uvs3;
  32730. }
  32731. if (this.uvs4) {
  32732. serializationObject.uvs4 = this.uvs4;
  32733. }
  32734. if (this.uvs5) {
  32735. serializationObject.uvs5 = this.uvs5;
  32736. }
  32737. if (this.uvs6) {
  32738. serializationObject.uvs6 = this.uvs6;
  32739. }
  32740. if (this.colors) {
  32741. serializationObject.colors = this.colors;
  32742. }
  32743. if (this.matricesIndices) {
  32744. serializationObject.matricesIndices = this.matricesIndices;
  32745. serializationObject.matricesIndices._isExpanded = true;
  32746. }
  32747. if (this.matricesWeights) {
  32748. serializationObject.matricesWeights = this.matricesWeights;
  32749. }
  32750. if (this.matricesIndicesExtra) {
  32751. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32752. serializationObject.matricesIndicesExtra._isExpanded = true;
  32753. }
  32754. if (this.matricesWeightsExtra) {
  32755. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32756. }
  32757. serializationObject.indices = this.indices;
  32758. return serializationObject;
  32759. };
  32760. // Statics
  32761. /**
  32762. * Returns the object VertexData associated to the passed mesh.
  32763. */
  32764. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32765. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32766. };
  32767. /**
  32768. * Returns the object VertexData associated to the passed geometry.
  32769. */
  32770. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32771. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32772. };
  32773. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32774. var result = new VertexData();
  32775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32776. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32777. }
  32778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32779. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32780. }
  32781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32782. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32783. }
  32784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32785. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32786. }
  32787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32788. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32789. }
  32790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32791. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32792. }
  32793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32794. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32795. }
  32796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32797. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32798. }
  32799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32800. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32801. }
  32802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32803. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32804. }
  32805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32806. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32807. }
  32808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32809. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32810. }
  32811. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32812. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32813. }
  32814. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32815. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32816. }
  32817. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32818. return result;
  32819. };
  32820. /**
  32821. * Creates the vertexData of the Ribbon.
  32822. */
  32823. VertexData.CreateRibbon = function (options) {
  32824. var pathArray = options.pathArray;
  32825. var closeArray = options.closeArray || false;
  32826. var closePath = options.closePath || false;
  32827. var invertUV = options.invertUV || false;
  32828. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32829. var offset = options.offset || defaultOffset;
  32830. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32832. var customUV = options.uvs;
  32833. var customColors = options.colors;
  32834. var positions = [];
  32835. var indices = [];
  32836. var normals = [];
  32837. var uvs = [];
  32838. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32839. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32840. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32841. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32842. var minlg; // minimal length among all paths from pathArray
  32843. var lg = []; // array of path lengths : nb of vertex per path
  32844. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32845. var p; // path iterator
  32846. var i; // point iterator
  32847. var j; // point iterator
  32848. // if single path in pathArray
  32849. if (pathArray.length < 2) {
  32850. var ar1 = [];
  32851. var ar2 = [];
  32852. for (i = 0; i < pathArray[0].length - offset; i++) {
  32853. ar1.push(pathArray[0][i]);
  32854. ar2.push(pathArray[0][i + offset]);
  32855. }
  32856. pathArray = [ar1, ar2];
  32857. }
  32858. // positions and horizontal distances (u)
  32859. var idc = 0;
  32860. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32861. var path;
  32862. var l;
  32863. minlg = pathArray[0].length;
  32864. var vectlg;
  32865. var dist;
  32866. for (p = 0; p < pathArray.length; p++) {
  32867. uTotalDistance[p] = 0;
  32868. us[p] = [0];
  32869. path = pathArray[p];
  32870. l = path.length;
  32871. minlg = (minlg < l) ? minlg : l;
  32872. j = 0;
  32873. while (j < l) {
  32874. positions.push(path[j].x, path[j].y, path[j].z);
  32875. if (j > 0) {
  32876. vectlg = path[j].subtract(path[j - 1]).length();
  32877. dist = vectlg + uTotalDistance[p];
  32878. us[p].push(dist);
  32879. uTotalDistance[p] = dist;
  32880. }
  32881. j++;
  32882. }
  32883. if (closePath) {
  32884. j--;
  32885. positions.push(path[0].x, path[0].y, path[0].z);
  32886. vectlg = path[j].subtract(path[0]).length();
  32887. dist = vectlg + uTotalDistance[p];
  32888. us[p].push(dist);
  32889. uTotalDistance[p] = dist;
  32890. }
  32891. lg[p] = l + closePathCorr;
  32892. idx[p] = idc;
  32893. idc += (l + closePathCorr);
  32894. }
  32895. // vertical distances (v)
  32896. var path1;
  32897. var path2;
  32898. var vertex1 = null;
  32899. var vertex2 = null;
  32900. for (i = 0; i < minlg + closePathCorr; i++) {
  32901. vTotalDistance[i] = 0;
  32902. vs[i] = [0];
  32903. for (p = 0; p < pathArray.length - 1; p++) {
  32904. path1 = pathArray[p];
  32905. path2 = pathArray[p + 1];
  32906. if (i === minlg) {
  32907. vertex1 = path1[0];
  32908. vertex2 = path2[0];
  32909. }
  32910. else {
  32911. vertex1 = path1[i];
  32912. vertex2 = path2[i];
  32913. }
  32914. vectlg = vertex2.subtract(vertex1).length();
  32915. dist = vectlg + vTotalDistance[i];
  32916. vs[i].push(dist);
  32917. vTotalDistance[i] = dist;
  32918. }
  32919. if (closeArray && vertex2 && vertex1) {
  32920. path1 = pathArray[p];
  32921. path2 = pathArray[0];
  32922. if (i === minlg) {
  32923. vertex2 = path2[0];
  32924. }
  32925. vectlg = vertex2.subtract(vertex1).length();
  32926. dist = vectlg + vTotalDistance[i];
  32927. vTotalDistance[i] = dist;
  32928. }
  32929. }
  32930. // uvs
  32931. var u;
  32932. var v;
  32933. if (customUV) {
  32934. for (p = 0; p < customUV.length; p++) {
  32935. uvs.push(customUV[p].x, customUV[p].y);
  32936. }
  32937. }
  32938. else {
  32939. for (p = 0; p < pathArray.length; p++) {
  32940. for (i = 0; i < minlg + closePathCorr; i++) {
  32941. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32942. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32943. if (invertUV) {
  32944. uvs.push(v, u);
  32945. }
  32946. else {
  32947. uvs.push(u, v);
  32948. }
  32949. }
  32950. }
  32951. }
  32952. // indices
  32953. p = 0; // path index
  32954. var pi = 0; // positions array index
  32955. var l1 = lg[p] - 1; // path1 length
  32956. var l2 = lg[p + 1] - 1; // path2 length
  32957. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32958. var shft = idx[1] - idx[0]; // shift
  32959. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32960. while (pi <= min && p < path1nb) {
  32961. // 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
  32962. indices.push(pi, pi + shft, pi + 1);
  32963. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32964. pi += 1;
  32965. if (pi === min) {
  32966. p++;
  32967. if (p === lg.length - 1) {
  32968. shft = idx[0] - idx[p];
  32969. l1 = lg[p] - 1;
  32970. l2 = lg[0] - 1;
  32971. }
  32972. else {
  32973. shft = idx[p + 1] - idx[p];
  32974. l1 = lg[p] - 1;
  32975. l2 = lg[p + 1] - 1;
  32976. }
  32977. pi = idx[p];
  32978. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32979. }
  32980. }
  32981. // normals
  32982. VertexData.ComputeNormals(positions, indices, normals);
  32983. if (closePath) {
  32984. var indexFirst = 0;
  32985. var indexLast = 0;
  32986. for (p = 0; p < pathArray.length; p++) {
  32987. indexFirst = idx[p] * 3;
  32988. if (p + 1 < pathArray.length) {
  32989. indexLast = (idx[p + 1] - 1) * 3;
  32990. }
  32991. else {
  32992. indexLast = normals.length - 3;
  32993. }
  32994. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32995. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32996. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32997. normals[indexLast] = normals[indexFirst];
  32998. normals[indexLast + 1] = normals[indexFirst + 1];
  32999. normals[indexLast + 2] = normals[indexFirst + 2];
  33000. }
  33001. }
  33002. // sides
  33003. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33004. // Colors
  33005. var colors = null;
  33006. if (customColors) {
  33007. colors = new Float32Array(customColors.length * 4);
  33008. for (var c = 0; c < customColors.length; c++) {
  33009. colors[c * 4] = customColors[c].r;
  33010. colors[c * 4 + 1] = customColors[c].g;
  33011. colors[c * 4 + 2] = customColors[c].b;
  33012. colors[c * 4 + 3] = customColors[c].a;
  33013. }
  33014. }
  33015. // Result
  33016. var vertexData = new VertexData();
  33017. var positions32 = new Float32Array(positions);
  33018. var normals32 = new Float32Array(normals);
  33019. var uvs32 = new Float32Array(uvs);
  33020. vertexData.indices = indices;
  33021. vertexData.positions = positions32;
  33022. vertexData.normals = normals32;
  33023. vertexData.uvs = uvs32;
  33024. if (colors) {
  33025. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33026. }
  33027. if (closePath) {
  33028. vertexData._idx = idx;
  33029. }
  33030. return vertexData;
  33031. };
  33032. /**
  33033. * Creates the VertexData of the Box.
  33034. */
  33035. VertexData.CreateBox = function (options) {
  33036. var normalsSource = [
  33037. new BABYLON.Vector3(0, 0, 1),
  33038. new BABYLON.Vector3(0, 0, -1),
  33039. new BABYLON.Vector3(1, 0, 0),
  33040. new BABYLON.Vector3(-1, 0, 0),
  33041. new BABYLON.Vector3(0, 1, 0),
  33042. new BABYLON.Vector3(0, -1, 0)
  33043. ];
  33044. var indices = [];
  33045. var positions = [];
  33046. var normals = [];
  33047. var uvs = [];
  33048. var width = options.width || options.size || 1;
  33049. var height = options.height || options.size || 1;
  33050. var depth = options.depth || options.size || 1;
  33051. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33052. var faceUV = options.faceUV || new Array(6);
  33053. var faceColors = options.faceColors;
  33054. var colors = [];
  33055. // default face colors and UV if undefined
  33056. for (var f = 0; f < 6; f++) {
  33057. if (faceUV[f] === undefined) {
  33058. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33059. }
  33060. if (faceColors && faceColors[f] === undefined) {
  33061. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33062. }
  33063. }
  33064. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33065. // Create each face in turn.
  33066. for (var index = 0; index < normalsSource.length; index++) {
  33067. var normal = normalsSource[index];
  33068. // Get two vectors perpendicular to the face normal and to each other.
  33069. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33070. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33071. // Six indices (two triangles) per face.
  33072. var verticesLength = positions.length / 3;
  33073. indices.push(verticesLength);
  33074. indices.push(verticesLength + 1);
  33075. indices.push(verticesLength + 2);
  33076. indices.push(verticesLength);
  33077. indices.push(verticesLength + 2);
  33078. indices.push(verticesLength + 3);
  33079. // Four vertices per face.
  33080. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33081. positions.push(vertex.x, vertex.y, vertex.z);
  33082. normals.push(normal.x, normal.y, normal.z);
  33083. uvs.push(faceUV[index].z, faceUV[index].w);
  33084. if (faceColors) {
  33085. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33086. }
  33087. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33088. positions.push(vertex.x, vertex.y, vertex.z);
  33089. normals.push(normal.x, normal.y, normal.z);
  33090. uvs.push(faceUV[index].x, faceUV[index].w);
  33091. if (faceColors) {
  33092. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33093. }
  33094. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33095. positions.push(vertex.x, vertex.y, vertex.z);
  33096. normals.push(normal.x, normal.y, normal.z);
  33097. uvs.push(faceUV[index].x, faceUV[index].y);
  33098. if (faceColors) {
  33099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33100. }
  33101. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33102. positions.push(vertex.x, vertex.y, vertex.z);
  33103. normals.push(normal.x, normal.y, normal.z);
  33104. uvs.push(faceUV[index].z, faceUV[index].y);
  33105. if (faceColors) {
  33106. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33107. }
  33108. }
  33109. // sides
  33110. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33111. // Result
  33112. var vertexData = new VertexData();
  33113. vertexData.indices = indices;
  33114. vertexData.positions = positions;
  33115. vertexData.normals = normals;
  33116. vertexData.uvs = uvs;
  33117. if (faceColors) {
  33118. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33119. vertexData.colors = totalColors;
  33120. }
  33121. return vertexData;
  33122. };
  33123. /**
  33124. * Creates the VertexData of the Sphere.
  33125. */
  33126. VertexData.CreateSphere = function (options) {
  33127. var segments = options.segments || 32;
  33128. var diameterX = options.diameterX || options.diameter || 1;
  33129. var diameterY = options.diameterY || options.diameter || 1;
  33130. var diameterZ = options.diameterZ || options.diameter || 1;
  33131. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33132. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33133. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33134. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33135. var totalZRotationSteps = 2 + segments;
  33136. var totalYRotationSteps = 2 * totalZRotationSteps;
  33137. var indices = [];
  33138. var positions = [];
  33139. var normals = [];
  33140. var uvs = [];
  33141. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33142. var normalizedZ = zRotationStep / totalZRotationSteps;
  33143. var angleZ = normalizedZ * Math.PI * slice;
  33144. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33145. var normalizedY = yRotationStep / totalYRotationSteps;
  33146. var angleY = normalizedY * Math.PI * 2 * arc;
  33147. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33148. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33149. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33150. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33151. var vertex = complete.multiply(radius);
  33152. var normal = complete.divide(radius).normalize();
  33153. positions.push(vertex.x, vertex.y, vertex.z);
  33154. normals.push(normal.x, normal.y, normal.z);
  33155. uvs.push(normalizedY, normalizedZ);
  33156. }
  33157. if (zRotationStep > 0) {
  33158. var verticesCount = positions.length / 3;
  33159. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33160. indices.push((firstIndex));
  33161. indices.push((firstIndex + 1));
  33162. indices.push(firstIndex + totalYRotationSteps + 1);
  33163. indices.push((firstIndex + totalYRotationSteps + 1));
  33164. indices.push((firstIndex + 1));
  33165. indices.push((firstIndex + totalYRotationSteps + 2));
  33166. }
  33167. }
  33168. }
  33169. // Sides
  33170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33171. // Result
  33172. var vertexData = new VertexData();
  33173. vertexData.indices = indices;
  33174. vertexData.positions = positions;
  33175. vertexData.normals = normals;
  33176. vertexData.uvs = uvs;
  33177. return vertexData;
  33178. };
  33179. /**
  33180. * Creates the VertexData of the Cylinder or Cone.
  33181. */
  33182. VertexData.CreateCylinder = function (options) {
  33183. var height = options.height || 2;
  33184. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33185. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33186. var tessellation = options.tessellation || 24;
  33187. var subdivisions = options.subdivisions || 1;
  33188. var hasRings = options.hasRings ? true : false;
  33189. var enclose = options.enclose ? true : false;
  33190. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33192. var faceUV = options.faceUV || new Array(3);
  33193. var faceColors = options.faceColors;
  33194. // default face colors and UV if undefined
  33195. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33196. var ringNb = (hasRings) ? subdivisions : 1;
  33197. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33198. var f;
  33199. for (f = 0; f < surfaceNb; f++) {
  33200. if (faceColors && faceColors[f] === undefined) {
  33201. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33202. }
  33203. }
  33204. for (f = 0; f < surfaceNb; f++) {
  33205. if (faceUV && faceUV[f] === undefined) {
  33206. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33207. }
  33208. }
  33209. var indices = new Array();
  33210. var positions = new Array();
  33211. var normals = new Array();
  33212. var uvs = new Array();
  33213. var colors = new Array();
  33214. var angle_step = Math.PI * 2 * arc / tessellation;
  33215. var angle;
  33216. var h;
  33217. var radius;
  33218. var tan = (diameterBottom - diameterTop) / 2 / height;
  33219. var ringVertex = BABYLON.Vector3.Zero();
  33220. var ringNormal = BABYLON.Vector3.Zero();
  33221. var ringFirstVertex = BABYLON.Vector3.Zero();
  33222. var ringFirstNormal = BABYLON.Vector3.Zero();
  33223. var quadNormal = BABYLON.Vector3.Zero();
  33224. var Y = BABYLON.Axis.Y;
  33225. // positions, normals, uvs
  33226. var i;
  33227. var j;
  33228. var r;
  33229. var ringIdx = 1;
  33230. var s = 1; // surface index
  33231. var cs = 0;
  33232. var v = 0;
  33233. for (i = 0; i <= subdivisions; i++) {
  33234. h = i / subdivisions;
  33235. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33236. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33237. for (r = 0; r < ringIdx; r++) {
  33238. if (hasRings) {
  33239. s += r;
  33240. }
  33241. if (enclose) {
  33242. s += 2 * r;
  33243. }
  33244. for (j = 0; j <= tessellation; j++) {
  33245. angle = j * angle_step;
  33246. // position
  33247. ringVertex.x = Math.cos(-angle) * radius;
  33248. ringVertex.y = -height / 2 + h * height;
  33249. ringVertex.z = Math.sin(-angle) * radius;
  33250. // normal
  33251. if (diameterTop === 0 && i === subdivisions) {
  33252. // if no top cap, reuse former normals
  33253. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33254. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33255. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33256. }
  33257. else {
  33258. ringNormal.x = ringVertex.x;
  33259. ringNormal.z = ringVertex.z;
  33260. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33261. ringNormal.normalize();
  33262. }
  33263. // keep first ring vertex values for enclose
  33264. if (j === 0) {
  33265. ringFirstVertex.copyFrom(ringVertex);
  33266. ringFirstNormal.copyFrom(ringNormal);
  33267. }
  33268. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33269. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33270. if (hasRings) {
  33271. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33272. }
  33273. else {
  33274. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33275. }
  33276. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33277. if (faceColors) {
  33278. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33279. }
  33280. }
  33281. // if enclose, add four vertices and their dedicated normals
  33282. if (arc !== 1 && enclose) {
  33283. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33284. positions.push(0, ringVertex.y, 0);
  33285. positions.push(0, ringVertex.y, 0);
  33286. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33287. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33288. quadNormal.normalize();
  33289. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33290. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33291. quadNormal.normalize();
  33292. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33293. if (hasRings) {
  33294. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33295. }
  33296. else {
  33297. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33298. }
  33299. uvs.push(faceUV[s + 1].x, v);
  33300. uvs.push(faceUV[s + 1].z, v);
  33301. if (hasRings) {
  33302. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33303. }
  33304. else {
  33305. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33306. }
  33307. uvs.push(faceUV[s + 2].x, v);
  33308. uvs.push(faceUV[s + 2].z, v);
  33309. if (faceColors) {
  33310. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33311. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33312. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33313. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33314. }
  33315. }
  33316. if (cs !== s) {
  33317. cs = s;
  33318. }
  33319. }
  33320. }
  33321. // indices
  33322. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33323. var s;
  33324. i = 0;
  33325. for (s = 0; s < subdivisions; s++) {
  33326. var i0 = 0;
  33327. var i1 = 0;
  33328. var i2 = 0;
  33329. var i3 = 0;
  33330. for (j = 0; j < tessellation; j++) {
  33331. i0 = i * (e + 1) + j;
  33332. i1 = (i + 1) * (e + 1) + j;
  33333. i2 = i * (e + 1) + (j + 1);
  33334. i3 = (i + 1) * (e + 1) + (j + 1);
  33335. indices.push(i0, i1, i2);
  33336. indices.push(i3, i2, i1);
  33337. }
  33338. if (arc !== 1 && enclose) {
  33339. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33340. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33341. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33342. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33343. }
  33344. i = (hasRings) ? (i + 2) : (i + 1);
  33345. }
  33346. // Caps
  33347. var createCylinderCap = function (isTop) {
  33348. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33349. if (radius === 0) {
  33350. return;
  33351. }
  33352. // Cap positions, normals & uvs
  33353. var angle;
  33354. var circleVector;
  33355. var i;
  33356. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33357. var c = null;
  33358. if (faceColors) {
  33359. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33360. }
  33361. // cap center
  33362. var vbase = positions.length / 3;
  33363. var offset = isTop ? height / 2 : -height / 2;
  33364. var center = new BABYLON.Vector3(0, offset, 0);
  33365. positions.push(center.x, center.y, center.z);
  33366. normals.push(0, isTop ? 1 : -1, 0);
  33367. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33368. if (c) {
  33369. colors.push(c.r, c.g, c.b, c.a);
  33370. }
  33371. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33372. for (i = 0; i <= tessellation; i++) {
  33373. angle = Math.PI * 2 * i * arc / tessellation;
  33374. var cos = Math.cos(-angle);
  33375. var sin = Math.sin(-angle);
  33376. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33377. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33378. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33379. normals.push(0, isTop ? 1 : -1, 0);
  33380. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33381. if (c) {
  33382. colors.push(c.r, c.g, c.b, c.a);
  33383. }
  33384. }
  33385. // Cap indices
  33386. for (i = 0; i < tessellation; i++) {
  33387. if (!isTop) {
  33388. indices.push(vbase);
  33389. indices.push(vbase + (i + 1));
  33390. indices.push(vbase + (i + 2));
  33391. }
  33392. else {
  33393. indices.push(vbase);
  33394. indices.push(vbase + (i + 2));
  33395. indices.push(vbase + (i + 1));
  33396. }
  33397. }
  33398. };
  33399. // add caps to geometry
  33400. createCylinderCap(false);
  33401. createCylinderCap(true);
  33402. // Sides
  33403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33404. var vertexData = new VertexData();
  33405. vertexData.indices = indices;
  33406. vertexData.positions = positions;
  33407. vertexData.normals = normals;
  33408. vertexData.uvs = uvs;
  33409. if (faceColors) {
  33410. vertexData.colors = colors;
  33411. }
  33412. return vertexData;
  33413. };
  33414. /**
  33415. * Creates the VertexData of the Torus.
  33416. */
  33417. VertexData.CreateTorus = function (options) {
  33418. var indices = [];
  33419. var positions = [];
  33420. var normals = [];
  33421. var uvs = [];
  33422. var diameter = options.diameter || 1;
  33423. var thickness = options.thickness || 0.5;
  33424. var tessellation = options.tessellation || 16;
  33425. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33426. var stride = tessellation + 1;
  33427. for (var i = 0; i <= tessellation; i++) {
  33428. var u = i / tessellation;
  33429. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33430. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33431. for (var j = 0; j <= tessellation; j++) {
  33432. var v = 1 - j / tessellation;
  33433. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33434. var dx = Math.cos(innerAngle);
  33435. var dy = Math.sin(innerAngle);
  33436. // Create a vertex.
  33437. var normal = new BABYLON.Vector3(dx, dy, 0);
  33438. var position = normal.scale(thickness / 2);
  33439. var textureCoordinate = new BABYLON.Vector2(u, v);
  33440. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33441. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33442. positions.push(position.x, position.y, position.z);
  33443. normals.push(normal.x, normal.y, normal.z);
  33444. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33445. // And create indices for two triangles.
  33446. var nextI = (i + 1) % stride;
  33447. var nextJ = (j + 1) % stride;
  33448. indices.push(i * stride + j);
  33449. indices.push(i * stride + nextJ);
  33450. indices.push(nextI * stride + j);
  33451. indices.push(i * stride + nextJ);
  33452. indices.push(nextI * stride + nextJ);
  33453. indices.push(nextI * stride + j);
  33454. }
  33455. }
  33456. // Sides
  33457. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33458. // Result
  33459. var vertexData = new VertexData();
  33460. vertexData.indices = indices;
  33461. vertexData.positions = positions;
  33462. vertexData.normals = normals;
  33463. vertexData.uvs = uvs;
  33464. return vertexData;
  33465. };
  33466. /**
  33467. * Creates the VertexData of the LineSystem.
  33468. */
  33469. VertexData.CreateLineSystem = function (options) {
  33470. var indices = [];
  33471. var positions = [];
  33472. var lines = options.lines;
  33473. var colors = options.colors;
  33474. var vertexColors = [];
  33475. var idx = 0;
  33476. for (var l = 0; l < lines.length; l++) {
  33477. var points = lines[l];
  33478. for (var index = 0; index < points.length; index++) {
  33479. positions.push(points[index].x, points[index].y, points[index].z);
  33480. if (colors) {
  33481. var color = colors[l];
  33482. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33483. }
  33484. if (index > 0) {
  33485. indices.push(idx - 1);
  33486. indices.push(idx);
  33487. }
  33488. idx++;
  33489. }
  33490. }
  33491. var vertexData = new VertexData();
  33492. vertexData.indices = indices;
  33493. vertexData.positions = positions;
  33494. if (colors) {
  33495. vertexData.colors = vertexColors;
  33496. }
  33497. return vertexData;
  33498. };
  33499. /**
  33500. * Create the VertexData of the DashedLines.
  33501. */
  33502. VertexData.CreateDashedLines = function (options) {
  33503. var dashSize = options.dashSize || 3;
  33504. var gapSize = options.gapSize || 1;
  33505. var dashNb = options.dashNb || 200;
  33506. var points = options.points;
  33507. var positions = new Array();
  33508. var indices = new Array();
  33509. var curvect = BABYLON.Vector3.Zero();
  33510. var lg = 0;
  33511. var nb = 0;
  33512. var shft = 0;
  33513. var dashshft = 0;
  33514. var curshft = 0;
  33515. var idx = 0;
  33516. var i = 0;
  33517. for (i = 0; i < points.length - 1; i++) {
  33518. points[i + 1].subtractToRef(points[i], curvect);
  33519. lg += curvect.length();
  33520. }
  33521. shft = lg / dashNb;
  33522. dashshft = dashSize * shft / (dashSize + gapSize);
  33523. for (i = 0; i < points.length - 1; i++) {
  33524. points[i + 1].subtractToRef(points[i], curvect);
  33525. nb = Math.floor(curvect.length() / shft);
  33526. curvect.normalize();
  33527. for (var j = 0; j < nb; j++) {
  33528. curshft = shft * j;
  33529. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33530. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33531. indices.push(idx, idx + 1);
  33532. idx += 2;
  33533. }
  33534. }
  33535. // Result
  33536. var vertexData = new VertexData();
  33537. vertexData.positions = positions;
  33538. vertexData.indices = indices;
  33539. return vertexData;
  33540. };
  33541. /**
  33542. * Creates the VertexData of the Ground.
  33543. */
  33544. VertexData.CreateGround = function (options) {
  33545. var indices = [];
  33546. var positions = [];
  33547. var normals = [];
  33548. var uvs = [];
  33549. var row, col;
  33550. var width = options.width || 1;
  33551. var height = options.height || 1;
  33552. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33553. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33554. for (row = 0; row <= subdivisionsY; row++) {
  33555. for (col = 0; col <= subdivisionsX; col++) {
  33556. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33557. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33558. positions.push(position.x, position.y, position.z);
  33559. normals.push(normal.x, normal.y, normal.z);
  33560. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33561. }
  33562. }
  33563. for (row = 0; row < subdivisionsY; row++) {
  33564. for (col = 0; col < subdivisionsX; col++) {
  33565. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33566. indices.push(col + 1 + row * (subdivisionsX + 1));
  33567. indices.push(col + row * (subdivisionsX + 1));
  33568. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33569. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33570. indices.push(col + row * (subdivisionsX + 1));
  33571. }
  33572. }
  33573. // Result
  33574. var vertexData = new VertexData();
  33575. vertexData.indices = indices;
  33576. vertexData.positions = positions;
  33577. vertexData.normals = normals;
  33578. vertexData.uvs = uvs;
  33579. return vertexData;
  33580. };
  33581. /**
  33582. * Creates the VertexData of the TiledGround.
  33583. */
  33584. VertexData.CreateTiledGround = function (options) {
  33585. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33586. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33587. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33588. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33589. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33590. var precision = options.precision || { w: 1, h: 1 };
  33591. var indices = new Array();
  33592. var positions = new Array();
  33593. var normals = new Array();
  33594. var uvs = new Array();
  33595. var row, col, tileRow, tileCol;
  33596. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33597. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33598. precision.w = (precision.w < 1) ? 1 : precision.w;
  33599. precision.h = (precision.h < 1) ? 1 : precision.h;
  33600. var tileSize = {
  33601. 'w': (xmax - xmin) / subdivisions.w,
  33602. 'h': (zmax - zmin) / subdivisions.h
  33603. };
  33604. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33605. // Indices
  33606. var base = positions.length / 3;
  33607. var rowLength = precision.w + 1;
  33608. for (row = 0; row < precision.h; row++) {
  33609. for (col = 0; col < precision.w; col++) {
  33610. var square = [
  33611. base + col + row * rowLength,
  33612. base + (col + 1) + row * rowLength,
  33613. base + (col + 1) + (row + 1) * rowLength,
  33614. base + col + (row + 1) * rowLength
  33615. ];
  33616. indices.push(square[1]);
  33617. indices.push(square[2]);
  33618. indices.push(square[3]);
  33619. indices.push(square[0]);
  33620. indices.push(square[1]);
  33621. indices.push(square[3]);
  33622. }
  33623. }
  33624. // Position, normals and uvs
  33625. var position = BABYLON.Vector3.Zero();
  33626. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33627. for (row = 0; row <= precision.h; row++) {
  33628. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33629. for (col = 0; col <= precision.w; col++) {
  33630. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33631. position.y = 0;
  33632. positions.push(position.x, position.y, position.z);
  33633. normals.push(normal.x, normal.y, normal.z);
  33634. uvs.push(col / precision.w, row / precision.h);
  33635. }
  33636. }
  33637. }
  33638. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33639. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33640. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33641. }
  33642. }
  33643. // Result
  33644. var vertexData = new VertexData();
  33645. vertexData.indices = indices;
  33646. vertexData.positions = positions;
  33647. vertexData.normals = normals;
  33648. vertexData.uvs = uvs;
  33649. return vertexData;
  33650. };
  33651. /**
  33652. * Creates the VertexData of the Ground designed from a heightmap.
  33653. */
  33654. VertexData.CreateGroundFromHeightMap = function (options) {
  33655. var indices = [];
  33656. var positions = [];
  33657. var normals = [];
  33658. var uvs = [];
  33659. var row, col;
  33660. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33661. // Vertices
  33662. for (row = 0; row <= options.subdivisions; row++) {
  33663. for (col = 0; col <= options.subdivisions; col++) {
  33664. 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));
  33665. // Compute height
  33666. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33667. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33668. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33669. var r = options.buffer[pos] / 255.0;
  33670. var g = options.buffer[pos + 1] / 255.0;
  33671. var b = options.buffer[pos + 2] / 255.0;
  33672. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33673. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33674. // Add vertex
  33675. positions.push(position.x, position.y, position.z);
  33676. normals.push(0, 0, 0);
  33677. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33678. }
  33679. }
  33680. // Indices
  33681. for (row = 0; row < options.subdivisions; row++) {
  33682. for (col = 0; col < options.subdivisions; col++) {
  33683. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33684. indices.push(col + 1 + row * (options.subdivisions + 1));
  33685. indices.push(col + row * (options.subdivisions + 1));
  33686. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33687. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33688. indices.push(col + row * (options.subdivisions + 1));
  33689. }
  33690. }
  33691. // Normals
  33692. VertexData.ComputeNormals(positions, indices, normals);
  33693. // Result
  33694. var vertexData = new VertexData();
  33695. vertexData.indices = indices;
  33696. vertexData.positions = positions;
  33697. vertexData.normals = normals;
  33698. vertexData.uvs = uvs;
  33699. return vertexData;
  33700. };
  33701. /**
  33702. * Creates the VertexData of the Plane.
  33703. */
  33704. VertexData.CreatePlane = function (options) {
  33705. var indices = [];
  33706. var positions = [];
  33707. var normals = [];
  33708. var uvs = [];
  33709. var width = options.width || options.size || 1;
  33710. var height = options.height || options.size || 1;
  33711. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33712. // Vertices
  33713. var halfWidth = width / 2.0;
  33714. var halfHeight = height / 2.0;
  33715. positions.push(-halfWidth, -halfHeight, 0);
  33716. normals.push(0, 0, -1.0);
  33717. uvs.push(0.0, 0.0);
  33718. positions.push(halfWidth, -halfHeight, 0);
  33719. normals.push(0, 0, -1.0);
  33720. uvs.push(1.0, 0.0);
  33721. positions.push(halfWidth, halfHeight, 0);
  33722. normals.push(0, 0, -1.0);
  33723. uvs.push(1.0, 1.0);
  33724. positions.push(-halfWidth, halfHeight, 0);
  33725. normals.push(0, 0, -1.0);
  33726. uvs.push(0.0, 1.0);
  33727. // Indices
  33728. indices.push(0);
  33729. indices.push(1);
  33730. indices.push(2);
  33731. indices.push(0);
  33732. indices.push(2);
  33733. indices.push(3);
  33734. // Sides
  33735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33736. // Result
  33737. var vertexData = new VertexData();
  33738. vertexData.indices = indices;
  33739. vertexData.positions = positions;
  33740. vertexData.normals = normals;
  33741. vertexData.uvs = uvs;
  33742. return vertexData;
  33743. };
  33744. /**
  33745. * Creates the VertexData of the Disc or regular Polygon.
  33746. */
  33747. VertexData.CreateDisc = function (options) {
  33748. var positions = new Array();
  33749. var indices = new Array();
  33750. var normals = new Array();
  33751. var uvs = new Array();
  33752. var radius = options.radius || 0.5;
  33753. var tessellation = options.tessellation || 64;
  33754. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33755. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33756. // positions and uvs
  33757. positions.push(0, 0, 0); // disc center first
  33758. uvs.push(0.5, 0.5);
  33759. var theta = Math.PI * 2 * arc;
  33760. var step = theta / tessellation;
  33761. for (var a = 0; a < theta; a += step) {
  33762. var x = Math.cos(a);
  33763. var y = Math.sin(a);
  33764. var u = (x + 1) / 2;
  33765. var v = (1 - y) / 2;
  33766. positions.push(radius * x, radius * y, 0);
  33767. uvs.push(u, v);
  33768. }
  33769. if (arc === 1) {
  33770. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33771. uvs.push(uvs[2], uvs[3]);
  33772. }
  33773. //indices
  33774. var vertexNb = positions.length / 3;
  33775. for (var i = 1; i < vertexNb - 1; i++) {
  33776. indices.push(i + 1, 0, i);
  33777. }
  33778. // result
  33779. VertexData.ComputeNormals(positions, indices, normals);
  33780. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33781. var vertexData = new VertexData();
  33782. vertexData.indices = indices;
  33783. vertexData.positions = positions;
  33784. vertexData.normals = normals;
  33785. vertexData.uvs = uvs;
  33786. return vertexData;
  33787. };
  33788. /**
  33789. * Re-creates the VertexData of the Polygon for sideOrientation.
  33790. */
  33791. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33792. var faceUV = fUV || new Array(3);
  33793. var faceColors = fColors;
  33794. var colors = [];
  33795. // default face colors and UV if undefined
  33796. for (var f = 0; f < 3; f++) {
  33797. if (faceUV[f] === undefined) {
  33798. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33799. }
  33800. if (faceColors && faceColors[f] === undefined) {
  33801. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33802. }
  33803. }
  33804. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33805. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33806. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33807. var indices = polygon.getIndices();
  33808. // set face colours and textures
  33809. var idx = 0;
  33810. var face = 0;
  33811. for (var index = 0; index < normals.length; index += 3) {
  33812. //Edge Face no. 1
  33813. if (Math.abs(normals[index + 1]) < 0.001) {
  33814. face = 1;
  33815. }
  33816. //Top Face no. 0
  33817. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33818. face = 0;
  33819. }
  33820. //Bottom Face no. 2
  33821. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33822. face = 2;
  33823. }
  33824. idx = index / 3;
  33825. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33826. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33827. if (faceColors) {
  33828. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33829. }
  33830. }
  33831. // sides
  33832. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33833. // Result
  33834. var vertexData = new VertexData();
  33835. vertexData.indices = indices;
  33836. vertexData.positions = positions;
  33837. vertexData.normals = normals;
  33838. vertexData.uvs = uvs;
  33839. if (faceColors) {
  33840. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33841. vertexData.colors = totalColors;
  33842. }
  33843. return vertexData;
  33844. };
  33845. /**
  33846. * Creates the VertexData of the IcoSphere.
  33847. */
  33848. VertexData.CreateIcoSphere = function (options) {
  33849. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33850. var radius = options.radius || 1;
  33851. var flat = (options.flat === undefined) ? true : options.flat;
  33852. var subdivisions = options.subdivisions || 4;
  33853. var radiusX = options.radiusX || radius;
  33854. var radiusY = options.radiusY || radius;
  33855. var radiusZ = options.radiusZ || radius;
  33856. var t = (1 + Math.sqrt(5)) / 2;
  33857. // 12 vertex x,y,z
  33858. var ico_vertices = [
  33859. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33860. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33861. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33862. ];
  33863. // index of 3 vertex makes a face of icopshere
  33864. var ico_indices = [
  33865. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33866. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33867. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33868. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33869. ];
  33870. // vertex for uv have aliased position, not for UV
  33871. var vertices_unalias_id = [
  33872. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33873. // vertex alias
  33874. 0,
  33875. 2,
  33876. 3,
  33877. 3,
  33878. 3,
  33879. 4,
  33880. 7,
  33881. 8,
  33882. 9,
  33883. 9,
  33884. 10,
  33885. 11 // 23: B + 12
  33886. ];
  33887. // uv as integer step (not pixels !)
  33888. var ico_vertexuv = [
  33889. 5, 1, 3, 1, 6, 4, 0, 0,
  33890. 5, 3, 4, 2, 2, 2, 4, 0,
  33891. 2, 0, 1, 1, 6, 0, 6, 2,
  33892. // vertex alias (for same vertex on different faces)
  33893. 0, 4,
  33894. 3, 3,
  33895. 4, 4,
  33896. 3, 1,
  33897. 4, 2,
  33898. 4, 4,
  33899. 0, 2,
  33900. 1, 1,
  33901. 2, 2,
  33902. 3, 3,
  33903. 1, 3,
  33904. 2, 4 // 23: B + 12
  33905. ];
  33906. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33907. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33908. // First island of uv mapping
  33909. // v = 4h 3+ 2
  33910. // v = 3h 9+ 4
  33911. // v = 2h 9+ 5 B
  33912. // v = 1h 9 1 0
  33913. // v = 0h 3 8 7 A
  33914. // u = 0 1 2 3 4 5 6 *a
  33915. // Second island of uv mapping
  33916. // v = 4h 0+ B+ 4+
  33917. // v = 3h A+ 2+
  33918. // v = 2h 7+ 6 3+
  33919. // v = 1h 8+ 3+
  33920. // v = 0h
  33921. // u = 0 1 2 3 4 5 6 *a
  33922. // Face layout on texture UV mapping
  33923. // ============
  33924. // \ 4 /\ 16 / ======
  33925. // \ / \ / /\ 11 /
  33926. // \/ 7 \/ / \ /
  33927. // ======= / 10 \/
  33928. // /\ 17 /\ =======
  33929. // / \ / \ \ 15 /\
  33930. // / 8 \/ 12 \ \ / \
  33931. // ============ \/ 6 \
  33932. // \ 18 /\ ============
  33933. // \ / \ \ 5 /\ 0 /
  33934. // \/ 13 \ \ / \ /
  33935. // ======= \/ 1 \/
  33936. // =============
  33937. // /\ 19 /\ 2 /\
  33938. // / \ / \ / \
  33939. // / 14 \/ 9 \/ 3 \
  33940. // ===================
  33941. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33942. var ustep = 138 / 1024;
  33943. var vstep = 239 / 1024;
  33944. var uoffset = 60 / 1024;
  33945. var voffset = 26 / 1024;
  33946. // Second island should have margin, not to touch the first island
  33947. // avoid any borderline artefact in pixel rounding
  33948. var island_u_offset = -40 / 1024;
  33949. var island_v_offset = +20 / 1024;
  33950. // face is either island 0 or 1 :
  33951. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33952. var island = [
  33953. 0, 0, 0, 0, 1,
  33954. 0, 0, 1, 1, 0,
  33955. 0, 0, 1, 1, 0,
  33956. 0, 1, 1, 1, 0 // 15 - 19
  33957. ];
  33958. var indices = new Array();
  33959. var positions = new Array();
  33960. var normals = new Array();
  33961. var uvs = new Array();
  33962. var current_indice = 0;
  33963. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33964. var face_vertex_pos = new Array(3);
  33965. var face_vertex_uv = new Array(3);
  33966. var v012;
  33967. for (v012 = 0; v012 < 3; v012++) {
  33968. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33969. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33970. }
  33971. // create all with normals
  33972. for (var face = 0; face < 20; face++) {
  33973. // 3 vertex per face
  33974. for (v012 = 0; v012 < 3; v012++) {
  33975. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33976. var v_id = ico_indices[3 * face + v012];
  33977. // vertex have 3D position (x,y,z)
  33978. 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]);
  33979. // Normalize to get normal, then scale to radius
  33980. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33981. // uv Coordinates from vertex ID
  33982. 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);
  33983. }
  33984. // Subdivide the face (interpolate pos, norm, uv)
  33985. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33986. // - norm is linear interpolation of vertex corner normal
  33987. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33988. // - uv is linear interpolation
  33989. //
  33990. // Topology is as below for sub-divide by 2
  33991. // vertex shown as v0,v1,v2
  33992. // interp index is i1 to progress in range [v0,v1[
  33993. // interp index is i2 to progress in range [v0,v2[
  33994. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33995. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33996. //
  33997. //
  33998. // i2 v2
  33999. // ^ ^
  34000. // / / \
  34001. // / / \
  34002. // / / \
  34003. // / / (0,1) \
  34004. // / #---------\
  34005. // / / \ (0,0)'/ \
  34006. // / / \ / \
  34007. // / / \ / \
  34008. // / / (0,0) \ / (1,0) \
  34009. // / #---------#---------\
  34010. // v0 v1
  34011. //
  34012. // --------------------> i1
  34013. //
  34014. // interp of (i1,i2):
  34015. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34016. // along i1 : lerp(x0,x1, i1/(S-i2))
  34017. //
  34018. // centroid of triangle is needed to get help normal computation
  34019. // (c1,c2) are used for centroid location
  34020. var interp_vertex = function (i1, i2, c1, c2) {
  34021. // vertex is interpolated from
  34022. // - face_vertex_pos[0..2]
  34023. // - face_vertex_uv[0..2]
  34024. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34025. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34026. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34027. pos_interp.normalize();
  34028. var vertex_normal;
  34029. if (flat) {
  34030. // in flat mode, recalculate normal as face centroid normal
  34031. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34032. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34033. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34034. }
  34035. else {
  34036. // in smooth mode, recalculate normal from each single vertex position
  34037. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34038. }
  34039. // Vertex normal need correction due to X,Y,Z radius scaling
  34040. vertex_normal.x /= radiusX;
  34041. vertex_normal.y /= radiusY;
  34042. vertex_normal.z /= radiusZ;
  34043. vertex_normal.normalize();
  34044. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34045. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34046. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34047. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34048. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34049. uvs.push(uv_interp.x, uv_interp.y);
  34050. // push each vertex has member of a face
  34051. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34052. indices.push(current_indice);
  34053. current_indice++;
  34054. };
  34055. for (var i2 = 0; i2 < subdivisions; i2++) {
  34056. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34057. // face : (i1,i2) for /\ :
  34058. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34059. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34060. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34061. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34062. if (i1 + i2 + 1 < subdivisions) {
  34063. // face : (i1,i2)' for \/ :
  34064. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34065. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34066. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34067. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34068. }
  34069. }
  34070. }
  34071. }
  34072. // Sides
  34073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34074. // Result
  34075. var vertexData = new VertexData();
  34076. vertexData.indices = indices;
  34077. vertexData.positions = positions;
  34078. vertexData.normals = normals;
  34079. vertexData.uvs = uvs;
  34080. return vertexData;
  34081. };
  34082. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34083. /**
  34084. * Creates the VertexData of the Polyhedron.
  34085. */
  34086. VertexData.CreatePolyhedron = function (options) {
  34087. // provided polyhedron types :
  34088. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34089. // 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)
  34090. var polyhedra = [];
  34091. 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]] };
  34092. 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]] };
  34093. polyhedra[2] = {
  34094. 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]],
  34095. 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]]
  34096. };
  34097. polyhedra[3] = {
  34098. 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]],
  34099. 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]]
  34100. };
  34101. polyhedra[4] = {
  34102. 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]],
  34103. 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]]
  34104. };
  34105. 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]] };
  34106. 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]] };
  34107. 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]] };
  34108. 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]] };
  34109. 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]] };
  34110. 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]] };
  34111. 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]] };
  34112. 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]] };
  34113. 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]] };
  34114. polyhedra[14] = {
  34115. 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]],
  34116. 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]]
  34117. };
  34118. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34119. var size = options.size;
  34120. var sizeX = options.sizeX || size || 1;
  34121. var sizeY = options.sizeY || size || 1;
  34122. var sizeZ = options.sizeZ || size || 1;
  34123. var data = options.custom || polyhedra[type];
  34124. var nbfaces = data.face.length;
  34125. var faceUV = options.faceUV || new Array(nbfaces);
  34126. var faceColors = options.faceColors;
  34127. var flat = (options.flat === undefined) ? true : options.flat;
  34128. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34129. var positions = new Array();
  34130. var indices = new Array();
  34131. var normals = new Array();
  34132. var uvs = new Array();
  34133. var colors = new Array();
  34134. var index = 0;
  34135. var faceIdx = 0; // face cursor in the array "indexes"
  34136. var indexes = new Array();
  34137. var i = 0;
  34138. var f = 0;
  34139. var u, v, ang, x, y, tmp;
  34140. // default face colors and UV if undefined
  34141. if (flat) {
  34142. for (f = 0; f < nbfaces; f++) {
  34143. if (faceColors && faceColors[f] === undefined) {
  34144. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34145. }
  34146. if (faceUV && faceUV[f] === undefined) {
  34147. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34148. }
  34149. }
  34150. }
  34151. if (!flat) {
  34152. for (i = 0; i < data.vertex.length; i++) {
  34153. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34154. uvs.push(0, 0);
  34155. }
  34156. for (f = 0; f < nbfaces; f++) {
  34157. for (i = 0; i < data.face[f].length - 2; i++) {
  34158. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34159. }
  34160. }
  34161. }
  34162. else {
  34163. for (f = 0; f < nbfaces; f++) {
  34164. var fl = data.face[f].length; // number of vertices of the current face
  34165. ang = 2 * Math.PI / fl;
  34166. x = 0.5 * Math.tan(ang / 2);
  34167. y = 0.5;
  34168. // positions, uvs, colors
  34169. for (i = 0; i < fl; i++) {
  34170. // positions
  34171. 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);
  34172. indexes.push(index);
  34173. index++;
  34174. // uvs
  34175. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34176. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34177. uvs.push(u, v);
  34178. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34179. y = x * Math.sin(ang) + y * Math.cos(ang);
  34180. x = tmp;
  34181. // colors
  34182. if (faceColors) {
  34183. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34184. }
  34185. }
  34186. // indices from indexes
  34187. for (i = 0; i < fl - 2; i++) {
  34188. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34189. }
  34190. faceIdx += fl;
  34191. }
  34192. }
  34193. VertexData.ComputeNormals(positions, indices, normals);
  34194. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34195. var vertexData = new VertexData();
  34196. vertexData.positions = positions;
  34197. vertexData.indices = indices;
  34198. vertexData.normals = normals;
  34199. vertexData.uvs = uvs;
  34200. if (faceColors && flat) {
  34201. vertexData.colors = colors;
  34202. }
  34203. return vertexData;
  34204. };
  34205. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34206. /**
  34207. * Creates the VertexData of the Torus Knot.
  34208. */
  34209. VertexData.CreateTorusKnot = function (options) {
  34210. var indices = new Array();
  34211. var positions = new Array();
  34212. var normals = new Array();
  34213. var uvs = new Array();
  34214. var radius = options.radius || 2;
  34215. var tube = options.tube || 0.5;
  34216. var radialSegments = options.radialSegments || 32;
  34217. var tubularSegments = options.tubularSegments || 32;
  34218. var p = options.p || 2;
  34219. var q = options.q || 3;
  34220. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34221. // Helper
  34222. var getPos = function (angle) {
  34223. var cu = Math.cos(angle);
  34224. var su = Math.sin(angle);
  34225. var quOverP = q / p * angle;
  34226. var cs = Math.cos(quOverP);
  34227. var tx = radius * (2 + cs) * 0.5 * cu;
  34228. var ty = radius * (2 + cs) * su * 0.5;
  34229. var tz = radius * Math.sin(quOverP) * 0.5;
  34230. return new BABYLON.Vector3(tx, ty, tz);
  34231. };
  34232. // Vertices
  34233. var i;
  34234. var j;
  34235. for (i = 0; i <= radialSegments; i++) {
  34236. var modI = i % radialSegments;
  34237. var u = modI / radialSegments * 2 * p * Math.PI;
  34238. var p1 = getPos(u);
  34239. var p2 = getPos(u + 0.01);
  34240. var tang = p2.subtract(p1);
  34241. var n = p2.add(p1);
  34242. var bitan = BABYLON.Vector3.Cross(tang, n);
  34243. n = BABYLON.Vector3.Cross(bitan, tang);
  34244. bitan.normalize();
  34245. n.normalize();
  34246. for (j = 0; j < tubularSegments; j++) {
  34247. var modJ = j % tubularSegments;
  34248. var v = modJ / tubularSegments * 2 * Math.PI;
  34249. var cx = -tube * Math.cos(v);
  34250. var cy = tube * Math.sin(v);
  34251. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34252. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34253. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34254. uvs.push(i / radialSegments);
  34255. uvs.push(j / tubularSegments);
  34256. }
  34257. }
  34258. for (i = 0; i < radialSegments; i++) {
  34259. for (j = 0; j < tubularSegments; j++) {
  34260. var jNext = (j + 1) % tubularSegments;
  34261. var a = i * tubularSegments + j;
  34262. var b = (i + 1) * tubularSegments + j;
  34263. var c = (i + 1) * tubularSegments + jNext;
  34264. var d = i * tubularSegments + jNext;
  34265. indices.push(d);
  34266. indices.push(b);
  34267. indices.push(a);
  34268. indices.push(d);
  34269. indices.push(c);
  34270. indices.push(b);
  34271. }
  34272. }
  34273. // Normals
  34274. VertexData.ComputeNormals(positions, indices, normals);
  34275. // Sides
  34276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34277. // Result
  34278. var vertexData = new VertexData();
  34279. vertexData.indices = indices;
  34280. vertexData.positions = positions;
  34281. vertexData.normals = normals;
  34282. vertexData.uvs = uvs;
  34283. return vertexData;
  34284. };
  34285. // Tools
  34286. /**
  34287. * @param {any} - positions (number[] or Float32Array)
  34288. * @param {any} - indices (number[] or Uint16Array)
  34289. * @param {any} - normals (number[] or Float32Array)
  34290. * options (optional) :
  34291. * facetPositions : optional array of facet positions (vector3)
  34292. * facetNormals : optional array of facet normals (vector3)
  34293. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34294. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34295. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34296. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34297. * bInfo : optional bounding info, required for facetPartitioning computation
  34298. * useRightHandedSystem: optional boolean to for right handed system computation
  34299. * depthSort : optional boolean to enable the facet depth sort computation
  34300. * distanceTo : optional Vector3 to compute the facet depth from this location
  34301. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34302. */
  34303. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34304. // temporary scalar variables
  34305. var index = 0; // facet index
  34306. var p1p2x = 0.0; // p1p2 vector x coordinate
  34307. var p1p2y = 0.0; // p1p2 vector y coordinate
  34308. var p1p2z = 0.0; // p1p2 vector z coordinate
  34309. var p3p2x = 0.0; // p3p2 vector x coordinate
  34310. var p3p2y = 0.0; // p3p2 vector y coordinate
  34311. var p3p2z = 0.0; // p3p2 vector z coordinate
  34312. var faceNormalx = 0.0; // facet normal x coordinate
  34313. var faceNormaly = 0.0; // facet normal y coordinate
  34314. var faceNormalz = 0.0; // facet normal z coordinate
  34315. var length = 0.0; // facet normal length before normalization
  34316. var v1x = 0; // vector1 x index in the positions array
  34317. var v1y = 0; // vector1 y index in the positions array
  34318. var v1z = 0; // vector1 z index in the positions array
  34319. var v2x = 0; // vector2 x index in the positions array
  34320. var v2y = 0; // vector2 y index in the positions array
  34321. var v2z = 0; // vector2 z index in the positions array
  34322. var v3x = 0; // vector3 x index in the positions array
  34323. var v3y = 0; // vector3 y index in the positions array
  34324. var v3z = 0; // vector3 z index in the positions array
  34325. var computeFacetNormals = false;
  34326. var computeFacetPositions = false;
  34327. var computeFacetPartitioning = false;
  34328. var computeDepthSort = false;
  34329. var faceNormalSign = 1;
  34330. var ratio = 0;
  34331. var distanceTo = null;
  34332. if (options) {
  34333. computeFacetNormals = (options.facetNormals) ? true : false;
  34334. computeFacetPositions = (options.facetPositions) ? true : false;
  34335. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34336. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34337. ratio = options.ratio || 0;
  34338. computeDepthSort = (options.depthSort) ? true : false;
  34339. distanceTo = (options.distanceTo);
  34340. if (computeDepthSort) {
  34341. if (distanceTo === undefined) {
  34342. distanceTo = BABYLON.Vector3.Zero();
  34343. }
  34344. var depthSortedFacets = options.depthSortedFacets;
  34345. }
  34346. }
  34347. // facetPartitioning reinit if needed
  34348. var xSubRatio = 0;
  34349. var ySubRatio = 0;
  34350. var zSubRatio = 0;
  34351. var subSq = 0;
  34352. if (computeFacetPartitioning && options && options.bbSize) {
  34353. var ox = 0; // X partitioning index for facet position
  34354. var oy = 0; // Y partinioning index for facet position
  34355. var oz = 0; // Z partinioning index for facet position
  34356. var b1x = 0; // X partitioning index for facet v1 vertex
  34357. var b1y = 0; // Y partitioning index for facet v1 vertex
  34358. var b1z = 0; // z partitioning index for facet v1 vertex
  34359. var b2x = 0; // X partitioning index for facet v2 vertex
  34360. var b2y = 0; // Y partitioning index for facet v2 vertex
  34361. var b2z = 0; // Z partitioning index for facet v2 vertex
  34362. var b3x = 0; // X partitioning index for facet v3 vertex
  34363. var b3y = 0; // Y partitioning index for facet v3 vertex
  34364. var b3z = 0; // Z partitioning index for facet v3 vertex
  34365. var block_idx_o = 0; // facet barycenter block index
  34366. var block_idx_v1 = 0; // v1 vertex block index
  34367. var block_idx_v2 = 0; // v2 vertex block index
  34368. var block_idx_v3 = 0; // v3 vertex block index
  34369. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34370. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34371. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34372. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34373. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34374. subSq = options.subDiv.max * options.subDiv.max;
  34375. options.facetPartitioning.length = 0;
  34376. }
  34377. // reset the normals
  34378. for (index = 0; index < positions.length; index++) {
  34379. normals[index] = 0.0;
  34380. }
  34381. // Loop : 1 indice triplet = 1 facet
  34382. var nbFaces = (indices.length / 3) | 0;
  34383. for (index = 0; index < nbFaces; index++) {
  34384. // get the indexes of the coordinates of each vertex of the facet
  34385. v1x = indices[index * 3] * 3;
  34386. v1y = v1x + 1;
  34387. v1z = v1x + 2;
  34388. v2x = indices[index * 3 + 1] * 3;
  34389. v2y = v2x + 1;
  34390. v2z = v2x + 2;
  34391. v3x = indices[index * 3 + 2] * 3;
  34392. v3y = v3x + 1;
  34393. v3z = v3x + 2;
  34394. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34395. p1p2y = positions[v1y] - positions[v2y];
  34396. p1p2z = positions[v1z] - positions[v2z];
  34397. p3p2x = positions[v3x] - positions[v2x];
  34398. p3p2y = positions[v3y] - positions[v2y];
  34399. p3p2z = positions[v3z] - positions[v2z];
  34400. // compute the face normal with the cross product
  34401. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34402. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34403. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34404. // normalize this normal and store it in the array facetData
  34405. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34406. length = (length === 0) ? 1.0 : length;
  34407. faceNormalx /= length;
  34408. faceNormaly /= length;
  34409. faceNormalz /= length;
  34410. if (computeFacetNormals && options) {
  34411. options.facetNormals[index].x = faceNormalx;
  34412. options.facetNormals[index].y = faceNormaly;
  34413. options.facetNormals[index].z = faceNormalz;
  34414. }
  34415. if (computeFacetPositions && options) {
  34416. // compute and the facet barycenter coordinates in the array facetPositions
  34417. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34418. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34419. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34420. }
  34421. if (computeFacetPartitioning && options) {
  34422. // store the facet indexes in arrays in the main facetPartitioning array :
  34423. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34424. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34425. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34426. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34427. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34428. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34429. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34430. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34431. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34432. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34433. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34434. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34435. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34436. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34437. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34438. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34439. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34440. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34441. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34442. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34443. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34444. // push each facet index in each block containing the vertex
  34445. options.facetPartitioning[block_idx_v1].push(index);
  34446. if (block_idx_v2 != block_idx_v1) {
  34447. options.facetPartitioning[block_idx_v2].push(index);
  34448. }
  34449. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34450. options.facetPartitioning[block_idx_v3].push(index);
  34451. }
  34452. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34453. options.facetPartitioning[block_idx_o].push(index);
  34454. }
  34455. }
  34456. if (computeDepthSort && options && options.facetPositions) {
  34457. var dsf = depthSortedFacets[index];
  34458. dsf.ind = index * 3;
  34459. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34460. }
  34461. // compute the normals anyway
  34462. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34463. normals[v1y] += faceNormaly;
  34464. normals[v1z] += faceNormalz;
  34465. normals[v2x] += faceNormalx;
  34466. normals[v2y] += faceNormaly;
  34467. normals[v2z] += faceNormalz;
  34468. normals[v3x] += faceNormalx;
  34469. normals[v3y] += faceNormaly;
  34470. normals[v3z] += faceNormalz;
  34471. }
  34472. // last normalization of each normal
  34473. for (index = 0; index < normals.length / 3; index++) {
  34474. faceNormalx = normals[index * 3];
  34475. faceNormaly = normals[index * 3 + 1];
  34476. faceNormalz = normals[index * 3 + 2];
  34477. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34478. length = (length === 0) ? 1.0 : length;
  34479. faceNormalx /= length;
  34480. faceNormaly /= length;
  34481. faceNormalz /= length;
  34482. normals[index * 3] = faceNormalx;
  34483. normals[index * 3 + 1] = faceNormaly;
  34484. normals[index * 3 + 2] = faceNormalz;
  34485. }
  34486. };
  34487. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34488. var li = indices.length;
  34489. var ln = normals.length;
  34490. var i;
  34491. var n;
  34492. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34493. switch (sideOrientation) {
  34494. case BABYLON.Mesh.FRONTSIDE:
  34495. // nothing changed
  34496. break;
  34497. case BABYLON.Mesh.BACKSIDE:
  34498. var tmp;
  34499. // indices
  34500. for (i = 0; i < li; i += 3) {
  34501. tmp = indices[i];
  34502. indices[i] = indices[i + 2];
  34503. indices[i + 2] = tmp;
  34504. }
  34505. // normals
  34506. for (n = 0; n < ln; n++) {
  34507. normals[n] = -normals[n];
  34508. }
  34509. break;
  34510. case BABYLON.Mesh.DOUBLESIDE:
  34511. // positions
  34512. var lp = positions.length;
  34513. var l = lp / 3;
  34514. for (var p = 0; p < lp; p++) {
  34515. positions[lp + p] = positions[p];
  34516. }
  34517. // indices
  34518. for (i = 0; i < li; i += 3) {
  34519. indices[i + li] = indices[i + 2] + l;
  34520. indices[i + 1 + li] = indices[i + 1] + l;
  34521. indices[i + 2 + li] = indices[i] + l;
  34522. }
  34523. // normals
  34524. for (n = 0; n < ln; n++) {
  34525. normals[ln + n] = -normals[n];
  34526. }
  34527. // uvs
  34528. var lu = uvs.length;
  34529. var u = 0;
  34530. for (u = 0; u < lu; u++) {
  34531. uvs[u + lu] = uvs[u];
  34532. }
  34533. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34534. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34535. u = 0;
  34536. for (i = 0; i < lu / 2; i++) {
  34537. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34538. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34539. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34540. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34541. u += 2;
  34542. }
  34543. break;
  34544. }
  34545. };
  34546. /**
  34547. * Creates a new VertexData from the imported parameters.
  34548. */
  34549. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34550. var vertexData = new VertexData();
  34551. // positions
  34552. var positions = parsedVertexData.positions;
  34553. if (positions) {
  34554. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34555. }
  34556. // normals
  34557. var normals = parsedVertexData.normals;
  34558. if (normals) {
  34559. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34560. }
  34561. // tangents
  34562. var tangents = parsedVertexData.tangents;
  34563. if (tangents) {
  34564. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34565. }
  34566. // uvs
  34567. var uvs = parsedVertexData.uvs;
  34568. if (uvs) {
  34569. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34570. }
  34571. // uv2s
  34572. var uv2s = parsedVertexData.uv2s;
  34573. if (uv2s) {
  34574. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34575. }
  34576. // uv3s
  34577. var uv3s = parsedVertexData.uv3s;
  34578. if (uv3s) {
  34579. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34580. }
  34581. // uv4s
  34582. var uv4s = parsedVertexData.uv4s;
  34583. if (uv4s) {
  34584. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34585. }
  34586. // uv5s
  34587. var uv5s = parsedVertexData.uv5s;
  34588. if (uv5s) {
  34589. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34590. }
  34591. // uv6s
  34592. var uv6s = parsedVertexData.uv6s;
  34593. if (uv6s) {
  34594. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34595. }
  34596. // colors
  34597. var colors = parsedVertexData.colors;
  34598. if (colors) {
  34599. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34600. }
  34601. // matricesIndices
  34602. var matricesIndices = parsedVertexData.matricesIndices;
  34603. if (matricesIndices) {
  34604. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34605. }
  34606. // matricesWeights
  34607. var matricesWeights = parsedVertexData.matricesWeights;
  34608. if (matricesWeights) {
  34609. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34610. }
  34611. // indices
  34612. var indices = parsedVertexData.indices;
  34613. if (indices) {
  34614. vertexData.indices = indices;
  34615. }
  34616. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34617. };
  34618. return VertexData;
  34619. }());
  34620. BABYLON.VertexData = VertexData;
  34621. })(BABYLON || (BABYLON = {}));
  34622. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34623. var BABYLON;
  34624. (function (BABYLON) {
  34625. /**
  34626. * Class used to store geometry data (vertex buffers + index buffer)
  34627. */
  34628. var Geometry = /** @class */ (function () {
  34629. /**
  34630. * Creates a new geometry
  34631. * @param id defines the unique ID
  34632. * @param scene defines the hosting scene
  34633. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34634. * @param updatable defines if geometry must be updatable (false by default)
  34635. * @param mesh defines the mesh that will be associated with the geometry
  34636. */
  34637. function Geometry(id, scene, vertexData, updatable, mesh) {
  34638. if (updatable === void 0) { updatable = false; }
  34639. if (mesh === void 0) { mesh = null; }
  34640. /**
  34641. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34642. */
  34643. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34644. this._totalVertices = 0;
  34645. this._isDisposed = false;
  34646. this._indexBufferIsUpdatable = false;
  34647. this.id = id;
  34648. this._engine = scene.getEngine();
  34649. this._meshes = [];
  34650. this._scene = scene;
  34651. //Init vertex buffer cache
  34652. this._vertexBuffers = {};
  34653. this._indices = [];
  34654. this._updatable = updatable;
  34655. // vertexData
  34656. if (vertexData) {
  34657. this.setAllVerticesData(vertexData, updatable);
  34658. }
  34659. else {
  34660. this._totalVertices = 0;
  34661. this._indices = [];
  34662. }
  34663. if (this._engine.getCaps().vertexArrayObject) {
  34664. this._vertexArrayObjects = {};
  34665. }
  34666. // applyToMesh
  34667. if (mesh) {
  34668. if (mesh.getClassName() === "LinesMesh") {
  34669. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34670. this.updateExtend();
  34671. }
  34672. this.applyToMesh(mesh);
  34673. mesh.computeWorldMatrix(true);
  34674. }
  34675. }
  34676. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34677. /**
  34678. * 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
  34679. */
  34680. get: function () {
  34681. return this._boundingBias;
  34682. },
  34683. /**
  34684. * 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
  34685. */
  34686. set: function (value) {
  34687. if (this._boundingBias && this._boundingBias.equals(value)) {
  34688. return;
  34689. }
  34690. this._boundingBias = value.clone();
  34691. this.updateBoundingInfo(true, null);
  34692. },
  34693. enumerable: true,
  34694. configurable: true
  34695. });
  34696. /**
  34697. * Static function used to attach a new empty geometry to a mesh
  34698. * @param mesh defines the mesh to attach the geometry to
  34699. * @returns the new {BABYLON.Geometry}
  34700. */
  34701. Geometry.CreateGeometryForMesh = function (mesh) {
  34702. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34703. geometry.applyToMesh(mesh);
  34704. return geometry;
  34705. };
  34706. Object.defineProperty(Geometry.prototype, "extend", {
  34707. /**
  34708. * Gets the current extend of the geometry
  34709. */
  34710. get: function () {
  34711. return this._extend;
  34712. },
  34713. enumerable: true,
  34714. configurable: true
  34715. });
  34716. /**
  34717. * Gets the hosting scene
  34718. * @returns the hosting {BABYLON.Scene}
  34719. */
  34720. Geometry.prototype.getScene = function () {
  34721. return this._scene;
  34722. };
  34723. /**
  34724. * Gets the hosting engine
  34725. * @returns the hosting {BABYLON.Engine}
  34726. */
  34727. Geometry.prototype.getEngine = function () {
  34728. return this._engine;
  34729. };
  34730. /**
  34731. * Defines if the geometry is ready to use
  34732. * @returns true if the geometry is ready to be used
  34733. */
  34734. Geometry.prototype.isReady = function () {
  34735. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34736. };
  34737. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34738. /**
  34739. * Gets a value indicating that the geometry should not be serialized
  34740. */
  34741. get: function () {
  34742. for (var index = 0; index < this._meshes.length; index++) {
  34743. if (!this._meshes[index].doNotSerialize) {
  34744. return false;
  34745. }
  34746. }
  34747. return true;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. /** @ignore */
  34753. Geometry.prototype._rebuild = function () {
  34754. if (this._vertexArrayObjects) {
  34755. this._vertexArrayObjects = {};
  34756. }
  34757. // Index buffer
  34758. if (this._meshes.length !== 0 && this._indices) {
  34759. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34760. }
  34761. // Vertex buffers
  34762. for (var key in this._vertexBuffers) {
  34763. var vertexBuffer = this._vertexBuffers[key];
  34764. vertexBuffer._rebuild();
  34765. }
  34766. };
  34767. /**
  34768. * Affects all gemetry data in one call
  34769. * @param vertexData defines the geometry data
  34770. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34771. */
  34772. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34773. vertexData.applyToGeometry(this, updatable);
  34774. this.notifyUpdate();
  34775. };
  34776. /**
  34777. * Set specific vertex data
  34778. * @param kind defines the data kind (Position, normal, etc...)
  34779. * @param data defines the vertex data to use
  34780. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34781. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34782. */
  34783. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34784. if (updatable === void 0) { updatable = false; }
  34785. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34786. this.setVerticesBuffer(buffer);
  34787. };
  34788. /**
  34789. * Removes a specific vertex data
  34790. * @param kind defines the data kind (Position, normal, etc...)
  34791. */
  34792. Geometry.prototype.removeVerticesData = function (kind) {
  34793. if (this._vertexBuffers[kind]) {
  34794. this._vertexBuffers[kind].dispose();
  34795. delete this._vertexBuffers[kind];
  34796. }
  34797. };
  34798. /**
  34799. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34800. * @param buffer defines the vertex buffer to use
  34801. */
  34802. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34803. var kind = buffer.getKind();
  34804. if (this._vertexBuffers[kind]) {
  34805. this._vertexBuffers[kind].dispose();
  34806. }
  34807. this._vertexBuffers[kind] = buffer;
  34808. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34809. var data = buffer.getData();
  34810. var stride = buffer.getStrideSize();
  34811. this._totalVertices = data.length / stride;
  34812. this.updateExtend(data, stride);
  34813. this._resetPointsArrayCache();
  34814. var meshes = this._meshes;
  34815. var numOfMeshes = meshes.length;
  34816. for (var index = 0; index < numOfMeshes; index++) {
  34817. var mesh = meshes[index];
  34818. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34819. mesh._createGlobalSubMesh(false);
  34820. mesh.computeWorldMatrix(true);
  34821. }
  34822. }
  34823. this.notifyUpdate(kind);
  34824. if (this._vertexArrayObjects) {
  34825. this._disposeVertexArrayObjects();
  34826. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34827. }
  34828. };
  34829. /**
  34830. * Update a specific vertex buffer
  34831. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34832. * It will do nothing if the buffer is not updatable
  34833. * @param kind defines the data kind (Position, normal, etc...)
  34834. * @param data defines the data to use
  34835. * @param offset defines the offset in the target buffer where to store the data
  34836. */
  34837. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34838. var vertexBuffer = this.getVertexBuffer(kind);
  34839. if (!vertexBuffer) {
  34840. return;
  34841. }
  34842. vertexBuffer.updateDirectly(data, offset);
  34843. this.notifyUpdate(kind);
  34844. };
  34845. /**
  34846. * Update a specific vertex buffer
  34847. * This function will create a new buffer if the current one is not updatable
  34848. * @param kind defines the data kind (Position, normal, etc...)
  34849. * @param data defines the data to use
  34850. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34851. */
  34852. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34853. if (updateExtends === void 0) { updateExtends = false; }
  34854. var vertexBuffer = this.getVertexBuffer(kind);
  34855. if (!vertexBuffer) {
  34856. return;
  34857. }
  34858. vertexBuffer.update(data);
  34859. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34860. var stride = vertexBuffer.getStrideSize();
  34861. this._totalVertices = data.length / stride;
  34862. this.updateBoundingInfo(updateExtends, data);
  34863. }
  34864. this.notifyUpdate(kind);
  34865. };
  34866. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34867. if (updateExtends) {
  34868. this.updateExtend(data);
  34869. }
  34870. var meshes = this._meshes;
  34871. var numOfMeshes = meshes.length;
  34872. this._resetPointsArrayCache();
  34873. for (var index = 0; index < numOfMeshes; index++) {
  34874. var mesh = meshes[index];
  34875. if (updateExtends) {
  34876. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34877. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34878. var subMesh = mesh.subMeshes[subIndex];
  34879. subMesh.refreshBoundingInfo();
  34880. }
  34881. }
  34882. }
  34883. };
  34884. /** @ignore */
  34885. Geometry.prototype._bind = function (effect, indexToBind) {
  34886. if (!effect) {
  34887. return;
  34888. }
  34889. if (indexToBind === undefined) {
  34890. indexToBind = this._indexBuffer;
  34891. }
  34892. var vbs = this.getVertexBuffers();
  34893. if (!vbs) {
  34894. return;
  34895. }
  34896. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34897. this._engine.bindBuffers(vbs, indexToBind, effect);
  34898. return;
  34899. }
  34900. // Using VAO
  34901. if (!this._vertexArrayObjects[effect.key]) {
  34902. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34903. }
  34904. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34905. };
  34906. /**
  34907. * Gets total number of vertices
  34908. * @returns the total number of vertices
  34909. */
  34910. Geometry.prototype.getTotalVertices = function () {
  34911. if (!this.isReady()) {
  34912. return 0;
  34913. }
  34914. return this._totalVertices;
  34915. };
  34916. /**
  34917. * Gets a specific vertex data attached to this geometry
  34918. * @param kind defines the data kind (Position, normal, etc...)
  34919. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34920. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34921. * @returns a float array containing vertex data
  34922. */
  34923. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34924. var vertexBuffer = this.getVertexBuffer(kind);
  34925. if (!vertexBuffer) {
  34926. return null;
  34927. }
  34928. var orig = vertexBuffer.getData();
  34929. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34930. return orig;
  34931. }
  34932. else {
  34933. var len = orig.length;
  34934. var copy = [];
  34935. for (var i = 0; i < len; i++) {
  34936. copy.push(orig[i]);
  34937. }
  34938. return copy;
  34939. }
  34940. };
  34941. /**
  34942. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34943. * @param kind defines the data kind (Position, normal, etc...)
  34944. * @returns true if the vertex buffer with the specified kind is updatable
  34945. */
  34946. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34947. var vb = this._vertexBuffers[kind];
  34948. if (!vb) {
  34949. return false;
  34950. }
  34951. return vb.isUpdatable();
  34952. };
  34953. /**
  34954. * Gets a specific vertex buffer
  34955. * @param kind defines the data kind (Position, normal, etc...)
  34956. * @returns a {BABYLON.VertexBuffer}
  34957. */
  34958. Geometry.prototype.getVertexBuffer = function (kind) {
  34959. if (!this.isReady()) {
  34960. return null;
  34961. }
  34962. return this._vertexBuffers[kind];
  34963. };
  34964. /**
  34965. * Returns all vertex buffers
  34966. * @return an object holding all vertex buffers indexed by kind
  34967. */
  34968. Geometry.prototype.getVertexBuffers = function () {
  34969. if (!this.isReady()) {
  34970. return null;
  34971. }
  34972. return this._vertexBuffers;
  34973. };
  34974. /**
  34975. * Gets a boolean indicating if specific vertex buffer is present
  34976. * @param kind defines the data kind (Position, normal, etc...)
  34977. * @returns true if data is present
  34978. */
  34979. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34980. if (!this._vertexBuffers) {
  34981. if (this._delayInfo) {
  34982. return this._delayInfo.indexOf(kind) !== -1;
  34983. }
  34984. return false;
  34985. }
  34986. return this._vertexBuffers[kind] !== undefined;
  34987. };
  34988. /**
  34989. * Gets a list of all attached data kinds (Position, normal, etc...)
  34990. * @returns a list of string containing all kinds
  34991. */
  34992. Geometry.prototype.getVerticesDataKinds = function () {
  34993. var result = [];
  34994. var kind;
  34995. if (!this._vertexBuffers && this._delayInfo) {
  34996. for (kind in this._delayInfo) {
  34997. result.push(kind);
  34998. }
  34999. }
  35000. else {
  35001. for (kind in this._vertexBuffers) {
  35002. result.push(kind);
  35003. }
  35004. }
  35005. return result;
  35006. };
  35007. /**
  35008. * Update index buffer
  35009. * @param indices defines the indices to store in the index buffer
  35010. * @param offset defines the offset in the target buffer where to store the data
  35011. */
  35012. Geometry.prototype.updateIndices = function (indices, offset) {
  35013. if (!this._indexBuffer) {
  35014. return;
  35015. }
  35016. if (!this._indexBufferIsUpdatable) {
  35017. this.setIndices(indices, null, true);
  35018. }
  35019. else {
  35020. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35021. }
  35022. };
  35023. /**
  35024. * Creates a new index buffer
  35025. * @param indices defines the indices to store in the index buffer
  35026. * @param totalVertices defines the total number of vertices (could be null)
  35027. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35028. */
  35029. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35030. if (totalVertices === void 0) { totalVertices = null; }
  35031. if (updatable === void 0) { updatable = false; }
  35032. if (this._indexBuffer) {
  35033. this._engine._releaseBuffer(this._indexBuffer);
  35034. }
  35035. this._disposeVertexArrayObjects();
  35036. this._indices = indices;
  35037. this._indexBufferIsUpdatable = updatable;
  35038. if (this._meshes.length !== 0 && this._indices) {
  35039. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35040. }
  35041. if (totalVertices != undefined) {
  35042. this._totalVertices = totalVertices;
  35043. }
  35044. var meshes = this._meshes;
  35045. var numOfMeshes = meshes.length;
  35046. for (var index = 0; index < numOfMeshes; index++) {
  35047. meshes[index]._createGlobalSubMesh(true);
  35048. }
  35049. this.notifyUpdate();
  35050. };
  35051. /**
  35052. * Return the total number of indices
  35053. * @returns the total number of indices
  35054. */
  35055. Geometry.prototype.getTotalIndices = function () {
  35056. if (!this.isReady()) {
  35057. return 0;
  35058. }
  35059. return this._indices.length;
  35060. };
  35061. /**
  35062. * Gets the index buffer array
  35063. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35064. * @returns the index buffer array
  35065. */
  35066. Geometry.prototype.getIndices = function (copyWhenShared) {
  35067. if (!this.isReady()) {
  35068. return null;
  35069. }
  35070. var orig = this._indices;
  35071. if (!copyWhenShared || this._meshes.length === 1) {
  35072. return orig;
  35073. }
  35074. else {
  35075. var len = orig.length;
  35076. var copy = [];
  35077. for (var i = 0; i < len; i++) {
  35078. copy.push(orig[i]);
  35079. }
  35080. return copy;
  35081. }
  35082. };
  35083. /**
  35084. * Gets the index buffer
  35085. * @return the index buffer
  35086. */
  35087. Geometry.prototype.getIndexBuffer = function () {
  35088. if (!this.isReady()) {
  35089. return null;
  35090. }
  35091. return this._indexBuffer;
  35092. };
  35093. /** @ignore */
  35094. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35095. if (effect === void 0) { effect = null; }
  35096. if (!effect || !this._vertexArrayObjects) {
  35097. return;
  35098. }
  35099. if (this._vertexArrayObjects[effect.key]) {
  35100. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35101. delete this._vertexArrayObjects[effect.key];
  35102. }
  35103. };
  35104. /**
  35105. * Release the associated resources for a specific mesh
  35106. * @param mesh defines the source mesh
  35107. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35108. */
  35109. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35110. var meshes = this._meshes;
  35111. var index = meshes.indexOf(mesh);
  35112. if (index === -1) {
  35113. return;
  35114. }
  35115. meshes.splice(index, 1);
  35116. mesh._geometry = null;
  35117. if (meshes.length === 0 && shouldDispose) {
  35118. this.dispose();
  35119. }
  35120. };
  35121. /**
  35122. * Apply current geometry to a given mesh
  35123. * @param mesh defines the mesh to apply geometry to
  35124. */
  35125. Geometry.prototype.applyToMesh = function (mesh) {
  35126. if (mesh._geometry === this) {
  35127. return;
  35128. }
  35129. var previousGeometry = mesh._geometry;
  35130. if (previousGeometry) {
  35131. previousGeometry.releaseForMesh(mesh);
  35132. }
  35133. var meshes = this._meshes;
  35134. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35135. mesh._geometry = this;
  35136. this._scene.pushGeometry(this);
  35137. meshes.push(mesh);
  35138. if (this.isReady()) {
  35139. this._applyToMesh(mesh);
  35140. }
  35141. else {
  35142. mesh._boundingInfo = this._boundingInfo;
  35143. }
  35144. };
  35145. Geometry.prototype.updateExtend = function (data, stride) {
  35146. if (data === void 0) { data = null; }
  35147. if (!data) {
  35148. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35149. }
  35150. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35151. };
  35152. Geometry.prototype._applyToMesh = function (mesh) {
  35153. var numOfMeshes = this._meshes.length;
  35154. // vertexBuffers
  35155. for (var kind in this._vertexBuffers) {
  35156. if (numOfMeshes === 1) {
  35157. this._vertexBuffers[kind].create();
  35158. }
  35159. var buffer = this._vertexBuffers[kind].getBuffer();
  35160. if (buffer)
  35161. buffer.references = numOfMeshes;
  35162. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35163. if (!this._extend) {
  35164. this.updateExtend(this._vertexBuffers[kind].getData());
  35165. }
  35166. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35167. mesh._createGlobalSubMesh(false);
  35168. //bounding info was just created again, world matrix should be applied again.
  35169. mesh._updateBoundingInfo();
  35170. }
  35171. }
  35172. // indexBuffer
  35173. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35174. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35175. }
  35176. if (this._indexBuffer) {
  35177. this._indexBuffer.references = numOfMeshes;
  35178. }
  35179. };
  35180. Geometry.prototype.notifyUpdate = function (kind) {
  35181. if (this.onGeometryUpdated) {
  35182. this.onGeometryUpdated(this, kind);
  35183. }
  35184. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35185. var mesh = _a[_i];
  35186. mesh._markSubMeshesAsAttributesDirty();
  35187. }
  35188. };
  35189. /**
  35190. * Load the geometry if it was flagged as delay loaded
  35191. * @param scene defines the hosting scene
  35192. * @param onLoaded defines a callback called when the geometry is loaded
  35193. */
  35194. Geometry.prototype.load = function (scene, onLoaded) {
  35195. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35196. return;
  35197. }
  35198. if (this.isReady()) {
  35199. if (onLoaded) {
  35200. onLoaded();
  35201. }
  35202. return;
  35203. }
  35204. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35205. this._queueLoad(scene, onLoaded);
  35206. };
  35207. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35208. var _this = this;
  35209. if (!this.delayLoadingFile) {
  35210. return;
  35211. }
  35212. scene._addPendingData(this);
  35213. scene._loadFile(this.delayLoadingFile, function (data) {
  35214. if (!_this._delayLoadingFunction) {
  35215. return;
  35216. }
  35217. _this._delayLoadingFunction(JSON.parse(data), _this);
  35218. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35219. _this._delayInfo = [];
  35220. scene._removePendingData(_this);
  35221. var meshes = _this._meshes;
  35222. var numOfMeshes = meshes.length;
  35223. for (var index = 0; index < numOfMeshes; index++) {
  35224. _this._applyToMesh(meshes[index]);
  35225. }
  35226. if (onLoaded) {
  35227. onLoaded();
  35228. }
  35229. }, undefined, true);
  35230. };
  35231. /**
  35232. * Invert the geometry to move from a right handed system to a left handed one.
  35233. */
  35234. Geometry.prototype.toLeftHanded = function () {
  35235. // Flip faces
  35236. var tIndices = this.getIndices(false);
  35237. if (tIndices != null && tIndices.length > 0) {
  35238. for (var i = 0; i < tIndices.length; i += 3) {
  35239. var tTemp = tIndices[i + 0];
  35240. tIndices[i + 0] = tIndices[i + 2];
  35241. tIndices[i + 2] = tTemp;
  35242. }
  35243. this.setIndices(tIndices);
  35244. }
  35245. // Negate position.z
  35246. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35247. if (tPositions != null && tPositions.length > 0) {
  35248. for (var i = 0; i < tPositions.length; i += 3) {
  35249. tPositions[i + 2] = -tPositions[i + 2];
  35250. }
  35251. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35252. }
  35253. // Negate normal.z
  35254. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35255. if (tNormals != null && tNormals.length > 0) {
  35256. for (var i = 0; i < tNormals.length; i += 3) {
  35257. tNormals[i + 2] = -tNormals[i + 2];
  35258. }
  35259. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35260. }
  35261. };
  35262. // Cache
  35263. /** @ignore */
  35264. Geometry.prototype._resetPointsArrayCache = function () {
  35265. this._positions = null;
  35266. };
  35267. /** @ignore */
  35268. Geometry.prototype._generatePointsArray = function () {
  35269. if (this._positions)
  35270. return true;
  35271. this._positions = [];
  35272. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35273. if (!data) {
  35274. return false;
  35275. }
  35276. for (var index = 0; index < data.length; index += 3) {
  35277. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35278. }
  35279. return true;
  35280. };
  35281. /**
  35282. * Gets a value indicating if the geometry is disposed
  35283. * @returns true if the geometry was disposed
  35284. */
  35285. Geometry.prototype.isDisposed = function () {
  35286. return this._isDisposed;
  35287. };
  35288. Geometry.prototype._disposeVertexArrayObjects = function () {
  35289. if (this._vertexArrayObjects) {
  35290. for (var kind in this._vertexArrayObjects) {
  35291. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35292. }
  35293. this._vertexArrayObjects = {};
  35294. }
  35295. };
  35296. /**
  35297. * Free all associated resources
  35298. */
  35299. Geometry.prototype.dispose = function () {
  35300. var meshes = this._meshes;
  35301. var numOfMeshes = meshes.length;
  35302. var index;
  35303. for (index = 0; index < numOfMeshes; index++) {
  35304. this.releaseForMesh(meshes[index]);
  35305. }
  35306. this._meshes = [];
  35307. this._disposeVertexArrayObjects();
  35308. for (var kind in this._vertexBuffers) {
  35309. this._vertexBuffers[kind].dispose();
  35310. }
  35311. this._vertexBuffers = {};
  35312. this._totalVertices = 0;
  35313. if (this._indexBuffer) {
  35314. this._engine._releaseBuffer(this._indexBuffer);
  35315. }
  35316. this._indexBuffer = null;
  35317. this._indices = [];
  35318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35319. this.delayLoadingFile = null;
  35320. this._delayLoadingFunction = null;
  35321. this._delayInfo = [];
  35322. this._boundingInfo = null;
  35323. this._scene.removeGeometry(this);
  35324. this._isDisposed = true;
  35325. };
  35326. /**
  35327. * Clone the current geometry into a new geometry
  35328. * @param id defines the unique ID of the new geometry
  35329. * @returns a new geometry object
  35330. */
  35331. Geometry.prototype.copy = function (id) {
  35332. var vertexData = new BABYLON.VertexData();
  35333. vertexData.indices = [];
  35334. var indices = this.getIndices();
  35335. if (indices) {
  35336. for (var index = 0; index < indices.length; index++) {
  35337. vertexData.indices.push(indices[index]);
  35338. }
  35339. }
  35340. var updatable = false;
  35341. var stopChecking = false;
  35342. var kind;
  35343. for (kind in this._vertexBuffers) {
  35344. // using slice() to make a copy of the array and not just reference it
  35345. var data = this.getVerticesData(kind);
  35346. if (data instanceof Float32Array) {
  35347. vertexData.set(new Float32Array(data), kind);
  35348. }
  35349. else {
  35350. vertexData.set(data.slice(0), kind);
  35351. }
  35352. if (!stopChecking) {
  35353. var vb = this.getVertexBuffer(kind);
  35354. if (vb) {
  35355. updatable = vb.isUpdatable();
  35356. stopChecking = !updatable;
  35357. }
  35358. }
  35359. }
  35360. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35361. geometry.delayLoadState = this.delayLoadState;
  35362. geometry.delayLoadingFile = this.delayLoadingFile;
  35363. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35364. for (kind in this._delayInfo) {
  35365. geometry._delayInfo = geometry._delayInfo || [];
  35366. geometry._delayInfo.push(kind);
  35367. }
  35368. // Bounding info
  35369. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35370. return geometry;
  35371. };
  35372. /**
  35373. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35374. * @return a JSON representation of the current geometry data (without the vertices data)
  35375. */
  35376. Geometry.prototype.serialize = function () {
  35377. var serializationObject = {};
  35378. serializationObject.id = this.id;
  35379. serializationObject.updatable = this._updatable;
  35380. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35381. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35382. }
  35383. return serializationObject;
  35384. };
  35385. Geometry.prototype.toNumberArray = function (origin) {
  35386. if (Array.isArray(origin)) {
  35387. return origin;
  35388. }
  35389. else {
  35390. return Array.prototype.slice.call(origin);
  35391. }
  35392. };
  35393. /**
  35394. * Serialize all vertices data into a JSON oject
  35395. * @returns a JSON representation of the current geometry data
  35396. */
  35397. Geometry.prototype.serializeVerticeData = function () {
  35398. var serializationObject = this.serialize();
  35399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35400. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35401. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35402. serializationObject.positions._updatable = true;
  35403. }
  35404. }
  35405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35406. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35407. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35408. serializationObject.normals._updatable = true;
  35409. }
  35410. }
  35411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35412. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35413. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35414. serializationObject.tangets._updatable = true;
  35415. }
  35416. }
  35417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35418. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35420. serializationObject.uvs._updatable = true;
  35421. }
  35422. }
  35423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35424. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35426. serializationObject.uv2s._updatable = true;
  35427. }
  35428. }
  35429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35430. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35431. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35432. serializationObject.uv3s._updatable = true;
  35433. }
  35434. }
  35435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35436. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35437. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35438. serializationObject.uv4s._updatable = true;
  35439. }
  35440. }
  35441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35442. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35444. serializationObject.uv5s._updatable = true;
  35445. }
  35446. }
  35447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35448. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35449. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35450. serializationObject.uv6s._updatable = true;
  35451. }
  35452. }
  35453. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35454. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35455. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35456. serializationObject.colors._updatable = true;
  35457. }
  35458. }
  35459. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35460. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35461. serializationObject.matricesIndices._isExpanded = true;
  35462. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35463. serializationObject.matricesIndices._updatable = true;
  35464. }
  35465. }
  35466. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35467. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35468. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35469. serializationObject.matricesWeights._updatable = true;
  35470. }
  35471. }
  35472. serializationObject.indices = this.toNumberArray(this.getIndices());
  35473. return serializationObject;
  35474. };
  35475. // Statics
  35476. /**
  35477. * Extracts a clone of a mesh geometry
  35478. * @param mesh defines the source mesh
  35479. * @param id defines the unique ID of the new geometry object
  35480. * @returns the new geometry object
  35481. */
  35482. Geometry.ExtractFromMesh = function (mesh, id) {
  35483. var geometry = mesh._geometry;
  35484. if (!geometry) {
  35485. return null;
  35486. }
  35487. return geometry.copy(id);
  35488. };
  35489. /**
  35490. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35491. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35492. * Be aware Math.random() could cause collisions, but:
  35493. * "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"
  35494. * @returns a string containing a new GUID
  35495. */
  35496. Geometry.RandomId = function () {
  35497. return BABYLON.Tools.RandomId();
  35498. };
  35499. /** @ignore */
  35500. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35501. var scene = mesh.getScene();
  35502. // Geometry
  35503. var geometryId = parsedGeometry.geometryId;
  35504. if (geometryId) {
  35505. var geometry = scene.getGeometryByID(geometryId);
  35506. if (geometry) {
  35507. geometry.applyToMesh(mesh);
  35508. }
  35509. }
  35510. else if (parsedGeometry instanceof ArrayBuffer) {
  35511. var binaryInfo = mesh._binaryInfo;
  35512. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35513. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35514. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35515. }
  35516. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35517. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35518. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35519. }
  35520. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35521. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35522. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35523. }
  35524. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35525. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35526. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35527. }
  35528. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35529. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35530. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35531. }
  35532. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35533. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35534. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35535. }
  35536. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35537. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35538. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35539. }
  35540. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35541. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35542. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35543. }
  35544. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35545. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35546. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35547. }
  35548. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35549. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35550. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35551. }
  35552. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35553. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35555. }
  35556. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35557. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35558. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35559. }
  35560. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35561. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35562. mesh.setIndices(indicesData, null);
  35563. }
  35564. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35565. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35566. mesh.subMeshes = [];
  35567. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35568. var materialIndex = subMeshesData[(i * 5) + 0];
  35569. var verticesStart = subMeshesData[(i * 5) + 1];
  35570. var verticesCount = subMeshesData[(i * 5) + 2];
  35571. var indexStart = subMeshesData[(i * 5) + 3];
  35572. var indexCount = subMeshesData[(i * 5) + 4];
  35573. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35574. }
  35575. }
  35576. }
  35577. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35579. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35580. if (parsedGeometry.tangents) {
  35581. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35582. }
  35583. if (parsedGeometry.uvs) {
  35584. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35585. }
  35586. if (parsedGeometry.uvs2) {
  35587. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35588. }
  35589. if (parsedGeometry.uvs3) {
  35590. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35591. }
  35592. if (parsedGeometry.uvs4) {
  35593. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35594. }
  35595. if (parsedGeometry.uvs5) {
  35596. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35597. }
  35598. if (parsedGeometry.uvs6) {
  35599. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35600. }
  35601. if (parsedGeometry.colors) {
  35602. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35603. }
  35604. if (parsedGeometry.matricesIndices) {
  35605. if (!parsedGeometry.matricesIndices._isExpanded) {
  35606. var floatIndices = [];
  35607. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35608. var matricesIndex = parsedGeometry.matricesIndices[i];
  35609. floatIndices.push(matricesIndex & 0x000000FF);
  35610. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35611. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35612. floatIndices.push(matricesIndex >> 24);
  35613. }
  35614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35615. }
  35616. else {
  35617. delete parsedGeometry.matricesIndices._isExpanded;
  35618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35619. }
  35620. }
  35621. if (parsedGeometry.matricesIndicesExtra) {
  35622. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35623. var floatIndices = [];
  35624. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35625. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35626. floatIndices.push(matricesIndex & 0x000000FF);
  35627. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35628. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35629. floatIndices.push(matricesIndex >> 24);
  35630. }
  35631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35632. }
  35633. else {
  35634. delete parsedGeometry.matricesIndices._isExpanded;
  35635. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35636. }
  35637. }
  35638. if (parsedGeometry.matricesWeights) {
  35639. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35641. }
  35642. if (parsedGeometry.matricesWeightsExtra) {
  35643. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35644. }
  35645. mesh.setIndices(parsedGeometry.indices, null);
  35646. }
  35647. // SubMeshes
  35648. if (parsedGeometry.subMeshes) {
  35649. mesh.subMeshes = [];
  35650. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35651. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35652. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35653. }
  35654. }
  35655. // Flat shading
  35656. if (mesh._shouldGenerateFlatShading) {
  35657. mesh.convertToFlatShadedMesh();
  35658. delete mesh._shouldGenerateFlatShading;
  35659. }
  35660. // Update
  35661. mesh.computeWorldMatrix(true);
  35662. // Octree
  35663. var sceneOctree = scene.selectionOctree;
  35664. if (sceneOctree !== undefined && sceneOctree !== null) {
  35665. sceneOctree.addMesh(mesh);
  35666. }
  35667. };
  35668. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35669. var epsilon = 1e-3;
  35670. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35671. return;
  35672. }
  35673. var noInfluenceBoneIndex = 0.0;
  35674. if (parsedGeometry.skeletonId > -1) {
  35675. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35676. if (!skeleton) {
  35677. return;
  35678. }
  35679. noInfluenceBoneIndex = skeleton.bones.length;
  35680. }
  35681. else {
  35682. return;
  35683. }
  35684. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35685. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35686. var matricesWeights = parsedGeometry.matricesWeights;
  35687. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35688. var influencers = parsedGeometry.numBoneInfluencer;
  35689. var size = matricesWeights.length;
  35690. for (var i = 0; i < size; i += 4) {
  35691. var weight = 0.0;
  35692. var firstZeroWeight = -1;
  35693. for (var j = 0; j < 4; j++) {
  35694. var w = matricesWeights[i + j];
  35695. weight += w;
  35696. if (w < epsilon && firstZeroWeight < 0) {
  35697. firstZeroWeight = j;
  35698. }
  35699. }
  35700. if (matricesWeightsExtra) {
  35701. for (var j = 0; j < 4; j++) {
  35702. var w = matricesWeightsExtra[i + j];
  35703. weight += w;
  35704. if (w < epsilon && firstZeroWeight < 0) {
  35705. firstZeroWeight = j + 4;
  35706. }
  35707. }
  35708. }
  35709. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35710. firstZeroWeight = influencers - 1;
  35711. }
  35712. if (weight > epsilon) {
  35713. var mweight = 1.0 / weight;
  35714. for (var j = 0; j < 4; j++) {
  35715. matricesWeights[i + j] *= mweight;
  35716. }
  35717. if (matricesWeightsExtra) {
  35718. for (var j = 0; j < 4; j++) {
  35719. matricesWeightsExtra[i + j] *= mweight;
  35720. }
  35721. }
  35722. }
  35723. else {
  35724. if (firstZeroWeight >= 4) {
  35725. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35726. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35727. }
  35728. else {
  35729. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35730. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35731. }
  35732. }
  35733. }
  35734. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35735. if (parsedGeometry.matricesWeightsExtra) {
  35736. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35737. }
  35738. };
  35739. /**
  35740. * Create a new geometry from persisted data (Using .babylon file format)
  35741. * @param parsedVertexData defines the persisted data
  35742. * @param scene defines the hosting scene
  35743. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35744. * @returns the new geometry object
  35745. */
  35746. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35747. if (scene.getGeometryByID(parsedVertexData.id)) {
  35748. return null; // null since geometry could be something else than a box...
  35749. }
  35750. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35751. if (BABYLON.Tags) {
  35752. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35753. }
  35754. if (parsedVertexData.delayLoadingFile) {
  35755. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35756. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35757. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35758. geometry._delayInfo = [];
  35759. if (parsedVertexData.hasUVs) {
  35760. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35761. }
  35762. if (parsedVertexData.hasUVs2) {
  35763. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35764. }
  35765. if (parsedVertexData.hasUVs3) {
  35766. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35767. }
  35768. if (parsedVertexData.hasUVs4) {
  35769. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35770. }
  35771. if (parsedVertexData.hasUVs5) {
  35772. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35773. }
  35774. if (parsedVertexData.hasUVs6) {
  35775. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35776. }
  35777. if (parsedVertexData.hasColors) {
  35778. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35779. }
  35780. if (parsedVertexData.hasMatricesIndices) {
  35781. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35782. }
  35783. if (parsedVertexData.hasMatricesWeights) {
  35784. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35785. }
  35786. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35787. }
  35788. else {
  35789. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35790. }
  35791. scene.pushGeometry(geometry, true);
  35792. return geometry;
  35793. };
  35794. return Geometry;
  35795. }());
  35796. BABYLON.Geometry = Geometry;
  35797. // Primitives
  35798. /// Abstract class
  35799. /**
  35800. * Abstract class used to provide common services for all typed geometries
  35801. */
  35802. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35803. __extends(_PrimitiveGeometry, _super);
  35804. /**
  35805. * Creates a new typed geometry
  35806. * @param id defines the unique ID of the geometry
  35807. * @param scene defines the hosting scene
  35808. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35809. * @param mesh defines the hosting mesh (can be null)
  35810. */
  35811. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35812. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35813. if (mesh === void 0) { mesh = null; }
  35814. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35815. _this._canBeRegenerated = _canBeRegenerated;
  35816. _this._beingRegenerated = true;
  35817. _this.regenerate();
  35818. _this._beingRegenerated = false;
  35819. return _this;
  35820. }
  35821. /**
  35822. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35823. * @returns true if the geometry can be regenerated
  35824. */
  35825. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35826. return this._canBeRegenerated;
  35827. };
  35828. /**
  35829. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35830. */
  35831. _PrimitiveGeometry.prototype.regenerate = function () {
  35832. if (!this._canBeRegenerated) {
  35833. return;
  35834. }
  35835. this._beingRegenerated = true;
  35836. this.setAllVerticesData(this._regenerateVertexData(), false);
  35837. this._beingRegenerated = false;
  35838. };
  35839. /**
  35840. * Clone the geometry
  35841. * @param id defines the unique ID of the new geometry
  35842. * @returns the new geometry
  35843. */
  35844. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35845. return _super.prototype.copy.call(this, id);
  35846. };
  35847. // overrides
  35848. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35849. if (!this._beingRegenerated) {
  35850. return;
  35851. }
  35852. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35853. };
  35854. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35855. if (!this._beingRegenerated) {
  35856. return;
  35857. }
  35858. _super.prototype.setVerticesData.call(this, kind, data, false);
  35859. };
  35860. // to override
  35861. /** @ignore */
  35862. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35863. throw new Error("Abstract method");
  35864. };
  35865. _PrimitiveGeometry.prototype.copy = function (id) {
  35866. throw new Error("Must be overriden in sub-classes.");
  35867. };
  35868. _PrimitiveGeometry.prototype.serialize = function () {
  35869. var serializationObject = _super.prototype.serialize.call(this);
  35870. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35871. return serializationObject;
  35872. };
  35873. return _PrimitiveGeometry;
  35874. }(Geometry));
  35875. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35876. /**
  35877. * Creates a ribbon geometry
  35878. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35879. */
  35880. var RibbonGeometry = /** @class */ (function (_super) {
  35881. __extends(RibbonGeometry, _super);
  35882. /**
  35883. * Creates a ribbon geometry
  35884. * @param id defines the unique ID of the geometry
  35885. * @param scene defines the hosting scene
  35886. * @param pathArray defines the array of paths to use
  35887. * @param closeArray defines if the last path and the first path must be joined
  35888. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35889. * @param offset defines the offset between points
  35890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35891. * @param mesh defines the hosting mesh (can be null)
  35892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35893. */
  35894. function RibbonGeometry(id, scene,
  35895. /**
  35896. * Defines the array of paths to use
  35897. */
  35898. pathArray,
  35899. /**
  35900. * Defines if the last and first points of each path in your pathArray must be joined
  35901. */
  35902. closeArray,
  35903. /**
  35904. * Defines if the last and first points of each path in your pathArray must be joined
  35905. */
  35906. closePath,
  35907. /**
  35908. * Defines the offset between points
  35909. */
  35910. offset, canBeRegenerated, mesh,
  35911. /**
  35912. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35913. */
  35914. side) {
  35915. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35917. _this.pathArray = pathArray;
  35918. _this.closeArray = closeArray;
  35919. _this.closePath = closePath;
  35920. _this.offset = offset;
  35921. _this.side = side;
  35922. return _this;
  35923. }
  35924. /** @ignore */
  35925. RibbonGeometry.prototype._regenerateVertexData = function () {
  35926. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35927. };
  35928. RibbonGeometry.prototype.copy = function (id) {
  35929. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35930. };
  35931. return RibbonGeometry;
  35932. }(_PrimitiveGeometry));
  35933. BABYLON.RibbonGeometry = RibbonGeometry;
  35934. /**
  35935. * Creates a box geometry
  35936. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35937. */
  35938. var BoxGeometry = /** @class */ (function (_super) {
  35939. __extends(BoxGeometry, _super);
  35940. /**
  35941. * Creates a box geometry
  35942. * @param id defines the unique ID of the geometry
  35943. * @param scene defines the hosting scene
  35944. * @param size defines the zise of the box (width, height and depth are the same)
  35945. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35946. * @param mesh defines the hosting mesh (can be null)
  35947. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35948. */
  35949. function BoxGeometry(id, scene,
  35950. /**
  35951. * Defines the zise of the box (width, height and depth are the same)
  35952. */
  35953. size, canBeRegenerated, mesh,
  35954. /**
  35955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35956. */
  35957. side) {
  35958. if (mesh === void 0) { mesh = null; }
  35959. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35961. _this.size = size;
  35962. _this.side = side;
  35963. return _this;
  35964. }
  35965. BoxGeometry.prototype._regenerateVertexData = function () {
  35966. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35967. };
  35968. BoxGeometry.prototype.copy = function (id) {
  35969. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35970. };
  35971. BoxGeometry.prototype.serialize = function () {
  35972. var serializationObject = _super.prototype.serialize.call(this);
  35973. serializationObject.size = this.size;
  35974. return serializationObject;
  35975. };
  35976. BoxGeometry.Parse = function (parsedBox, scene) {
  35977. if (scene.getGeometryByID(parsedBox.id)) {
  35978. return null; // null since geometry could be something else than a box...
  35979. }
  35980. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35981. if (BABYLON.Tags) {
  35982. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35983. }
  35984. scene.pushGeometry(box, true);
  35985. return box;
  35986. };
  35987. return BoxGeometry;
  35988. }(_PrimitiveGeometry));
  35989. BABYLON.BoxGeometry = BoxGeometry;
  35990. /**
  35991. * Creates a sphere geometry
  35992. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35993. */
  35994. var SphereGeometry = /** @class */ (function (_super) {
  35995. __extends(SphereGeometry, _super);
  35996. /**
  35997. * Create a new sphere geometry
  35998. * @param id defines the unique ID of the geometry
  35999. * @param scene defines the hosting scene
  36000. * @param segments defines the number of segments to use to create the sphere
  36001. * @param diameter defines the diameter of the sphere
  36002. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36003. * @param mesh defines the hosting mesh (can be null)
  36004. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36005. */
  36006. function SphereGeometry(id, scene,
  36007. /**
  36008. * Defines the number of segments to use to create the sphere
  36009. */
  36010. segments,
  36011. /**
  36012. * Defines the diameter of the sphere
  36013. */
  36014. diameter, canBeRegenerated, mesh,
  36015. /**
  36016. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36017. */
  36018. side) {
  36019. if (mesh === void 0) { mesh = null; }
  36020. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36021. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36022. _this.segments = segments;
  36023. _this.diameter = diameter;
  36024. _this.side = side;
  36025. return _this;
  36026. }
  36027. SphereGeometry.prototype._regenerateVertexData = function () {
  36028. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36029. };
  36030. SphereGeometry.prototype.copy = function (id) {
  36031. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36032. };
  36033. SphereGeometry.prototype.serialize = function () {
  36034. var serializationObject = _super.prototype.serialize.call(this);
  36035. serializationObject.segments = this.segments;
  36036. serializationObject.diameter = this.diameter;
  36037. return serializationObject;
  36038. };
  36039. SphereGeometry.Parse = function (parsedSphere, scene) {
  36040. if (scene.getGeometryByID(parsedSphere.id)) {
  36041. return null; // null since geometry could be something else than a sphere...
  36042. }
  36043. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36044. if (BABYLON.Tags) {
  36045. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36046. }
  36047. scene.pushGeometry(sphere, true);
  36048. return sphere;
  36049. };
  36050. return SphereGeometry;
  36051. }(_PrimitiveGeometry));
  36052. BABYLON.SphereGeometry = SphereGeometry;
  36053. /**
  36054. * Creates a disc geometry
  36055. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36056. */
  36057. var DiscGeometry = /** @class */ (function (_super) {
  36058. __extends(DiscGeometry, _super);
  36059. /**
  36060. * Creates a new disc geometry
  36061. * @param id defines the unique ID of the geometry
  36062. * @param scene defines the hosting scene
  36063. * @param radius defines the radius of the disc
  36064. * @param tessellation defines the tesselation factor to apply to the disc
  36065. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36066. * @param mesh defines the hosting mesh (can be null)
  36067. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36068. */
  36069. function DiscGeometry(id, scene,
  36070. /**
  36071. * Defines the radius of the disc
  36072. */
  36073. radius,
  36074. /**
  36075. * Defines the tesselation factor to apply to the disc
  36076. */
  36077. tessellation, canBeRegenerated, mesh,
  36078. /**
  36079. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36080. */
  36081. side) {
  36082. if (mesh === void 0) { mesh = null; }
  36083. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36084. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36085. _this.radius = radius;
  36086. _this.tessellation = tessellation;
  36087. _this.side = side;
  36088. return _this;
  36089. }
  36090. DiscGeometry.prototype._regenerateVertexData = function () {
  36091. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36092. };
  36093. DiscGeometry.prototype.copy = function (id) {
  36094. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36095. };
  36096. return DiscGeometry;
  36097. }(_PrimitiveGeometry));
  36098. BABYLON.DiscGeometry = DiscGeometry;
  36099. /**
  36100. * Creates a new cylinder geometry
  36101. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36102. */
  36103. var CylinderGeometry = /** @class */ (function (_super) {
  36104. __extends(CylinderGeometry, _super);
  36105. /**
  36106. * Creates a new cylinder geometry
  36107. * @param id defines the unique ID of the geometry
  36108. * @param scene defines the hosting scene
  36109. * @param height defines the height of the cylinder
  36110. * @param diameterTop defines the diameter of the cylinder's top cap
  36111. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36112. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36113. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36114. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36115. * @param mesh defines the hosting mesh (can be null)
  36116. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36117. */
  36118. function CylinderGeometry(id, scene,
  36119. /**
  36120. * Defines the height of the cylinder
  36121. */
  36122. height,
  36123. /**
  36124. * Defines the diameter of the cylinder's top cap
  36125. */
  36126. diameterTop,
  36127. /**
  36128. * Defines the diameter of the cylinder's bottom cap
  36129. */
  36130. diameterBottom,
  36131. /**
  36132. * Defines the tessellation factor to apply to the cylinder
  36133. */
  36134. tessellation,
  36135. /**
  36136. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36137. */
  36138. subdivisions, canBeRegenerated, mesh,
  36139. /**
  36140. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36141. */
  36142. side) {
  36143. if (subdivisions === void 0) { subdivisions = 1; }
  36144. if (mesh === void 0) { mesh = null; }
  36145. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36146. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36147. _this.height = height;
  36148. _this.diameterTop = diameterTop;
  36149. _this.diameterBottom = diameterBottom;
  36150. _this.tessellation = tessellation;
  36151. _this.subdivisions = subdivisions;
  36152. _this.side = side;
  36153. return _this;
  36154. }
  36155. CylinderGeometry.prototype._regenerateVertexData = function () {
  36156. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36157. };
  36158. CylinderGeometry.prototype.copy = function (id) {
  36159. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36160. };
  36161. CylinderGeometry.prototype.serialize = function () {
  36162. var serializationObject = _super.prototype.serialize.call(this);
  36163. serializationObject.height = this.height;
  36164. serializationObject.diameterTop = this.diameterTop;
  36165. serializationObject.diameterBottom = this.diameterBottom;
  36166. serializationObject.tessellation = this.tessellation;
  36167. return serializationObject;
  36168. };
  36169. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36170. if (scene.getGeometryByID(parsedCylinder.id)) {
  36171. return null; // null since geometry could be something else than a cylinder...
  36172. }
  36173. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36174. if (BABYLON.Tags) {
  36175. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36176. }
  36177. scene.pushGeometry(cylinder, true);
  36178. return cylinder;
  36179. };
  36180. return CylinderGeometry;
  36181. }(_PrimitiveGeometry));
  36182. BABYLON.CylinderGeometry = CylinderGeometry;
  36183. /**
  36184. * Creates a new torus geometry
  36185. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36186. */
  36187. var TorusGeometry = /** @class */ (function (_super) {
  36188. __extends(TorusGeometry, _super);
  36189. /**
  36190. * Creates a new torus geometry
  36191. * @param id defines the unique ID of the geometry
  36192. * @param scene defines the hosting scene
  36193. * @param diameter defines the diameter of the torus
  36194. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36195. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36196. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36197. * @param mesh defines the hosting mesh (can be null)
  36198. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36199. */
  36200. function TorusGeometry(id, scene,
  36201. /**
  36202. * Defines the diameter of the torus
  36203. */
  36204. diameter,
  36205. /**
  36206. * Defines the thickness of the torus (ie. internal diameter)
  36207. */
  36208. thickness,
  36209. /**
  36210. * Defines the tesselation factor to apply to the torus
  36211. */
  36212. tessellation, canBeRegenerated, mesh,
  36213. /**
  36214. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36215. */
  36216. side) {
  36217. if (mesh === void 0) { mesh = null; }
  36218. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36219. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36220. _this.diameter = diameter;
  36221. _this.thickness = thickness;
  36222. _this.tessellation = tessellation;
  36223. _this.side = side;
  36224. return _this;
  36225. }
  36226. TorusGeometry.prototype._regenerateVertexData = function () {
  36227. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36228. };
  36229. TorusGeometry.prototype.copy = function (id) {
  36230. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36231. };
  36232. TorusGeometry.prototype.serialize = function () {
  36233. var serializationObject = _super.prototype.serialize.call(this);
  36234. serializationObject.diameter = this.diameter;
  36235. serializationObject.thickness = this.thickness;
  36236. serializationObject.tessellation = this.tessellation;
  36237. return serializationObject;
  36238. };
  36239. TorusGeometry.Parse = function (parsedTorus, scene) {
  36240. if (scene.getGeometryByID(parsedTorus.id)) {
  36241. return null; // null since geometry could be something else than a torus...
  36242. }
  36243. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36244. if (BABYLON.Tags) {
  36245. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36246. }
  36247. scene.pushGeometry(torus, true);
  36248. return torus;
  36249. };
  36250. return TorusGeometry;
  36251. }(_PrimitiveGeometry));
  36252. BABYLON.TorusGeometry = TorusGeometry;
  36253. /**
  36254. * Creates a new ground geometry
  36255. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36256. */
  36257. var GroundGeometry = /** @class */ (function (_super) {
  36258. __extends(GroundGeometry, _super);
  36259. /**
  36260. * Creates a new ground geometry
  36261. * @param id defines the unique ID of the geometry
  36262. * @param scene defines the hosting scene
  36263. * @param width defines the width of the ground
  36264. * @param height defines the height of the ground
  36265. * @param subdivisions defines the subdivisions to apply to the ground
  36266. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36267. * @param mesh defines the hosting mesh (can be null)
  36268. */
  36269. function GroundGeometry(id, scene,
  36270. /**
  36271. * Defines the width of the ground
  36272. */
  36273. width,
  36274. /**
  36275. * Defines the height of the ground
  36276. */
  36277. height,
  36278. /**
  36279. * Defines the subdivisions to apply to the ground
  36280. */
  36281. subdivisions, canBeRegenerated, mesh) {
  36282. if (mesh === void 0) { mesh = null; }
  36283. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36284. _this.width = width;
  36285. _this.height = height;
  36286. _this.subdivisions = subdivisions;
  36287. return _this;
  36288. }
  36289. GroundGeometry.prototype._regenerateVertexData = function () {
  36290. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36291. };
  36292. GroundGeometry.prototype.copy = function (id) {
  36293. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36294. };
  36295. GroundGeometry.prototype.serialize = function () {
  36296. var serializationObject = _super.prototype.serialize.call(this);
  36297. serializationObject.width = this.width;
  36298. serializationObject.height = this.height;
  36299. serializationObject.subdivisions = this.subdivisions;
  36300. return serializationObject;
  36301. };
  36302. GroundGeometry.Parse = function (parsedGround, scene) {
  36303. if (scene.getGeometryByID(parsedGround.id)) {
  36304. return null; // null since geometry could be something else than a ground...
  36305. }
  36306. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36307. if (BABYLON.Tags) {
  36308. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36309. }
  36310. scene.pushGeometry(ground, true);
  36311. return ground;
  36312. };
  36313. return GroundGeometry;
  36314. }(_PrimitiveGeometry));
  36315. BABYLON.GroundGeometry = GroundGeometry;
  36316. /**
  36317. * Creates a tiled ground geometry
  36318. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36319. */
  36320. var TiledGroundGeometry = /** @class */ (function (_super) {
  36321. __extends(TiledGroundGeometry, _super);
  36322. /**
  36323. * Creates a tiled ground geometry
  36324. * @param id defines the unique ID of the geometry
  36325. * @param scene defines the hosting scene
  36326. * @param xmin defines the minimum value on X axis
  36327. * @param zmin defines the minimum value on Z axis
  36328. * @param xmax defines the maximum value on X axis
  36329. * @param zmax defines the maximum value on Z axis
  36330. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36331. * @param precision defines the precision to use when computing the tiles
  36332. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36333. * @param mesh defines the hosting mesh (can be null)
  36334. */
  36335. function TiledGroundGeometry(id, scene,
  36336. /**
  36337. * Defines the minimum value on X axis
  36338. */
  36339. xmin,
  36340. /**
  36341. * Defines the minimum value on Z axis
  36342. */
  36343. zmin,
  36344. /**
  36345. * Defines the maximum value on X axis
  36346. */
  36347. xmax,
  36348. /**
  36349. * Defines the maximum value on Z axis
  36350. */
  36351. zmax,
  36352. /**
  36353. * Defines the subdivisions to apply to the ground
  36354. */
  36355. subdivisions,
  36356. /**
  36357. * Defines the precision to use when computing the tiles
  36358. */
  36359. precision, canBeRegenerated, mesh) {
  36360. if (mesh === void 0) { mesh = null; }
  36361. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36362. _this.xmin = xmin;
  36363. _this.zmin = zmin;
  36364. _this.xmax = xmax;
  36365. _this.zmax = zmax;
  36366. _this.subdivisions = subdivisions;
  36367. _this.precision = precision;
  36368. return _this;
  36369. }
  36370. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36371. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36372. };
  36373. TiledGroundGeometry.prototype.copy = function (id) {
  36374. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36375. };
  36376. return TiledGroundGeometry;
  36377. }(_PrimitiveGeometry));
  36378. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36379. /**
  36380. * Creates a plane geometry
  36381. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36382. */
  36383. var PlaneGeometry = /** @class */ (function (_super) {
  36384. __extends(PlaneGeometry, _super);
  36385. /**
  36386. * Creates a plane geometry
  36387. * @param id defines the unique ID of the geometry
  36388. * @param scene defines the hosting scene
  36389. * @param size defines the size of the plane (width === height)
  36390. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36391. * @param mesh defines the hosting mesh (can be null)
  36392. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36393. */
  36394. function PlaneGeometry(id, scene,
  36395. /**
  36396. * Defines the size of the plane (width === height)
  36397. */
  36398. size, canBeRegenerated, mesh,
  36399. /**
  36400. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36401. */
  36402. side) {
  36403. if (mesh === void 0) { mesh = null; }
  36404. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36405. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36406. _this.size = size;
  36407. _this.side = side;
  36408. return _this;
  36409. }
  36410. PlaneGeometry.prototype._regenerateVertexData = function () {
  36411. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36412. };
  36413. PlaneGeometry.prototype.copy = function (id) {
  36414. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36415. };
  36416. PlaneGeometry.prototype.serialize = function () {
  36417. var serializationObject = _super.prototype.serialize.call(this);
  36418. serializationObject.size = this.size;
  36419. return serializationObject;
  36420. };
  36421. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36422. if (scene.getGeometryByID(parsedPlane.id)) {
  36423. return null; // null since geometry could be something else than a ground...
  36424. }
  36425. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36426. if (BABYLON.Tags) {
  36427. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36428. }
  36429. scene.pushGeometry(plane, true);
  36430. return plane;
  36431. };
  36432. return PlaneGeometry;
  36433. }(_PrimitiveGeometry));
  36434. BABYLON.PlaneGeometry = PlaneGeometry;
  36435. /**
  36436. * Creates a torus knot geometry
  36437. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36438. */
  36439. var TorusKnotGeometry = /** @class */ (function (_super) {
  36440. __extends(TorusKnotGeometry, _super);
  36441. /**
  36442. * Creates a torus knot geometry
  36443. * @param id defines the unique ID of the geometry
  36444. * @param scene defines the hosting scene
  36445. * @param radius defines the radius of the torus knot
  36446. * @param tube defines the thickness of the torus knot tube
  36447. * @param radialSegments defines the number of radial segments
  36448. * @param tubularSegments defines the number of tubular segments
  36449. * @param p defines the first number of windings
  36450. * @param q defines the second number of windings
  36451. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36452. * @param mesh defines the hosting mesh (can be null)
  36453. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36454. */
  36455. function TorusKnotGeometry(id, scene,
  36456. /**
  36457. * Defines the radius of the torus knot
  36458. */
  36459. radius,
  36460. /**
  36461. * Defines the thickness of the torus knot tube
  36462. */
  36463. tube,
  36464. /**
  36465. * Defines the number of radial segments
  36466. */
  36467. radialSegments,
  36468. /**
  36469. * Defines the number of tubular segments
  36470. */
  36471. tubularSegments,
  36472. /**
  36473. * Defines the first number of windings
  36474. */
  36475. p,
  36476. /**
  36477. * Defines the second number of windings
  36478. */
  36479. q, canBeRegenerated, mesh,
  36480. /**
  36481. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36482. */
  36483. side) {
  36484. if (mesh === void 0) { mesh = null; }
  36485. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36486. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36487. _this.radius = radius;
  36488. _this.tube = tube;
  36489. _this.radialSegments = radialSegments;
  36490. _this.tubularSegments = tubularSegments;
  36491. _this.p = p;
  36492. _this.q = q;
  36493. _this.side = side;
  36494. return _this;
  36495. }
  36496. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36497. 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 });
  36498. };
  36499. TorusKnotGeometry.prototype.copy = function (id) {
  36500. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36501. };
  36502. TorusKnotGeometry.prototype.serialize = function () {
  36503. var serializationObject = _super.prototype.serialize.call(this);
  36504. serializationObject.radius = this.radius;
  36505. serializationObject.tube = this.tube;
  36506. serializationObject.radialSegments = this.radialSegments;
  36507. serializationObject.tubularSegments = this.tubularSegments;
  36508. serializationObject.p = this.p;
  36509. serializationObject.q = this.q;
  36510. return serializationObject;
  36511. };
  36512. ;
  36513. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36514. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36515. return null; // null since geometry could be something else than a ground...
  36516. }
  36517. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36518. if (BABYLON.Tags) {
  36519. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36520. }
  36521. scene.pushGeometry(torusKnot, true);
  36522. return torusKnot;
  36523. };
  36524. return TorusKnotGeometry;
  36525. }(_PrimitiveGeometry));
  36526. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36527. //}
  36528. })(BABYLON || (BABYLON = {}));
  36529. //# sourceMappingURL=babylon.geometry.js.map
  36530. var BABYLON;
  36531. (function (BABYLON) {
  36532. /**
  36533. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36534. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36535. */
  36536. var PostProcessManager = /** @class */ (function () {
  36537. /**
  36538. * Creates a new instance of @see PostProcess
  36539. * @param scene The scene that the post process is associated with.
  36540. */
  36541. function PostProcessManager(scene) {
  36542. this._vertexBuffers = {};
  36543. this._scene = scene;
  36544. }
  36545. PostProcessManager.prototype._prepareBuffers = function () {
  36546. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36547. return;
  36548. }
  36549. // VBO
  36550. var vertices = [];
  36551. vertices.push(1, 1);
  36552. vertices.push(-1, 1);
  36553. vertices.push(-1, -1);
  36554. vertices.push(1, -1);
  36555. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36556. this._buildIndexBuffer();
  36557. };
  36558. PostProcessManager.prototype._buildIndexBuffer = function () {
  36559. // Indices
  36560. var indices = [];
  36561. indices.push(0);
  36562. indices.push(1);
  36563. indices.push(2);
  36564. indices.push(0);
  36565. indices.push(2);
  36566. indices.push(3);
  36567. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36568. };
  36569. /**
  36570. * Rebuilds the vertex buffers of the manager.
  36571. */
  36572. PostProcessManager.prototype._rebuild = function () {
  36573. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36574. if (!vb) {
  36575. return;
  36576. }
  36577. vb._rebuild();
  36578. this._buildIndexBuffer();
  36579. };
  36580. // Methods
  36581. /**
  36582. * Prepares a frame to be run through a post process.
  36583. * @param sourceTexture The input texture to the post procesess. (default: null)
  36584. * @param postProcesses An array of post processes to be run. (default: null)
  36585. * @returns True if the post processes were able to be run.
  36586. */
  36587. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36588. if (sourceTexture === void 0) { sourceTexture = null; }
  36589. if (postProcesses === void 0) { postProcesses = null; }
  36590. var camera = this._scene.activeCamera;
  36591. if (!camera) {
  36592. return false;
  36593. }
  36594. var postProcesses = postProcesses || camera._postProcesses;
  36595. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36596. return false;
  36597. }
  36598. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36599. return true;
  36600. };
  36601. /**
  36602. * Manually render a set of post processes to a texture.
  36603. * @param postProcesses An array of post processes to be run.
  36604. * @param targetTexture The target texture to render to.
  36605. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36606. */
  36607. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36608. if (targetTexture === void 0) { targetTexture = null; }
  36609. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36610. var engine = this._scene.getEngine();
  36611. for (var index = 0; index < postProcesses.length; index++) {
  36612. if (index < postProcesses.length - 1) {
  36613. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36614. }
  36615. else {
  36616. if (targetTexture) {
  36617. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36618. }
  36619. else {
  36620. engine.restoreDefaultFramebuffer();
  36621. }
  36622. }
  36623. var pp = postProcesses[index];
  36624. var effect = pp.apply();
  36625. if (effect) {
  36626. pp.onBeforeRenderObservable.notifyObservers(effect);
  36627. // VBOs
  36628. this._prepareBuffers();
  36629. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36630. // Draw order
  36631. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36632. pp.onAfterRenderObservable.notifyObservers(effect);
  36633. }
  36634. }
  36635. // Restore depth buffer
  36636. engine.setDepthBuffer(true);
  36637. engine.setDepthWrite(true);
  36638. };
  36639. /**
  36640. * Finalize the result of the output of the postprocesses.
  36641. * @param doNotPresent If true the result will not be displayed to the screen.
  36642. * @param targetTexture The target texture to render to.
  36643. * @param faceIndex The index of the face to bind the target texture to.
  36644. * @param postProcesses The array of post processes to render.
  36645. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36646. */
  36647. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36648. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36649. var camera = this._scene.activeCamera;
  36650. if (!camera) {
  36651. return;
  36652. }
  36653. postProcesses = postProcesses || camera._postProcesses;
  36654. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36655. return;
  36656. }
  36657. var engine = this._scene.getEngine();
  36658. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36659. if (index < len - 1) {
  36660. postProcesses[index + 1].activate(camera, targetTexture);
  36661. }
  36662. else {
  36663. if (targetTexture) {
  36664. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36665. }
  36666. else {
  36667. engine.restoreDefaultFramebuffer();
  36668. }
  36669. }
  36670. if (doNotPresent) {
  36671. break;
  36672. }
  36673. var pp = postProcesses[index];
  36674. var effect = pp.apply();
  36675. if (effect) {
  36676. pp.onBeforeRenderObservable.notifyObservers(effect);
  36677. // VBOs
  36678. this._prepareBuffers();
  36679. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36680. // Draw order
  36681. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36682. pp.onAfterRenderObservable.notifyObservers(effect);
  36683. }
  36684. }
  36685. // Restore states
  36686. engine.setDepthBuffer(true);
  36687. engine.setDepthWrite(true);
  36688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36689. };
  36690. /**
  36691. * Disposes of the post process manager.
  36692. */
  36693. PostProcessManager.prototype.dispose = function () {
  36694. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36695. if (buffer) {
  36696. buffer.dispose();
  36697. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36698. }
  36699. if (this._indexBuffer) {
  36700. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36701. this._indexBuffer = null;
  36702. }
  36703. };
  36704. return PostProcessManager;
  36705. }());
  36706. BABYLON.PostProcessManager = PostProcessManager;
  36707. })(BABYLON || (BABYLON = {}));
  36708. //# sourceMappingURL=babylon.postProcessManager.js.map
  36709. var BABYLON;
  36710. (function (BABYLON) {
  36711. /**
  36712. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36713. */
  36714. var PerformanceMonitor = /** @class */ (function () {
  36715. /**
  36716. * constructor
  36717. * @param frameSampleSize The number of samples required to saturate the sliding window
  36718. */
  36719. function PerformanceMonitor(frameSampleSize) {
  36720. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36721. this._enabled = true;
  36722. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36723. }
  36724. /**
  36725. * Samples current frame
  36726. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36727. */
  36728. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36729. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36730. if (!this._enabled)
  36731. return;
  36732. if (this._lastFrameTimeMs != null) {
  36733. var dt = timeMs - this._lastFrameTimeMs;
  36734. this._rollingFrameTime.add(dt);
  36735. }
  36736. this._lastFrameTimeMs = timeMs;
  36737. };
  36738. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36739. /**
  36740. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36741. * @return Average frame time in milliseconds
  36742. */
  36743. get: function () {
  36744. return this._rollingFrameTime.average;
  36745. },
  36746. enumerable: true,
  36747. configurable: true
  36748. });
  36749. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36750. /**
  36751. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36752. * @return Frame time variance in milliseconds squared
  36753. */
  36754. get: function () {
  36755. return this._rollingFrameTime.variance;
  36756. },
  36757. enumerable: true,
  36758. configurable: true
  36759. });
  36760. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36761. /**
  36762. * Returns the frame time of the most recent frame
  36763. * @return Frame time in milliseconds
  36764. */
  36765. get: function () {
  36766. return this._rollingFrameTime.history(0);
  36767. },
  36768. enumerable: true,
  36769. configurable: true
  36770. });
  36771. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36772. /**
  36773. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36774. * @return Framerate in frames per second
  36775. */
  36776. get: function () {
  36777. return 1000.0 / this._rollingFrameTime.average;
  36778. },
  36779. enumerable: true,
  36780. configurable: true
  36781. });
  36782. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36783. /**
  36784. * Returns the average framerate in frames per second using the most recent frame time
  36785. * @return Framerate in frames per second
  36786. */
  36787. get: function () {
  36788. var history = this._rollingFrameTime.history(0);
  36789. if (history === 0) {
  36790. return 0;
  36791. }
  36792. return 1000.0 / history;
  36793. },
  36794. enumerable: true,
  36795. configurable: true
  36796. });
  36797. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36798. /**
  36799. * Returns true if enough samples have been taken to completely fill the sliding window
  36800. * @return true if saturated
  36801. */
  36802. get: function () {
  36803. return this._rollingFrameTime.isSaturated();
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. /**
  36809. * Enables contributions to the sliding window sample set
  36810. */
  36811. PerformanceMonitor.prototype.enable = function () {
  36812. this._enabled = true;
  36813. };
  36814. /**
  36815. * Disables contributions to the sliding window sample set
  36816. * Samples will not be interpolated over the disabled period
  36817. */
  36818. PerformanceMonitor.prototype.disable = function () {
  36819. this._enabled = false;
  36820. //clear last sample to avoid interpolating over the disabled period when next enabled
  36821. this._lastFrameTimeMs = null;
  36822. };
  36823. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36824. /**
  36825. * Returns true if sampling is enabled
  36826. * @return true if enabled
  36827. */
  36828. get: function () {
  36829. return this._enabled;
  36830. },
  36831. enumerable: true,
  36832. configurable: true
  36833. });
  36834. /**
  36835. * Resets performance monitor
  36836. */
  36837. PerformanceMonitor.prototype.reset = function () {
  36838. //clear last sample to avoid interpolating over the disabled period when next enabled
  36839. this._lastFrameTimeMs = null;
  36840. //wipe record
  36841. this._rollingFrameTime.reset();
  36842. };
  36843. return PerformanceMonitor;
  36844. }());
  36845. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36846. /**
  36847. * RollingAverage
  36848. *
  36849. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36850. */
  36851. var RollingAverage = /** @class */ (function () {
  36852. /**
  36853. * constructor
  36854. * @param length The number of samples required to saturate the sliding window
  36855. */
  36856. function RollingAverage(length) {
  36857. this._samples = new Array(length);
  36858. this.reset();
  36859. }
  36860. /**
  36861. * Adds a sample to the sample set
  36862. * @param v The sample value
  36863. */
  36864. RollingAverage.prototype.add = function (v) {
  36865. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36866. var delta;
  36867. //we need to check if we've already wrapped round
  36868. if (this.isSaturated()) {
  36869. //remove bottom of stack from mean
  36870. var bottomValue = this._samples[this._pos];
  36871. delta = bottomValue - this.average;
  36872. this.average -= delta / (this._sampleCount - 1);
  36873. this._m2 -= delta * (bottomValue - this.average);
  36874. }
  36875. else {
  36876. this._sampleCount++;
  36877. }
  36878. //add new value to mean
  36879. delta = v - this.average;
  36880. this.average += delta / (this._sampleCount);
  36881. this._m2 += delta * (v - this.average);
  36882. //set the new variance
  36883. this.variance = this._m2 / (this._sampleCount - 1);
  36884. this._samples[this._pos] = v;
  36885. this._pos++;
  36886. this._pos %= this._samples.length; //positive wrap around
  36887. };
  36888. /**
  36889. * Returns previously added values or null if outside of history or outside the sliding window domain
  36890. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36891. * @return Value previously recorded with add() or null if outside of range
  36892. */
  36893. RollingAverage.prototype.history = function (i) {
  36894. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36895. return 0;
  36896. }
  36897. var i0 = this._wrapPosition(this._pos - 1.0);
  36898. return this._samples[this._wrapPosition(i0 - i)];
  36899. };
  36900. /**
  36901. * Returns true if enough samples have been taken to completely fill the sliding window
  36902. * @return true if sample-set saturated
  36903. */
  36904. RollingAverage.prototype.isSaturated = function () {
  36905. return this._sampleCount >= this._samples.length;
  36906. };
  36907. /**
  36908. * Resets the rolling average (equivalent to 0 samples taken so far)
  36909. */
  36910. RollingAverage.prototype.reset = function () {
  36911. this.average = 0;
  36912. this.variance = 0;
  36913. this._sampleCount = 0;
  36914. this._pos = 0;
  36915. this._m2 = 0;
  36916. };
  36917. /**
  36918. * Wraps a value around the sample range boundaries
  36919. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36920. * @return Wrapped position in sample range
  36921. */
  36922. RollingAverage.prototype._wrapPosition = function (i) {
  36923. var max = this._samples.length;
  36924. return ((i % max) + max) % max;
  36925. };
  36926. return RollingAverage;
  36927. }());
  36928. BABYLON.RollingAverage = RollingAverage;
  36929. })(BABYLON || (BABYLON = {}));
  36930. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36931. var BABYLON;
  36932. (function (BABYLON) {
  36933. /**
  36934. * This groups together the common properties used for image processing either in direct forward pass
  36935. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36936. * or not.
  36937. */
  36938. var ImageProcessingConfiguration = /** @class */ (function () {
  36939. function ImageProcessingConfiguration() {
  36940. /**
  36941. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36942. */
  36943. this.colorCurves = new BABYLON.ColorCurves();
  36944. this._colorCurvesEnabled = false;
  36945. this._colorGradingEnabled = false;
  36946. this._colorGradingWithGreenDepth = true;
  36947. this._colorGradingBGR = true;
  36948. this._exposure = 1.0;
  36949. this._toneMappingEnabled = false;
  36950. this._contrast = 1.0;
  36951. /**
  36952. * Vignette stretch size.
  36953. */
  36954. this.vignetteStretch = 0;
  36955. /**
  36956. * Vignette centre X Offset.
  36957. */
  36958. this.vignetteCentreX = 0;
  36959. /**
  36960. * Vignette centre Y Offset.
  36961. */
  36962. this.vignetteCentreY = 0;
  36963. /**
  36964. * Vignette weight or intensity of the vignette effect.
  36965. */
  36966. this.vignetteWeight = 1.5;
  36967. /**
  36968. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36969. * if vignetteEnabled is set to true.
  36970. */
  36971. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36972. /**
  36973. * Camera field of view used by the Vignette effect.
  36974. */
  36975. this.vignetteCameraFov = 0.5;
  36976. this._grainEnabled = false;
  36977. this._grainIntensity = 30;
  36978. this._grainAnimated = false;
  36979. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36980. this._vignetteEnabled = false;
  36981. this._applyByPostProcess = false;
  36982. this._isEnabled = true;
  36983. /**
  36984. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36985. * @type {BABYLON.Observable}
  36986. */
  36987. this.onUpdateParameters = new BABYLON.Observable();
  36988. }
  36989. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36990. /**
  36991. * Gets wether the color curves effect is enabled.
  36992. */
  36993. get: function () {
  36994. return this._colorCurvesEnabled;
  36995. },
  36996. /**
  36997. * Sets wether the color curves effect is enabled.
  36998. */
  36999. set: function (value) {
  37000. if (this._colorCurvesEnabled === value) {
  37001. return;
  37002. }
  37003. this._colorCurvesEnabled = value;
  37004. this._updateParameters();
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37010. /**
  37011. * Gets wether the color grading effect is enabled.
  37012. */
  37013. get: function () {
  37014. return this._colorGradingEnabled;
  37015. },
  37016. /**
  37017. * Sets wether the color grading effect is enabled.
  37018. */
  37019. set: function (value) {
  37020. if (this._colorGradingEnabled === value) {
  37021. return;
  37022. }
  37023. this._colorGradingEnabled = value;
  37024. this._updateParameters();
  37025. },
  37026. enumerable: true,
  37027. configurable: true
  37028. });
  37029. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37030. /**
  37031. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37032. */
  37033. get: function () {
  37034. return this._colorGradingWithGreenDepth;
  37035. },
  37036. /**
  37037. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37038. */
  37039. set: function (value) {
  37040. if (this._colorGradingWithGreenDepth === value) {
  37041. return;
  37042. }
  37043. this._colorGradingWithGreenDepth = value;
  37044. this._updateParameters();
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37050. /**
  37051. * Gets wether the color grading texture contains BGR values.
  37052. */
  37053. get: function () {
  37054. return this._colorGradingBGR;
  37055. },
  37056. /**
  37057. * Sets wether the color grading texture contains BGR values.
  37058. */
  37059. set: function (value) {
  37060. if (this._colorGradingBGR === value) {
  37061. return;
  37062. }
  37063. this._colorGradingBGR = value;
  37064. this._updateParameters();
  37065. },
  37066. enumerable: true,
  37067. configurable: true
  37068. });
  37069. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37070. /**
  37071. * Gets the Exposure used in the effect.
  37072. */
  37073. get: function () {
  37074. return this._exposure;
  37075. },
  37076. /**
  37077. * Sets the Exposure used in the effect.
  37078. */
  37079. set: function (value) {
  37080. if (this._exposure === value) {
  37081. return;
  37082. }
  37083. this._exposure = value;
  37084. this._updateParameters();
  37085. },
  37086. enumerable: true,
  37087. configurable: true
  37088. });
  37089. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37090. /**
  37091. * Gets wether the tone mapping effect is enabled.
  37092. */
  37093. get: function () {
  37094. return this._toneMappingEnabled;
  37095. },
  37096. /**
  37097. * Sets wether the tone mapping effect is enabled.
  37098. */
  37099. set: function (value) {
  37100. if (this._toneMappingEnabled === value) {
  37101. return;
  37102. }
  37103. this._toneMappingEnabled = value;
  37104. this._updateParameters();
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37110. /**
  37111. * Gets the contrast used in the effect.
  37112. */
  37113. get: function () {
  37114. return this._contrast;
  37115. },
  37116. /**
  37117. * Sets the contrast used in the effect.
  37118. */
  37119. set: function (value) {
  37120. if (this._contrast === value) {
  37121. return;
  37122. }
  37123. this._contrast = value;
  37124. this._updateParameters();
  37125. },
  37126. enumerable: true,
  37127. configurable: true
  37128. });
  37129. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37130. /**
  37131. * If the grain effect should be enabled.
  37132. */
  37133. get: function () {
  37134. return this._grainEnabled;
  37135. },
  37136. set: function (value) {
  37137. if (this._grainEnabled === value) {
  37138. return;
  37139. }
  37140. this._grainEnabled = value;
  37141. this._updateParameters();
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37147. /**
  37148. * Amount of grain to be applied by the grain effect.
  37149. */
  37150. get: function () {
  37151. return this._grainIntensity;
  37152. },
  37153. set: function (value) {
  37154. if (this._grainIntensity === value) {
  37155. return;
  37156. }
  37157. this._grainIntensity = value;
  37158. },
  37159. enumerable: true,
  37160. configurable: true
  37161. });
  37162. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37163. /**
  37164. * If the grain effect should be animated.
  37165. */
  37166. get: function () {
  37167. return this._grainAnimated;
  37168. },
  37169. set: function (value) {
  37170. if (this._grainAnimated === value) {
  37171. return;
  37172. }
  37173. this._grainAnimated = value;
  37174. this._updateParameters();
  37175. },
  37176. enumerable: true,
  37177. configurable: true
  37178. });
  37179. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37180. /**
  37181. * Gets the vignette blend mode allowing different kind of effect.
  37182. */
  37183. get: function () {
  37184. return this._vignetteBlendMode;
  37185. },
  37186. /**
  37187. * Sets the vignette blend mode allowing different kind of effect.
  37188. */
  37189. set: function (value) {
  37190. if (this._vignetteBlendMode === value) {
  37191. return;
  37192. }
  37193. this._vignetteBlendMode = value;
  37194. this._updateParameters();
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37200. /**
  37201. * Gets wether the vignette effect is enabled.
  37202. */
  37203. get: function () {
  37204. return this._vignetteEnabled;
  37205. },
  37206. /**
  37207. * Sets wether the vignette effect is enabled.
  37208. */
  37209. set: function (value) {
  37210. if (this._vignetteEnabled === value) {
  37211. return;
  37212. }
  37213. this._vignetteEnabled = value;
  37214. this._updateParameters();
  37215. },
  37216. enumerable: true,
  37217. configurable: true
  37218. });
  37219. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37220. /**
  37221. * Gets wether the image processing is applied through a post process or not.
  37222. */
  37223. get: function () {
  37224. return this._applyByPostProcess;
  37225. },
  37226. /**
  37227. * Sets wether the image processing is applied through a post process or not.
  37228. */
  37229. set: function (value) {
  37230. if (this._applyByPostProcess === value) {
  37231. return;
  37232. }
  37233. this._applyByPostProcess = value;
  37234. this._updateParameters();
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37240. /**
  37241. * Gets wether the image processing is enabled or not.
  37242. */
  37243. get: function () {
  37244. return this._isEnabled;
  37245. },
  37246. /**
  37247. * Sets wether the image processing is enabled or not.
  37248. */
  37249. set: function (value) {
  37250. if (this._isEnabled === value) {
  37251. return;
  37252. }
  37253. this._isEnabled = value;
  37254. this._updateParameters();
  37255. },
  37256. enumerable: true,
  37257. configurable: true
  37258. });
  37259. /**
  37260. * Method called each time the image processing information changes requires to recompile the effect.
  37261. */
  37262. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37263. this.onUpdateParameters.notifyObservers(this);
  37264. };
  37265. ImageProcessingConfiguration.prototype.getClassName = function () {
  37266. return "ImageProcessingConfiguration";
  37267. };
  37268. /**
  37269. * Prepare the list of uniforms associated with the Image Processing effects.
  37270. * @param uniformsList The list of uniforms used in the effect
  37271. * @param defines the list of defines currently in use
  37272. */
  37273. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37274. if (defines.EXPOSURE) {
  37275. uniforms.push("exposureLinear");
  37276. }
  37277. if (defines.CONTRAST) {
  37278. uniforms.push("contrast");
  37279. }
  37280. if (defines.COLORGRADING) {
  37281. uniforms.push("colorTransformSettings");
  37282. }
  37283. if (defines.VIGNETTE) {
  37284. uniforms.push("vInverseScreenSize");
  37285. uniforms.push("vignetteSettings1");
  37286. uniforms.push("vignetteSettings2");
  37287. }
  37288. if (defines.COLORCURVES) {
  37289. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37290. }
  37291. if (defines.GRAIN) {
  37292. uniforms.push("grainVarianceAmount");
  37293. uniforms.push("grainAnimatedSeed");
  37294. }
  37295. };
  37296. /**
  37297. * Prepare the list of samplers associated with the Image Processing effects.
  37298. * @param uniformsList The list of uniforms used in the effect
  37299. * @param defines the list of defines currently in use
  37300. */
  37301. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37302. if (defines.COLORGRADING) {
  37303. samplersList.push("txColorTransform");
  37304. }
  37305. };
  37306. /**
  37307. * Prepare the list of defines associated to the shader.
  37308. * @param defines the list of defines to complete
  37309. */
  37310. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37311. if (forPostProcess === void 0) { forPostProcess = false; }
  37312. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37313. defines.VIGNETTE = false;
  37314. defines.TONEMAPPING = false;
  37315. defines.CONTRAST = false;
  37316. defines.EXPOSURE = false;
  37317. defines.COLORCURVES = false;
  37318. defines.COLORGRADING = false;
  37319. defines.COLORGRADING3D = false;
  37320. defines.IMAGEPROCESSING = false;
  37321. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37322. return;
  37323. }
  37324. defines.VIGNETTE = this.vignetteEnabled;
  37325. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37326. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37327. defines.TONEMAPPING = this.toneMappingEnabled;
  37328. defines.CONTRAST = (this.contrast !== 1.0);
  37329. defines.EXPOSURE = (this.exposure !== 1.0);
  37330. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37331. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37332. if (defines.COLORGRADING) {
  37333. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37334. }
  37335. else {
  37336. defines.COLORGRADING3D = false;
  37337. }
  37338. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37339. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37340. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37341. defines.GRAIN = this.grainEnabled;
  37342. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37343. };
  37344. /**
  37345. * Returns true if all the image processing information are ready.
  37346. */
  37347. ImageProcessingConfiguration.prototype.isReady = function () {
  37348. // Color Grading texure can not be none blocking.
  37349. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37350. };
  37351. /**
  37352. * Binds the image processing to the shader.
  37353. * @param effect The effect to bind to
  37354. */
  37355. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37356. if (aspectRatio === void 0) { aspectRatio = 1; }
  37357. // Color Curves
  37358. if (this._colorCurvesEnabled && this.colorCurves) {
  37359. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37360. }
  37361. // Vignette
  37362. if (this._vignetteEnabled) {
  37363. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37364. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37365. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37366. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37367. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37368. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37369. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37370. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37371. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37372. var vignettePower = -2.0 * this.vignetteWeight;
  37373. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37374. }
  37375. // Exposure
  37376. effect.setFloat("exposureLinear", this.exposure);
  37377. // Contrast
  37378. effect.setFloat("contrast", this.contrast);
  37379. // Color transform settings
  37380. if (this.colorGradingTexture) {
  37381. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37382. var textureSize = this.colorGradingTexture.getSize().height;
  37383. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37384. 0.5 / textureSize, // textureOffset
  37385. textureSize, // textureSize
  37386. this.colorGradingTexture.level // weight
  37387. );
  37388. }
  37389. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37390. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37391. };
  37392. /**
  37393. * Clones the current image processing instance.
  37394. * @return The cloned image processing
  37395. */
  37396. ImageProcessingConfiguration.prototype.clone = function () {
  37397. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37398. };
  37399. /**
  37400. * Serializes the current image processing instance to a json representation.
  37401. * @return a JSON representation
  37402. */
  37403. ImageProcessingConfiguration.prototype.serialize = function () {
  37404. return BABYLON.SerializationHelper.Serialize(this);
  37405. };
  37406. /**
  37407. * Parses the image processing from a json representation.
  37408. * @param source the JSON source to parse
  37409. * @return The parsed image processing
  37410. */
  37411. ImageProcessingConfiguration.Parse = function (source) {
  37412. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37413. };
  37414. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37415. /**
  37416. * Used to apply the vignette as a mix with the pixel color.
  37417. */
  37418. get: function () {
  37419. return this._VIGNETTEMODE_MULTIPLY;
  37420. },
  37421. enumerable: true,
  37422. configurable: true
  37423. });
  37424. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37425. /**
  37426. * Used to apply the vignette as a replacement of the pixel color.
  37427. */
  37428. get: function () {
  37429. return this._VIGNETTEMODE_OPAQUE;
  37430. },
  37431. enumerable: true,
  37432. configurable: true
  37433. });
  37434. // Static constants associated to the image processing.
  37435. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37436. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37437. __decorate([
  37438. BABYLON.serializeAsColorCurves()
  37439. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37440. __decorate([
  37441. BABYLON.serialize()
  37442. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37443. __decorate([
  37444. BABYLON.serializeAsTexture()
  37445. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37446. __decorate([
  37447. BABYLON.serialize()
  37448. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37449. __decorate([
  37450. BABYLON.serialize()
  37451. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37452. __decorate([
  37453. BABYLON.serialize()
  37454. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37455. __decorate([
  37456. BABYLON.serialize()
  37457. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37458. __decorate([
  37459. BABYLON.serialize()
  37460. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37461. __decorate([
  37462. BABYLON.serialize()
  37463. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37464. __decorate([
  37465. BABYLON.serialize()
  37466. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37467. __decorate([
  37468. BABYLON.serialize()
  37469. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37470. __decorate([
  37471. BABYLON.serialize()
  37472. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37473. __decorate([
  37474. BABYLON.serialize()
  37475. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37476. __decorate([
  37477. BABYLON.serializeAsColor4()
  37478. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37479. __decorate([
  37480. BABYLON.serialize()
  37481. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37482. __decorate([
  37483. BABYLON.serialize()
  37484. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37485. __decorate([
  37486. BABYLON.serialize()
  37487. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37488. __decorate([
  37489. BABYLON.serialize()
  37490. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37491. __decorate([
  37492. BABYLON.serialize()
  37493. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37494. __decorate([
  37495. BABYLON.serialize()
  37496. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37497. __decorate([
  37498. BABYLON.serialize()
  37499. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37500. __decorate([
  37501. BABYLON.serialize()
  37502. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37503. return ImageProcessingConfiguration;
  37504. }());
  37505. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37506. })(BABYLON || (BABYLON = {}));
  37507. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37508. var BABYLON;
  37509. (function (BABYLON) {
  37510. /**
  37511. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37512. * It can help converting any input color in a desired output one. This can then be used to create effects
  37513. * from sepia, black and white to sixties or futuristic rendering...
  37514. *
  37515. * The only supported format is currently 3dl.
  37516. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37517. */
  37518. var ColorGradingTexture = /** @class */ (function (_super) {
  37519. __extends(ColorGradingTexture, _super);
  37520. /**
  37521. * Instantiates a ColorGradingTexture from the following parameters.
  37522. *
  37523. * @param url The location of the color gradind data (currently only supporting 3dl)
  37524. * @param scene The scene the texture will be used in
  37525. */
  37526. function ColorGradingTexture(url, scene) {
  37527. var _this = _super.call(this, scene) || this;
  37528. if (!url) {
  37529. return _this;
  37530. }
  37531. _this._engine = scene.getEngine();
  37532. _this._textureMatrix = BABYLON.Matrix.Identity();
  37533. _this.name = url;
  37534. _this.url = url;
  37535. _this.hasAlpha = false;
  37536. _this.isCube = false;
  37537. _this.is3D = _this._engine.webGLVersion > 1;
  37538. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37539. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37540. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37541. _this.anisotropicFilteringLevel = 1;
  37542. _this._texture = _this._getFromCache(url, true);
  37543. if (!_this._texture) {
  37544. if (!scene.useDelayedTextureLoading) {
  37545. _this.loadTexture();
  37546. }
  37547. else {
  37548. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37549. }
  37550. }
  37551. return _this;
  37552. }
  37553. /**
  37554. * Returns the texture matrix used in most of the material.
  37555. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37556. */
  37557. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37558. return this._textureMatrix;
  37559. };
  37560. /**
  37561. * Occurs when the file being loaded is a .3dl LUT file.
  37562. */
  37563. ColorGradingTexture.prototype.load3dlTexture = function () {
  37564. var engine = this._engine;
  37565. var texture;
  37566. if (engine.webGLVersion === 1) {
  37567. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37568. }
  37569. else {
  37570. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37571. }
  37572. this._texture = texture;
  37573. var callback = function (text) {
  37574. if (typeof text !== "string") {
  37575. return;
  37576. }
  37577. var data = null;
  37578. var tempData = null;
  37579. var line;
  37580. var lines = text.split('\n');
  37581. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37582. var maxColor = 0;
  37583. for (var i = 0; i < lines.length; i++) {
  37584. line = lines[i];
  37585. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37586. continue;
  37587. if (line.indexOf('#') === 0)
  37588. continue;
  37589. var words = line.split(" ");
  37590. if (size === 0) {
  37591. // Number of space + one
  37592. size = words.length;
  37593. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37594. tempData = new Float32Array(size * size * size * 4);
  37595. continue;
  37596. }
  37597. if (size != 0) {
  37598. var r = Math.max(parseInt(words[0]), 0);
  37599. var g = Math.max(parseInt(words[1]), 0);
  37600. var b = Math.max(parseInt(words[2]), 0);
  37601. maxColor = Math.max(r, maxColor);
  37602. maxColor = Math.max(g, maxColor);
  37603. maxColor = Math.max(b, maxColor);
  37604. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37605. if (tempData) {
  37606. tempData[pixelStorageIndex + 0] = r;
  37607. tempData[pixelStorageIndex + 1] = g;
  37608. tempData[pixelStorageIndex + 2] = b;
  37609. }
  37610. pixelIndexSlice++;
  37611. if (pixelIndexSlice % size == 0) {
  37612. pixelIndexH++;
  37613. pixelIndexSlice = 0;
  37614. if (pixelIndexH % size == 0) {
  37615. pixelIndexW++;
  37616. pixelIndexH = 0;
  37617. }
  37618. }
  37619. }
  37620. }
  37621. if (tempData && data) {
  37622. for (var i = 0; i < tempData.length; i++) {
  37623. if (i > 0 && (i + 1) % 4 === 0) {
  37624. data[i] = 255;
  37625. }
  37626. else {
  37627. var value = tempData[i];
  37628. data[i] = (value / maxColor * 255);
  37629. }
  37630. }
  37631. }
  37632. if (texture.is3D) {
  37633. texture.updateSize(size, size, size);
  37634. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37635. }
  37636. else {
  37637. texture.updateSize(size * size, size);
  37638. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37639. }
  37640. };
  37641. var scene = this.getScene();
  37642. if (scene) {
  37643. scene._loadFile(this.url, callback);
  37644. }
  37645. else {
  37646. this._engine._loadFile(this.url, callback);
  37647. }
  37648. return this._texture;
  37649. };
  37650. /**
  37651. * Starts the loading process of the texture.
  37652. */
  37653. ColorGradingTexture.prototype.loadTexture = function () {
  37654. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37655. this.load3dlTexture();
  37656. }
  37657. };
  37658. /**
  37659. * Clones the color gradind texture.
  37660. */
  37661. ColorGradingTexture.prototype.clone = function () {
  37662. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37663. // Base texture
  37664. newTexture.level = this.level;
  37665. return newTexture;
  37666. };
  37667. /**
  37668. * Called during delayed load for textures.
  37669. */
  37670. ColorGradingTexture.prototype.delayLoad = function () {
  37671. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37672. return;
  37673. }
  37674. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37675. this._texture = this._getFromCache(this.url, true);
  37676. if (!this._texture) {
  37677. this.loadTexture();
  37678. }
  37679. };
  37680. /**
  37681. * Parses a color grading texture serialized by Babylon.
  37682. * @param parsedTexture The texture information being parsedTexture
  37683. * @param scene The scene to load the texture in
  37684. * @param rootUrl The root url of the data assets to load
  37685. * @return A color gradind texture
  37686. */
  37687. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37688. var texture = null;
  37689. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37690. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37691. texture.name = parsedTexture.name;
  37692. texture.level = parsedTexture.level;
  37693. }
  37694. return texture;
  37695. };
  37696. /**
  37697. * Serializes the LUT texture to json format.
  37698. */
  37699. ColorGradingTexture.prototype.serialize = function () {
  37700. if (!this.name) {
  37701. return null;
  37702. }
  37703. var serializationObject = {};
  37704. serializationObject.name = this.name;
  37705. serializationObject.level = this.level;
  37706. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37707. return serializationObject;
  37708. };
  37709. /**
  37710. * Empty line regex stored for GC.
  37711. */
  37712. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37713. return ColorGradingTexture;
  37714. }(BABYLON.BaseTexture));
  37715. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37716. })(BABYLON || (BABYLON = {}));
  37717. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37718. var BABYLON;
  37719. (function (BABYLON) {
  37720. /**
  37721. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37722. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37723. * 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;
  37724. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37725. */
  37726. var ColorCurves = /** @class */ (function () {
  37727. function ColorCurves() {
  37728. this._dirty = true;
  37729. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37730. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37731. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37732. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37733. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37734. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37735. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37736. this._globalHue = 30;
  37737. this._globalDensity = 0;
  37738. this._globalSaturation = 0;
  37739. this._globalExposure = 0;
  37740. this._highlightsHue = 30;
  37741. this._highlightsDensity = 0;
  37742. this._highlightsSaturation = 0;
  37743. this._highlightsExposure = 0;
  37744. this._midtonesHue = 30;
  37745. this._midtonesDensity = 0;
  37746. this._midtonesSaturation = 0;
  37747. this._midtonesExposure = 0;
  37748. this._shadowsHue = 30;
  37749. this._shadowsDensity = 0;
  37750. this._shadowsSaturation = 0;
  37751. this._shadowsExposure = 0;
  37752. }
  37753. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37754. /**
  37755. * Gets the global Hue value.
  37756. * 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).
  37757. */
  37758. get: function () {
  37759. return this._globalHue;
  37760. },
  37761. /**
  37762. * Sets the global Hue value.
  37763. * 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).
  37764. */
  37765. set: function (value) {
  37766. this._globalHue = value;
  37767. this._dirty = true;
  37768. },
  37769. enumerable: true,
  37770. configurable: true
  37771. });
  37772. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37773. /**
  37774. * Gets the global Density value.
  37775. * 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.
  37776. * Values less than zero provide a filter of opposite hue.
  37777. */
  37778. get: function () {
  37779. return this._globalDensity;
  37780. },
  37781. /**
  37782. * Sets the global Density value.
  37783. * 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.
  37784. * Values less than zero provide a filter of opposite hue.
  37785. */
  37786. set: function (value) {
  37787. this._globalDensity = value;
  37788. this._dirty = true;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37794. /**
  37795. * Gets the global Saturation value.
  37796. * 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.
  37797. */
  37798. get: function () {
  37799. return this._globalSaturation;
  37800. },
  37801. /**
  37802. * Sets the global Saturation value.
  37803. * 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.
  37804. */
  37805. set: function (value) {
  37806. this._globalSaturation = value;
  37807. this._dirty = true;
  37808. },
  37809. enumerable: true,
  37810. configurable: true
  37811. });
  37812. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37813. /**
  37814. * Gets the highlights Hue value.
  37815. * 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).
  37816. */
  37817. get: function () {
  37818. return this._highlightsHue;
  37819. },
  37820. /**
  37821. * Sets the highlights Hue value.
  37822. * 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).
  37823. */
  37824. set: function (value) {
  37825. this._highlightsHue = value;
  37826. this._dirty = true;
  37827. },
  37828. enumerable: true,
  37829. configurable: true
  37830. });
  37831. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37832. /**
  37833. * Gets the highlights Density value.
  37834. * 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.
  37835. * Values less than zero provide a filter of opposite hue.
  37836. */
  37837. get: function () {
  37838. return this._highlightsDensity;
  37839. },
  37840. /**
  37841. * Sets the highlights Density value.
  37842. * 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.
  37843. * Values less than zero provide a filter of opposite hue.
  37844. */
  37845. set: function (value) {
  37846. this._highlightsDensity = value;
  37847. this._dirty = true;
  37848. },
  37849. enumerable: true,
  37850. configurable: true
  37851. });
  37852. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37853. /**
  37854. * Gets the highlights Saturation value.
  37855. * 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.
  37856. */
  37857. get: function () {
  37858. return this._highlightsSaturation;
  37859. },
  37860. /**
  37861. * Sets the highlights Saturation value.
  37862. * 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.
  37863. */
  37864. set: function (value) {
  37865. this._highlightsSaturation = value;
  37866. this._dirty = true;
  37867. },
  37868. enumerable: true,
  37869. configurable: true
  37870. });
  37871. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37872. /**
  37873. * Gets the highlights Exposure value.
  37874. * 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.
  37875. */
  37876. get: function () {
  37877. return this._highlightsExposure;
  37878. },
  37879. /**
  37880. * Sets the highlights Exposure value.
  37881. * 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.
  37882. */
  37883. set: function (value) {
  37884. this._highlightsExposure = value;
  37885. this._dirty = true;
  37886. },
  37887. enumerable: true,
  37888. configurable: true
  37889. });
  37890. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37891. /**
  37892. * Gets the midtones Hue value.
  37893. * 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).
  37894. */
  37895. get: function () {
  37896. return this._midtonesHue;
  37897. },
  37898. /**
  37899. * Sets the midtones Hue value.
  37900. * 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).
  37901. */
  37902. set: function (value) {
  37903. this._midtonesHue = value;
  37904. this._dirty = true;
  37905. },
  37906. enumerable: true,
  37907. configurable: true
  37908. });
  37909. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37910. /**
  37911. * Gets the midtones Density value.
  37912. * 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.
  37913. * Values less than zero provide a filter of opposite hue.
  37914. */
  37915. get: function () {
  37916. return this._midtonesDensity;
  37917. },
  37918. /**
  37919. * Sets the midtones Density value.
  37920. * 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.
  37921. * Values less than zero provide a filter of opposite hue.
  37922. */
  37923. set: function (value) {
  37924. this._midtonesDensity = value;
  37925. this._dirty = true;
  37926. },
  37927. enumerable: true,
  37928. configurable: true
  37929. });
  37930. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37931. /**
  37932. * Gets the midtones Saturation value.
  37933. * 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.
  37934. */
  37935. get: function () {
  37936. return this._midtonesSaturation;
  37937. },
  37938. /**
  37939. * Sets the midtones Saturation value.
  37940. * 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.
  37941. */
  37942. set: function (value) {
  37943. this._midtonesSaturation = value;
  37944. this._dirty = true;
  37945. },
  37946. enumerable: true,
  37947. configurable: true
  37948. });
  37949. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37950. /**
  37951. * Gets the midtones Exposure value.
  37952. * 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.
  37953. */
  37954. get: function () {
  37955. return this._midtonesExposure;
  37956. },
  37957. /**
  37958. * Sets the midtones Exposure value.
  37959. * 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.
  37960. */
  37961. set: function (value) {
  37962. this._midtonesExposure = value;
  37963. this._dirty = true;
  37964. },
  37965. enumerable: true,
  37966. configurable: true
  37967. });
  37968. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37969. /**
  37970. * Gets the shadows Hue value.
  37971. * 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).
  37972. */
  37973. get: function () {
  37974. return this._shadowsHue;
  37975. },
  37976. /**
  37977. * Sets the shadows Hue value.
  37978. * 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).
  37979. */
  37980. set: function (value) {
  37981. this._shadowsHue = value;
  37982. this._dirty = true;
  37983. },
  37984. enumerable: true,
  37985. configurable: true
  37986. });
  37987. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37988. /**
  37989. * Gets the shadows Density value.
  37990. * 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.
  37991. * Values less than zero provide a filter of opposite hue.
  37992. */
  37993. get: function () {
  37994. return this._shadowsDensity;
  37995. },
  37996. /**
  37997. * Sets the shadows Density value.
  37998. * 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.
  37999. * Values less than zero provide a filter of opposite hue.
  38000. */
  38001. set: function (value) {
  38002. this._shadowsDensity = value;
  38003. this._dirty = true;
  38004. },
  38005. enumerable: true,
  38006. configurable: true
  38007. });
  38008. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38009. /**
  38010. * Gets the shadows Saturation value.
  38011. * 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.
  38012. */
  38013. get: function () {
  38014. return this._shadowsSaturation;
  38015. },
  38016. /**
  38017. * Sets the shadows Saturation value.
  38018. * 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.
  38019. */
  38020. set: function (value) {
  38021. this._shadowsSaturation = value;
  38022. this._dirty = true;
  38023. },
  38024. enumerable: true,
  38025. configurable: true
  38026. });
  38027. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38028. /**
  38029. * Gets the shadows Exposure value.
  38030. * 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.
  38031. */
  38032. get: function () {
  38033. return this._shadowsExposure;
  38034. },
  38035. /**
  38036. * Sets the shadows Exposure value.
  38037. * 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.
  38038. */
  38039. set: function (value) {
  38040. this._shadowsExposure = value;
  38041. this._dirty = true;
  38042. },
  38043. enumerable: true,
  38044. configurable: true
  38045. });
  38046. ColorCurves.prototype.getClassName = function () {
  38047. return "ColorCurves";
  38048. };
  38049. /**
  38050. * Binds the color curves to the shader.
  38051. * @param colorCurves The color curve to bind
  38052. * @param effect The effect to bind to
  38053. */
  38054. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38055. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38056. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38057. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38058. if (colorCurves._dirty) {
  38059. colorCurves._dirty = false;
  38060. // Fill in global info.
  38061. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38062. // Compute highlights info.
  38063. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38064. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38065. // Compute midtones info.
  38066. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38067. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38068. // Compute shadows info.
  38069. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38070. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38071. // Compute deltas (neutral is midtones).
  38072. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38073. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38074. }
  38075. if (effect) {
  38076. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38077. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38078. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38079. }
  38080. };
  38081. /**
  38082. * Prepare the list of uniforms associated with the ColorCurves effects.
  38083. * @param uniformsList The list of uniforms used in the effect
  38084. */
  38085. ColorCurves.PrepareUniforms = function (uniformsList) {
  38086. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38087. };
  38088. /**
  38089. * Returns color grading data based on a hue, density, saturation and exposure value.
  38090. * @param filterHue The hue of the color filter.
  38091. * @param filterDensity The density of the color filter.
  38092. * @param saturation The saturation.
  38093. * @param exposure The exposure.
  38094. * @param result The result data container.
  38095. */
  38096. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38097. if (hue == null) {
  38098. return;
  38099. }
  38100. hue = ColorCurves.clamp(hue, 0, 360);
  38101. density = ColorCurves.clamp(density, -100, 100);
  38102. saturation = ColorCurves.clamp(saturation, -100, 100);
  38103. exposure = ColorCurves.clamp(exposure, -100, 100);
  38104. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38105. // so that the maximum filter density is only 50% control. This provides fine control
  38106. // for small values and reasonable range.
  38107. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38108. density *= 0.5;
  38109. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38110. if (density < 0) {
  38111. density *= -1;
  38112. hue = (hue + 180) % 360;
  38113. }
  38114. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38115. result.scaleToRef(2, result);
  38116. result.a = 1 + 0.01 * saturation;
  38117. };
  38118. /**
  38119. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38120. * @param value The input slider value in range [-100,100].
  38121. * @returns Adjusted value.
  38122. */
  38123. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38124. value /= 100;
  38125. var x = Math.abs(value);
  38126. x = Math.pow(x, 2);
  38127. if (value < 0) {
  38128. x *= -1;
  38129. }
  38130. x *= 100;
  38131. return x;
  38132. };
  38133. /**
  38134. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38135. * @param hue The hue (H) input.
  38136. * @param saturation The saturation (S) input.
  38137. * @param brightness The brightness (B) input.
  38138. * @result An RGBA color represented as Vector4.
  38139. */
  38140. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38141. var h = ColorCurves.clamp(hue, 0, 360);
  38142. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38143. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38144. if (s === 0) {
  38145. result.r = v;
  38146. result.g = v;
  38147. result.b = v;
  38148. }
  38149. else {
  38150. // sector 0 to 5
  38151. h /= 60;
  38152. var i = Math.floor(h);
  38153. // fractional part of h
  38154. var f = h - i;
  38155. var p = v * (1 - s);
  38156. var q = v * (1 - s * f);
  38157. var t = v * (1 - s * (1 - f));
  38158. switch (i) {
  38159. case 0:
  38160. result.r = v;
  38161. result.g = t;
  38162. result.b = p;
  38163. break;
  38164. case 1:
  38165. result.r = q;
  38166. result.g = v;
  38167. result.b = p;
  38168. break;
  38169. case 2:
  38170. result.r = p;
  38171. result.g = v;
  38172. result.b = t;
  38173. break;
  38174. case 3:
  38175. result.r = p;
  38176. result.g = q;
  38177. result.b = v;
  38178. break;
  38179. case 4:
  38180. result.r = t;
  38181. result.g = p;
  38182. result.b = v;
  38183. break;
  38184. default:// case 5:
  38185. result.r = v;
  38186. result.g = p;
  38187. result.b = q;
  38188. break;
  38189. }
  38190. }
  38191. result.a = 1;
  38192. };
  38193. /**
  38194. * Returns a value clamped between min and max
  38195. * @param value The value to clamp
  38196. * @param min The minimum of value
  38197. * @param max The maximum of value
  38198. * @returns The clamped value.
  38199. */
  38200. ColorCurves.clamp = function (value, min, max) {
  38201. return Math.min(Math.max(value, min), max);
  38202. };
  38203. /**
  38204. * Clones the current color curve instance.
  38205. * @return The cloned curves
  38206. */
  38207. ColorCurves.prototype.clone = function () {
  38208. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38209. };
  38210. /**
  38211. * Serializes the current color curve instance to a json representation.
  38212. * @return a JSON representation
  38213. */
  38214. ColorCurves.prototype.serialize = function () {
  38215. return BABYLON.SerializationHelper.Serialize(this);
  38216. };
  38217. /**
  38218. * Parses the color curve from a json representation.
  38219. * @param source the JSON source to parse
  38220. * @return The parsed curves
  38221. */
  38222. ColorCurves.Parse = function (source) {
  38223. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38224. };
  38225. __decorate([
  38226. BABYLON.serialize()
  38227. ], ColorCurves.prototype, "_globalHue", void 0);
  38228. __decorate([
  38229. BABYLON.serialize()
  38230. ], ColorCurves.prototype, "_globalDensity", void 0);
  38231. __decorate([
  38232. BABYLON.serialize()
  38233. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38234. __decorate([
  38235. BABYLON.serialize()
  38236. ], ColorCurves.prototype, "_globalExposure", void 0);
  38237. __decorate([
  38238. BABYLON.serialize()
  38239. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38240. __decorate([
  38241. BABYLON.serialize()
  38242. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38243. __decorate([
  38244. BABYLON.serialize()
  38245. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38246. __decorate([
  38247. BABYLON.serialize()
  38248. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38249. __decorate([
  38250. BABYLON.serialize()
  38251. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38252. __decorate([
  38253. BABYLON.serialize()
  38254. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38255. __decorate([
  38256. BABYLON.serialize()
  38257. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38258. __decorate([
  38259. BABYLON.serialize()
  38260. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38261. return ColorCurves;
  38262. }());
  38263. BABYLON.ColorCurves = ColorCurves;
  38264. })(BABYLON || (BABYLON = {}));
  38265. //# sourceMappingURL=babylon.colorCurves.js.map
  38266. //# sourceMappingURL=babylon.behavior.js.map
  38267. var BABYLON;
  38268. (function (BABYLON) {
  38269. /**
  38270. * "Static Class" containing the most commonly used helper while dealing with material for
  38271. * rendering purpose.
  38272. *
  38273. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38274. *
  38275. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38276. */
  38277. var MaterialHelper = /** @class */ (function () {
  38278. function MaterialHelper() {
  38279. }
  38280. /**
  38281. * Bind the current view position to an effect.
  38282. * @param effect The effect to be bound
  38283. * @param scene The scene the eyes position is used from
  38284. */
  38285. MaterialHelper.BindEyePosition = function (effect, scene) {
  38286. if (scene._forcedViewPosition) {
  38287. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38288. return;
  38289. }
  38290. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38291. };
  38292. /**
  38293. * Helps preparing the defines values about the UVs in used in the effect.
  38294. * UVs are shared as much as we can accross chanels in the shaders.
  38295. * @param texture The texture we are preparing the UVs for
  38296. * @param defines The defines to update
  38297. * @param key The chanel key "diffuse", "specular"... used in the shader
  38298. */
  38299. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38300. defines._needUVs = true;
  38301. defines[key] = true;
  38302. if (texture.getTextureMatrix().isIdentity(true)) {
  38303. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38304. if (texture.coordinatesIndex === 0) {
  38305. defines["MAINUV1"] = true;
  38306. }
  38307. else {
  38308. defines["MAINUV2"] = true;
  38309. }
  38310. }
  38311. else {
  38312. defines[key + "DIRECTUV"] = 0;
  38313. }
  38314. };
  38315. /**
  38316. * Binds a texture matrix value to its corrsponding uniform
  38317. * @param texture The texture to bind the matrix for
  38318. * @param uniformBuffer The uniform buffer receivin the data
  38319. * @param key The chanel key "diffuse", "specular"... used in the shader
  38320. */
  38321. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38322. var matrix = texture.getTextureMatrix();
  38323. if (!matrix.isIdentity(true)) {
  38324. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38325. }
  38326. };
  38327. /**
  38328. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38329. * @param mesh defines the current mesh
  38330. * @param scene defines the current scene
  38331. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38332. * @param pointsCloud defines if point cloud rendering has to be turned on
  38333. * @param fogEnabled defines if fog has to be turned on
  38334. * @param alphaTest defines if alpha testing has to be turned on
  38335. * @param defines defines the current list of defines
  38336. */
  38337. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38338. if (defines._areMiscDirty) {
  38339. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38340. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38341. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38342. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38343. defines["ALPHATEST"] = alphaTest;
  38344. }
  38345. };
  38346. /**
  38347. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38348. * @param scene defines the current scene
  38349. * @param engine defines the current engine
  38350. * @param defines specifies the list of active defines
  38351. * @param useInstances defines if instances have to be turned on
  38352. * @param useClipPlane defines if clip plane have to be turned on
  38353. */
  38354. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38355. if (useClipPlane === void 0) { useClipPlane = null; }
  38356. var changed = false;
  38357. if (useClipPlane == null) {
  38358. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38359. }
  38360. if (defines["CLIPPLANE"] !== useClipPlane) {
  38361. defines["CLIPPLANE"] = useClipPlane;
  38362. changed = true;
  38363. }
  38364. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38365. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38366. changed = true;
  38367. }
  38368. if (defines["INSTANCES"] !== useInstances) {
  38369. defines["INSTANCES"] = useInstances;
  38370. changed = true;
  38371. }
  38372. if (changed) {
  38373. defines.markAsUnprocessed();
  38374. }
  38375. };
  38376. /**
  38377. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38378. * @param mesh The mesh containing the geometry data we will draw
  38379. * @param defines The defines to update
  38380. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38381. * @param useBones Precise whether bones should be used or not (override mesh info)
  38382. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38383. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38384. * @returns false if defines are considered not dirty and have not been checked
  38385. */
  38386. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38387. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38388. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38389. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38390. return false;
  38391. }
  38392. defines._normals = defines._needNormals;
  38393. defines._uvs = defines._needUVs;
  38394. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38395. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38396. defines["TANGENT"] = true;
  38397. }
  38398. if (defines._needUVs) {
  38399. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38400. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38401. }
  38402. else {
  38403. defines["UV1"] = false;
  38404. defines["UV2"] = false;
  38405. }
  38406. if (useVertexColor) {
  38407. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38408. defines["VERTEXCOLOR"] = hasVertexColors;
  38409. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38410. }
  38411. if (useBones) {
  38412. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38413. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38414. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38415. }
  38416. else {
  38417. defines["NUM_BONE_INFLUENCERS"] = 0;
  38418. defines["BonesPerMesh"] = 0;
  38419. }
  38420. }
  38421. if (useMorphTargets) {
  38422. var manager = mesh.morphTargetManager;
  38423. if (manager) {
  38424. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38425. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38426. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38427. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38428. }
  38429. else {
  38430. defines["MORPHTARGETS_TANGENT"] = false;
  38431. defines["MORPHTARGETS_NORMAL"] = false;
  38432. defines["MORPHTARGETS"] = false;
  38433. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38434. }
  38435. }
  38436. return true;
  38437. };
  38438. /**
  38439. * Prepares the defines related to the light information passed in parameter
  38440. * @param scene The scene we are intending to draw
  38441. * @param mesh The mesh the effect is compiling for
  38442. * @param defines The defines to update
  38443. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38444. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38445. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38446. * @returns true if normals will be required for the rest of the effect
  38447. */
  38448. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38449. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38450. if (disableLighting === void 0) { disableLighting = false; }
  38451. if (!defines._areLightsDirty) {
  38452. return defines._needNormals;
  38453. }
  38454. var lightIndex = 0;
  38455. var needNormals = false;
  38456. var needRebuild = false;
  38457. var lightmapMode = false;
  38458. var shadowEnabled = false;
  38459. var specularEnabled = false;
  38460. if (scene.lightsEnabled && !disableLighting) {
  38461. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38462. var light = _a[_i];
  38463. needNormals = true;
  38464. if (defines["LIGHT" + lightIndex] === undefined) {
  38465. needRebuild = true;
  38466. }
  38467. defines["LIGHT" + lightIndex] = true;
  38468. defines["SPOTLIGHT" + lightIndex] = false;
  38469. defines["HEMILIGHT" + lightIndex] = false;
  38470. defines["POINTLIGHT" + lightIndex] = false;
  38471. defines["DIRLIGHT" + lightIndex] = false;
  38472. var type;
  38473. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38474. type = "SPOTLIGHT" + lightIndex;
  38475. var spotLight = light;
  38476. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38477. }
  38478. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38479. type = "HEMILIGHT" + lightIndex;
  38480. }
  38481. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38482. type = "POINTLIGHT" + lightIndex;
  38483. }
  38484. else {
  38485. type = "DIRLIGHT" + lightIndex;
  38486. }
  38487. defines[type] = true;
  38488. // Specular
  38489. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38490. specularEnabled = true;
  38491. }
  38492. // Shadows
  38493. defines["SHADOW" + lightIndex] = false;
  38494. defines["SHADOWPCF" + lightIndex] = false;
  38495. defines["SHADOWESM" + lightIndex] = false;
  38496. defines["SHADOWCUBE" + lightIndex] = false;
  38497. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38498. var shadowGenerator = light.getShadowGenerator();
  38499. if (shadowGenerator) {
  38500. shadowEnabled = true;
  38501. shadowGenerator.prepareDefines(defines, lightIndex);
  38502. }
  38503. }
  38504. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38505. lightmapMode = true;
  38506. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38507. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38508. }
  38509. else {
  38510. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38511. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38512. }
  38513. lightIndex++;
  38514. if (lightIndex === maxSimultaneousLights)
  38515. break;
  38516. }
  38517. }
  38518. defines["SPECULARTERM"] = specularEnabled;
  38519. defines["SHADOWS"] = shadowEnabled;
  38520. // Resetting all other lights if any
  38521. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38522. if (defines["LIGHT" + index] !== undefined) {
  38523. defines["LIGHT" + index] = false;
  38524. defines["HEMILIGHT" + lightIndex] = false;
  38525. defines["POINTLIGHT" + lightIndex] = false;
  38526. defines["DIRLIGHT" + lightIndex] = false;
  38527. defines["SPOTLIGHT" + lightIndex] = false;
  38528. defines["SHADOW" + lightIndex] = false;
  38529. }
  38530. }
  38531. var caps = scene.getEngine().getCaps();
  38532. if (defines["SHADOWFLOAT"] === undefined) {
  38533. needRebuild = true;
  38534. }
  38535. defines["SHADOWFLOAT"] = shadowEnabled &&
  38536. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38537. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38538. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38539. if (needRebuild) {
  38540. defines.rebuild();
  38541. }
  38542. return needNormals;
  38543. };
  38544. /**
  38545. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38546. * that won t be acctive due to defines being turned off.
  38547. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38548. * @param samplersList The samplers list
  38549. * @param defines The defines helping in the list generation
  38550. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38551. */
  38552. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38553. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38554. var uniformsList;
  38555. var uniformBuffersList = null;
  38556. if (uniformsListOrOptions.uniformsNames) {
  38557. var options = uniformsListOrOptions;
  38558. uniformsList = options.uniformsNames;
  38559. uniformBuffersList = options.uniformBuffersNames;
  38560. samplersList = options.samplers;
  38561. defines = options.defines;
  38562. maxSimultaneousLights = options.maxSimultaneousLights;
  38563. }
  38564. else {
  38565. uniformsList = uniformsListOrOptions;
  38566. if (!samplersList) {
  38567. samplersList = [];
  38568. }
  38569. }
  38570. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38571. if (!defines["LIGHT" + lightIndex]) {
  38572. break;
  38573. }
  38574. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38575. if (uniformBuffersList) {
  38576. uniformBuffersList.push("Light" + lightIndex);
  38577. }
  38578. samplersList.push("shadowSampler" + lightIndex);
  38579. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38580. samplersList.push("projectionLightSampler" + lightIndex);
  38581. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38582. }
  38583. }
  38584. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38585. uniformsList.push("morphTargetInfluences");
  38586. }
  38587. };
  38588. /**
  38589. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38590. * @param defines The defines to update while falling back
  38591. * @param fallbacks The authorized effect fallbacks
  38592. * @param maxSimultaneousLights The maximum number of lights allowed
  38593. * @param rank the current rank of the Effect
  38594. * @returns The newly affected rank
  38595. */
  38596. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38597. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38598. if (rank === void 0) { rank = 0; }
  38599. var lightFallbackRank = 0;
  38600. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38601. if (!defines["LIGHT" + lightIndex]) {
  38602. break;
  38603. }
  38604. if (lightIndex > 0) {
  38605. lightFallbackRank = rank + lightIndex;
  38606. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38607. }
  38608. if (!defines["SHADOWS"]) {
  38609. if (defines["SHADOW" + lightIndex]) {
  38610. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38611. }
  38612. if (defines["SHADOWPCF" + lightIndex]) {
  38613. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38614. }
  38615. if (defines["SHADOWESM" + lightIndex]) {
  38616. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38617. }
  38618. }
  38619. }
  38620. return lightFallbackRank++;
  38621. };
  38622. /**
  38623. * Prepares the list of attributes required for morph targets according to the effect defines.
  38624. * @param attribs The current list of supported attribs
  38625. * @param mesh The mesh to prepare the morph targets attributes for
  38626. * @param defines The current Defines of the effect
  38627. */
  38628. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38629. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38630. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38631. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38632. var manager = mesh.morphTargetManager;
  38633. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38634. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38635. for (var index = 0; index < influencers; index++) {
  38636. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38637. if (normal) {
  38638. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38639. }
  38640. if (tangent) {
  38641. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38642. }
  38643. if (attribs.length > maxAttributesCount) {
  38644. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38645. }
  38646. }
  38647. }
  38648. };
  38649. /**
  38650. * Prepares the list of attributes required for bones according to the effect defines.
  38651. * @param attribs The current list of supported attribs
  38652. * @param mesh The mesh to prepare the bones attributes for
  38653. * @param defines The current Defines of the effect
  38654. * @param fallbacks The current efffect fallback strategy
  38655. */
  38656. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38657. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38658. fallbacks.addCPUSkinningFallback(0, mesh);
  38659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38661. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38664. }
  38665. }
  38666. };
  38667. /**
  38668. * Prepares the list of attributes required for instances according to the effect defines.
  38669. * @param attribs The current list of supported attribs
  38670. * @param defines The current Defines of the effect
  38671. */
  38672. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38673. if (defines["INSTANCES"]) {
  38674. attribs.push("world0");
  38675. attribs.push("world1");
  38676. attribs.push("world2");
  38677. attribs.push("world3");
  38678. }
  38679. };
  38680. /**
  38681. * Binds the light shadow information to the effect for the given mesh.
  38682. * @param light The light containing the generator
  38683. * @param scene The scene the lights belongs to
  38684. * @param mesh The mesh we are binding the information to render
  38685. * @param lightIndex The light index in the effect used to render the mesh
  38686. * @param effect The effect we are binding the data to
  38687. */
  38688. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38689. if (light.shadowEnabled && mesh.receiveShadows) {
  38690. var shadowGenerator = light.getShadowGenerator();
  38691. if (shadowGenerator) {
  38692. shadowGenerator.bindShadowLight(lightIndex, effect);
  38693. }
  38694. }
  38695. };
  38696. /**
  38697. * Binds the light information to the effect.
  38698. * @param light The light containing the generator
  38699. * @param effect The effect we are binding the data to
  38700. * @param lightIndex The light index in the effect used to render
  38701. */
  38702. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38703. light.transferToEffect(effect, lightIndex + "");
  38704. };
  38705. /**
  38706. * Binds the lights information from the scene to the effect for the given mesh.
  38707. * @param scene The scene the lights belongs to
  38708. * @param mesh The mesh we are binding the information to render
  38709. * @param effect The effect we are binding the data to
  38710. * @param defines The generated defines for the effect
  38711. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38712. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38713. */
  38714. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38715. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38716. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38717. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38718. for (var i = 0; i < len; i++) {
  38719. var light = mesh._lightSources[i];
  38720. var iAsString = i.toString();
  38721. var scaledIntensity = light.getScaledIntensity();
  38722. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38723. MaterialHelper.BindLightProperties(light, effect, i);
  38724. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38725. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38726. if (defines["SPECULARTERM"]) {
  38727. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38728. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38729. }
  38730. // Shadows
  38731. if (scene.shadowsEnabled) {
  38732. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38733. }
  38734. light._uniformBuffer.update();
  38735. }
  38736. };
  38737. /**
  38738. * Binds the fog information from the scene to the effect for the given mesh.
  38739. * @param scene The scene the lights belongs to
  38740. * @param mesh The mesh we are binding the information to render
  38741. * @param effect The effect we are binding the data to
  38742. */
  38743. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38744. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38745. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38746. effect.setColor3("vFogColor", scene.fogColor);
  38747. }
  38748. };
  38749. /**
  38750. * Binds the bones information from the mesh to the effect.
  38751. * @param mesh The mesh we are binding the information to render
  38752. * @param effect The effect we are binding the data to
  38753. */
  38754. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38755. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38756. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38757. if (matrices && effect) {
  38758. effect.setMatrices("mBones", matrices);
  38759. }
  38760. }
  38761. };
  38762. /**
  38763. * Binds the morph targets information from the mesh to the effect.
  38764. * @param abstractMesh The mesh we are binding the information to render
  38765. * @param effect The effect we are binding the data to
  38766. */
  38767. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38768. var manager = abstractMesh.morphTargetManager;
  38769. if (!abstractMesh || !manager) {
  38770. return;
  38771. }
  38772. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38773. };
  38774. /**
  38775. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38776. * @param defines The generated defines used in the effect
  38777. * @param effect The effect we are binding the data to
  38778. * @param scene The scene we are willing to render with logarithmic scale for
  38779. */
  38780. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38781. if (defines["LOGARITHMICDEPTH"]) {
  38782. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38783. }
  38784. };
  38785. /**
  38786. * Binds the clip plane information from the scene to the effect.
  38787. * @param scene The scene the clip plane information are extracted from
  38788. * @param effect The effect we are binding the data to
  38789. */
  38790. MaterialHelper.BindClipPlane = function (effect, scene) {
  38791. if (scene.clipPlane) {
  38792. var clipPlane = scene.clipPlane;
  38793. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38794. }
  38795. };
  38796. return MaterialHelper;
  38797. }());
  38798. BABYLON.MaterialHelper = MaterialHelper;
  38799. })(BABYLON || (BABYLON = {}));
  38800. //# sourceMappingURL=babylon.materialHelper.js.map
  38801. var BABYLON;
  38802. (function (BABYLON) {
  38803. var PushMaterial = /** @class */ (function (_super) {
  38804. __extends(PushMaterial, _super);
  38805. function PushMaterial(name, scene) {
  38806. var _this = _super.call(this, name, scene) || this;
  38807. _this._normalMatrix = new BABYLON.Matrix();
  38808. _this.storeEffectOnSubMeshes = true;
  38809. return _this;
  38810. }
  38811. PushMaterial.prototype.getEffect = function () {
  38812. return this._activeEffect;
  38813. };
  38814. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38815. if (!mesh) {
  38816. return false;
  38817. }
  38818. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38819. return true;
  38820. }
  38821. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38822. };
  38823. /**
  38824. * Binds the given world matrix to the active effect
  38825. *
  38826. * @param world the matrix to bind
  38827. */
  38828. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38829. this._activeEffect.setMatrix("world", world);
  38830. };
  38831. /**
  38832. * Binds the given normal matrix to the active effect
  38833. *
  38834. * @param normalMatrix the matrix to bind
  38835. */
  38836. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38837. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38838. };
  38839. PushMaterial.prototype.bind = function (world, mesh) {
  38840. if (!mesh) {
  38841. return;
  38842. }
  38843. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38844. };
  38845. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38846. if (effect === void 0) { effect = null; }
  38847. _super.prototype._afterBind.call(this, mesh);
  38848. this.getScene()._cachedEffect = effect;
  38849. };
  38850. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38851. if (visibility === void 0) { visibility = 1; }
  38852. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38853. };
  38854. return PushMaterial;
  38855. }(BABYLON.Material));
  38856. BABYLON.PushMaterial = PushMaterial;
  38857. })(BABYLON || (BABYLON = {}));
  38858. //# sourceMappingURL=babylon.pushMaterial.js.map
  38859. var BABYLON;
  38860. (function (BABYLON) {
  38861. /** @ignore */
  38862. var StandardMaterialDefines = /** @class */ (function (_super) {
  38863. __extends(StandardMaterialDefines, _super);
  38864. function StandardMaterialDefines() {
  38865. var _this = _super.call(this) || this;
  38866. _this.MAINUV1 = false;
  38867. _this.MAINUV2 = false;
  38868. _this.DIFFUSE = false;
  38869. _this.DIFFUSEDIRECTUV = 0;
  38870. _this.AMBIENT = false;
  38871. _this.AMBIENTDIRECTUV = 0;
  38872. _this.OPACITY = false;
  38873. _this.OPACITYDIRECTUV = 0;
  38874. _this.OPACITYRGB = false;
  38875. _this.REFLECTION = false;
  38876. _this.EMISSIVE = false;
  38877. _this.EMISSIVEDIRECTUV = 0;
  38878. _this.SPECULAR = false;
  38879. _this.SPECULARDIRECTUV = 0;
  38880. _this.BUMP = false;
  38881. _this.BUMPDIRECTUV = 0;
  38882. _this.PARALLAX = false;
  38883. _this.PARALLAXOCCLUSION = false;
  38884. _this.SPECULAROVERALPHA = false;
  38885. _this.CLIPPLANE = false;
  38886. _this.ALPHATEST = false;
  38887. _this.DEPTHPREPASS = false;
  38888. _this.ALPHAFROMDIFFUSE = false;
  38889. _this.POINTSIZE = false;
  38890. _this.FOG = false;
  38891. _this.SPECULARTERM = false;
  38892. _this.DIFFUSEFRESNEL = false;
  38893. _this.OPACITYFRESNEL = false;
  38894. _this.REFLECTIONFRESNEL = false;
  38895. _this.REFRACTIONFRESNEL = false;
  38896. _this.EMISSIVEFRESNEL = false;
  38897. _this.FRESNEL = false;
  38898. _this.NORMAL = false;
  38899. _this.UV1 = false;
  38900. _this.UV2 = false;
  38901. _this.VERTEXCOLOR = false;
  38902. _this.VERTEXALPHA = false;
  38903. _this.NUM_BONE_INFLUENCERS = 0;
  38904. _this.BonesPerMesh = 0;
  38905. _this.INSTANCES = false;
  38906. _this.GLOSSINESS = false;
  38907. _this.ROUGHNESS = false;
  38908. _this.EMISSIVEASILLUMINATION = false;
  38909. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38910. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38911. _this.LIGHTMAP = false;
  38912. _this.LIGHTMAPDIRECTUV = 0;
  38913. _this.OBJECTSPACE_NORMALMAP = false;
  38914. _this.USELIGHTMAPASSHADOWMAP = false;
  38915. _this.REFLECTIONMAP_3D = false;
  38916. _this.REFLECTIONMAP_SPHERICAL = false;
  38917. _this.REFLECTIONMAP_PLANAR = false;
  38918. _this.REFLECTIONMAP_CUBIC = false;
  38919. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38920. _this.REFLECTIONMAP_PROJECTION = false;
  38921. _this.REFLECTIONMAP_SKYBOX = false;
  38922. _this.REFLECTIONMAP_EXPLICIT = false;
  38923. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38924. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38925. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38926. _this.INVERTCUBICMAP = false;
  38927. _this.LOGARITHMICDEPTH = false;
  38928. _this.REFRACTION = false;
  38929. _this.REFRACTIONMAP_3D = false;
  38930. _this.REFLECTIONOVERALPHA = false;
  38931. _this.TWOSIDEDLIGHTING = false;
  38932. _this.SHADOWFLOAT = false;
  38933. _this.MORPHTARGETS = false;
  38934. _this.MORPHTARGETS_NORMAL = false;
  38935. _this.MORPHTARGETS_TANGENT = false;
  38936. _this.NUM_MORPH_INFLUENCERS = 0;
  38937. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38938. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38939. _this.IMAGEPROCESSING = false;
  38940. _this.VIGNETTE = false;
  38941. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38942. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38943. _this.TONEMAPPING = false;
  38944. _this.CONTRAST = false;
  38945. _this.COLORCURVES = false;
  38946. _this.COLORGRADING = false;
  38947. _this.COLORGRADING3D = false;
  38948. _this.SAMPLER3DGREENDEPTH = false;
  38949. _this.SAMPLER3DBGRMAP = false;
  38950. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38951. _this.EXPOSURE = false;
  38952. _this.GRAIN = false;
  38953. _this.rebuild();
  38954. return _this;
  38955. }
  38956. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38957. var modes = [
  38958. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38959. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38960. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38961. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38962. ];
  38963. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38964. var mode = modes_1[_i];
  38965. this[mode] = (mode === modeToEnable);
  38966. }
  38967. };
  38968. return StandardMaterialDefines;
  38969. }(BABYLON.MaterialDefines));
  38970. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38971. var StandardMaterial = /** @class */ (function (_super) {
  38972. __extends(StandardMaterial, _super);
  38973. function StandardMaterial(name, scene) {
  38974. var _this = _super.call(this, name, scene) || this;
  38975. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38976. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38977. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38978. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38979. _this.specularPower = 64;
  38980. _this._useAlphaFromDiffuseTexture = false;
  38981. _this._useEmissiveAsIllumination = false;
  38982. _this._linkEmissiveWithDiffuse = false;
  38983. _this._useSpecularOverAlpha = false;
  38984. _this._useReflectionOverAlpha = false;
  38985. _this._disableLighting = false;
  38986. _this._useObjectSpaceNormalMap = false;
  38987. _this._useParallax = false;
  38988. _this._useParallaxOcclusion = false;
  38989. _this.parallaxScaleBias = 0.05;
  38990. _this._roughness = 0;
  38991. _this.indexOfRefraction = 0.98;
  38992. _this.invertRefractionY = true;
  38993. _this._useLightmapAsShadowmap = false;
  38994. _this._useReflectionFresnelFromSpecular = false;
  38995. _this._useGlossinessFromSpecularMapAlpha = false;
  38996. _this._maxSimultaneousLights = 4;
  38997. /**
  38998. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38999. */
  39000. _this._invertNormalMapX = false;
  39001. /**
  39002. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39003. */
  39004. _this._invertNormalMapY = false;
  39005. /**
  39006. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39007. */
  39008. _this._twoSidedLighting = false;
  39009. _this._renderTargets = new BABYLON.SmartArray(16);
  39010. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39011. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39012. // Setup the default processing configuration to the scene.
  39013. _this._attachImageProcessingConfiguration(null);
  39014. _this.getRenderTargetTextures = function () {
  39015. _this._renderTargets.reset();
  39016. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39017. _this._renderTargets.push(_this._reflectionTexture);
  39018. }
  39019. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39020. _this._renderTargets.push(_this._refractionTexture);
  39021. }
  39022. return _this._renderTargets;
  39023. };
  39024. return _this;
  39025. }
  39026. ;
  39027. ;
  39028. ;
  39029. ;
  39030. ;
  39031. ;
  39032. ;
  39033. ;
  39034. ;
  39035. ;
  39036. ;
  39037. ;
  39038. ;
  39039. ;
  39040. ;
  39041. ;
  39042. ;
  39043. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39044. /**
  39045. * Gets the image processing configuration used either in this material.
  39046. */
  39047. get: function () {
  39048. return this._imageProcessingConfiguration;
  39049. },
  39050. /**
  39051. * Sets the Default image processing configuration used either in the this material.
  39052. *
  39053. * If sets to null, the scene one is in use.
  39054. */
  39055. set: function (value) {
  39056. this._attachImageProcessingConfiguration(value);
  39057. // Ensure the effect will be rebuilt.
  39058. this._markAllSubMeshesAsTexturesDirty();
  39059. },
  39060. enumerable: true,
  39061. configurable: true
  39062. });
  39063. /**
  39064. * Attaches a new image processing configuration to the Standard Material.
  39065. * @param configuration
  39066. */
  39067. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39068. var _this = this;
  39069. if (configuration === this._imageProcessingConfiguration) {
  39070. return;
  39071. }
  39072. // Detaches observer.
  39073. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39074. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39075. }
  39076. // Pick the scene configuration if needed.
  39077. if (!configuration) {
  39078. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39079. }
  39080. else {
  39081. this._imageProcessingConfiguration = configuration;
  39082. }
  39083. // Attaches observer.
  39084. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39085. _this._markAllSubMeshesAsImageProcessingDirty();
  39086. });
  39087. };
  39088. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39089. /**
  39090. * Gets wether the color curves effect is enabled.
  39091. */
  39092. get: function () {
  39093. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39094. },
  39095. /**
  39096. * Sets wether the color curves effect is enabled.
  39097. */
  39098. set: function (value) {
  39099. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39100. },
  39101. enumerable: true,
  39102. configurable: true
  39103. });
  39104. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39105. /**
  39106. * Gets wether the color grading effect is enabled.
  39107. */
  39108. get: function () {
  39109. return this.imageProcessingConfiguration.colorGradingEnabled;
  39110. },
  39111. /**
  39112. * Gets wether the color grading effect is enabled.
  39113. */
  39114. set: function (value) {
  39115. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39116. },
  39117. enumerable: true,
  39118. configurable: true
  39119. });
  39120. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39121. /**
  39122. * Gets wether tonemapping is enabled or not.
  39123. */
  39124. get: function () {
  39125. return this._imageProcessingConfiguration.toneMappingEnabled;
  39126. },
  39127. /**
  39128. * Sets wether tonemapping is enabled or not
  39129. */
  39130. set: function (value) {
  39131. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39132. },
  39133. enumerable: true,
  39134. configurable: true
  39135. });
  39136. ;
  39137. ;
  39138. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39139. /**
  39140. * The camera exposure used on this material.
  39141. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39142. * This corresponds to a photographic exposure.
  39143. */
  39144. get: function () {
  39145. return this._imageProcessingConfiguration.exposure;
  39146. },
  39147. /**
  39148. * The camera exposure used on this material.
  39149. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39150. * This corresponds to a photographic exposure.
  39151. */
  39152. set: function (value) {
  39153. this._imageProcessingConfiguration.exposure = value;
  39154. },
  39155. enumerable: true,
  39156. configurable: true
  39157. });
  39158. ;
  39159. ;
  39160. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39161. /**
  39162. * Gets The camera contrast used on this material.
  39163. */
  39164. get: function () {
  39165. return this._imageProcessingConfiguration.contrast;
  39166. },
  39167. /**
  39168. * Sets The camera contrast used on this material.
  39169. */
  39170. set: function (value) {
  39171. this._imageProcessingConfiguration.contrast = value;
  39172. },
  39173. enumerable: true,
  39174. configurable: true
  39175. });
  39176. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39177. /**
  39178. * Gets the Color Grading 2D Lookup Texture.
  39179. */
  39180. get: function () {
  39181. return this._imageProcessingConfiguration.colorGradingTexture;
  39182. },
  39183. /**
  39184. * Sets the Color Grading 2D Lookup Texture.
  39185. */
  39186. set: function (value) {
  39187. this._imageProcessingConfiguration.colorGradingTexture = value;
  39188. },
  39189. enumerable: true,
  39190. configurable: true
  39191. });
  39192. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39193. /**
  39194. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39195. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39196. * 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;
  39197. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39198. */
  39199. get: function () {
  39200. return this._imageProcessingConfiguration.colorCurves;
  39201. },
  39202. /**
  39203. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39204. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39205. * 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;
  39206. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39207. */
  39208. set: function (value) {
  39209. this._imageProcessingConfiguration.colorCurves = value;
  39210. },
  39211. enumerable: true,
  39212. configurable: true
  39213. });
  39214. StandardMaterial.prototype.getClassName = function () {
  39215. return "StandardMaterial";
  39216. };
  39217. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39218. get: function () {
  39219. return this._useLogarithmicDepth;
  39220. },
  39221. set: function (value) {
  39222. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39223. this._markAllSubMeshesAsMiscDirty();
  39224. },
  39225. enumerable: true,
  39226. configurable: true
  39227. });
  39228. StandardMaterial.prototype.needAlphaBlending = function () {
  39229. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39230. };
  39231. StandardMaterial.prototype.needAlphaTesting = function () {
  39232. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39233. };
  39234. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39235. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39236. };
  39237. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39238. return this._diffuseTexture;
  39239. };
  39240. /**
  39241. * Child classes can use it to update shaders
  39242. */
  39243. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39244. if (useInstances === void 0) { useInstances = false; }
  39245. if (subMesh.effect && this.isFrozen) {
  39246. if (this._wasPreviouslyReady && subMesh.effect) {
  39247. return true;
  39248. }
  39249. }
  39250. if (!subMesh._materialDefines) {
  39251. subMesh._materialDefines = new StandardMaterialDefines();
  39252. }
  39253. var scene = this.getScene();
  39254. var defines = subMesh._materialDefines;
  39255. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39256. if (defines._renderId === scene.getRenderId()) {
  39257. return true;
  39258. }
  39259. }
  39260. var engine = scene.getEngine();
  39261. // Lights
  39262. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39263. // Textures
  39264. if (defines._areTexturesDirty) {
  39265. defines._needUVs = false;
  39266. defines.MAINUV1 = false;
  39267. defines.MAINUV2 = false;
  39268. if (scene.texturesEnabled) {
  39269. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39270. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39271. return false;
  39272. }
  39273. else {
  39274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39275. }
  39276. }
  39277. else {
  39278. defines.DIFFUSE = false;
  39279. }
  39280. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39281. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39282. return false;
  39283. }
  39284. else {
  39285. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39286. }
  39287. }
  39288. else {
  39289. defines.AMBIENT = false;
  39290. }
  39291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39292. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39293. return false;
  39294. }
  39295. else {
  39296. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39297. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39298. }
  39299. }
  39300. else {
  39301. defines.OPACITY = false;
  39302. }
  39303. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39304. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39305. return false;
  39306. }
  39307. else {
  39308. defines._needNormals = true;
  39309. defines.REFLECTION = true;
  39310. defines.ROUGHNESS = (this._roughness > 0);
  39311. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39312. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39313. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39314. switch (this._reflectionTexture.coordinatesMode) {
  39315. case BABYLON.Texture.CUBIC_MODE:
  39316. case BABYLON.Texture.INVCUBIC_MODE:
  39317. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39318. break;
  39319. case BABYLON.Texture.EXPLICIT_MODE:
  39320. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39321. break;
  39322. case BABYLON.Texture.PLANAR_MODE:
  39323. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39324. break;
  39325. case BABYLON.Texture.PROJECTION_MODE:
  39326. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39327. break;
  39328. case BABYLON.Texture.SKYBOX_MODE:
  39329. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39330. break;
  39331. case BABYLON.Texture.SPHERICAL_MODE:
  39332. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39333. break;
  39334. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39335. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39336. break;
  39337. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39338. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39339. break;
  39340. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39341. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39342. break;
  39343. }
  39344. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39345. }
  39346. }
  39347. else {
  39348. defines.REFLECTION = false;
  39349. }
  39350. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39351. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39352. return false;
  39353. }
  39354. else {
  39355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39356. }
  39357. }
  39358. else {
  39359. defines.EMISSIVE = false;
  39360. }
  39361. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39362. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39363. return false;
  39364. }
  39365. else {
  39366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39367. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39368. }
  39369. }
  39370. else {
  39371. defines.LIGHTMAP = false;
  39372. }
  39373. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39374. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39375. return false;
  39376. }
  39377. else {
  39378. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39379. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39380. }
  39381. }
  39382. else {
  39383. defines.SPECULAR = false;
  39384. }
  39385. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39386. // Bump texure can not be not blocking.
  39387. if (!this._bumpTexture.isReady()) {
  39388. return false;
  39389. }
  39390. else {
  39391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39392. defines.PARALLAX = this._useParallax;
  39393. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39394. }
  39395. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39396. }
  39397. else {
  39398. defines.BUMP = false;
  39399. }
  39400. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39401. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39402. return false;
  39403. }
  39404. else {
  39405. defines._needUVs = true;
  39406. defines.REFRACTION = true;
  39407. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39408. }
  39409. }
  39410. else {
  39411. defines.REFRACTION = false;
  39412. }
  39413. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39414. }
  39415. else {
  39416. defines.DIFFUSE = false;
  39417. defines.AMBIENT = false;
  39418. defines.OPACITY = false;
  39419. defines.REFLECTION = false;
  39420. defines.EMISSIVE = false;
  39421. defines.LIGHTMAP = false;
  39422. defines.BUMP = false;
  39423. defines.REFRACTION = false;
  39424. }
  39425. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39426. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39427. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39428. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39429. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39430. }
  39431. if (defines._areImageProcessingDirty) {
  39432. if (!this._imageProcessingConfiguration.isReady()) {
  39433. return false;
  39434. }
  39435. this._imageProcessingConfiguration.prepareDefines(defines);
  39436. }
  39437. if (defines._areFresnelDirty) {
  39438. if (StandardMaterial.FresnelEnabled) {
  39439. // Fresnel
  39440. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39441. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39442. this._reflectionFresnelParameters) {
  39443. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39444. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39445. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39446. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39447. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39448. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39449. defines._needNormals = true;
  39450. defines.FRESNEL = true;
  39451. }
  39452. }
  39453. else {
  39454. defines.FRESNEL = false;
  39455. }
  39456. }
  39457. // Misc.
  39458. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39459. // Attribs
  39460. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39461. // Values that need to be evaluated on every frame
  39462. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39463. // Get correct effect
  39464. if (defines.isDirty) {
  39465. defines.markAsProcessed();
  39466. scene.resetCachedMaterial();
  39467. // Fallbacks
  39468. var fallbacks = new BABYLON.EffectFallbacks();
  39469. if (defines.REFLECTION) {
  39470. fallbacks.addFallback(0, "REFLECTION");
  39471. }
  39472. if (defines.SPECULAR) {
  39473. fallbacks.addFallback(0, "SPECULAR");
  39474. }
  39475. if (defines.BUMP) {
  39476. fallbacks.addFallback(0, "BUMP");
  39477. }
  39478. if (defines.PARALLAX) {
  39479. fallbacks.addFallback(1, "PARALLAX");
  39480. }
  39481. if (defines.PARALLAXOCCLUSION) {
  39482. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39483. }
  39484. if (defines.SPECULAROVERALPHA) {
  39485. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39486. }
  39487. if (defines.FOG) {
  39488. fallbacks.addFallback(1, "FOG");
  39489. }
  39490. if (defines.POINTSIZE) {
  39491. fallbacks.addFallback(0, "POINTSIZE");
  39492. }
  39493. if (defines.LOGARITHMICDEPTH) {
  39494. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39495. }
  39496. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39497. if (defines.SPECULARTERM) {
  39498. fallbacks.addFallback(0, "SPECULARTERM");
  39499. }
  39500. if (defines.DIFFUSEFRESNEL) {
  39501. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39502. }
  39503. if (defines.OPACITYFRESNEL) {
  39504. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39505. }
  39506. if (defines.REFLECTIONFRESNEL) {
  39507. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39508. }
  39509. if (defines.EMISSIVEFRESNEL) {
  39510. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39511. }
  39512. if (defines.FRESNEL) {
  39513. fallbacks.addFallback(4, "FRESNEL");
  39514. }
  39515. //Attributes
  39516. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39517. if (defines.NORMAL) {
  39518. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39519. }
  39520. if (defines.UV1) {
  39521. attribs.push(BABYLON.VertexBuffer.UVKind);
  39522. }
  39523. if (defines.UV2) {
  39524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39525. }
  39526. if (defines.VERTEXCOLOR) {
  39527. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39528. }
  39529. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39530. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39531. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39532. var shaderName = "default";
  39533. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39534. "vFogInfos", "vFogColor", "pointSize",
  39535. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39536. "mBones",
  39537. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39538. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39539. "vReflectionPosition", "vReflectionSize",
  39540. "logarithmicDepthConstant", "vTangentSpaceParams"
  39541. ];
  39542. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39543. var uniformBuffers = ["Material", "Scene"];
  39544. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39545. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39547. uniformsNames: uniforms,
  39548. uniformBuffersNames: uniformBuffers,
  39549. samplers: samplers,
  39550. defines: defines,
  39551. maxSimultaneousLights: this._maxSimultaneousLights
  39552. });
  39553. if (this.customShaderNameResolve) {
  39554. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39555. }
  39556. var join = defines.toString();
  39557. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39558. attributes: attribs,
  39559. uniformsNames: uniforms,
  39560. uniformBuffersNames: uniformBuffers,
  39561. samplers: samplers,
  39562. defines: join,
  39563. fallbacks: fallbacks,
  39564. onCompiled: this.onCompiled,
  39565. onError: this.onError,
  39566. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39567. }, engine), defines);
  39568. this.buildUniformLayout();
  39569. }
  39570. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39571. return false;
  39572. }
  39573. defines._renderId = scene.getRenderId();
  39574. this._wasPreviouslyReady = true;
  39575. return true;
  39576. };
  39577. StandardMaterial.prototype.buildUniformLayout = function () {
  39578. // Order is important !
  39579. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39580. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39581. this._uniformBuffer.addUniform("opacityParts", 4);
  39582. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39583. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39584. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39585. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39586. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39587. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39588. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39589. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39590. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39591. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39592. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39593. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39594. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39595. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39596. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39597. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39598. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39599. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39600. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39601. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39602. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39603. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39604. this._uniformBuffer.addUniform("specularMatrix", 16);
  39605. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39606. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39607. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39608. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39609. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39610. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39611. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39612. this._uniformBuffer.addUniform("pointSize", 1);
  39613. this._uniformBuffer.create();
  39614. };
  39615. StandardMaterial.prototype.unbind = function () {
  39616. if (this._activeEffect) {
  39617. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39618. this._activeEffect.setTexture("reflection2DSampler", null);
  39619. }
  39620. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39621. this._activeEffect.setTexture("refraction2DSampler", null);
  39622. }
  39623. }
  39624. _super.prototype.unbind.call(this);
  39625. };
  39626. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39627. var scene = this.getScene();
  39628. var defines = subMesh._materialDefines;
  39629. if (!defines) {
  39630. return;
  39631. }
  39632. var effect = subMesh.effect;
  39633. if (!effect) {
  39634. return;
  39635. }
  39636. this._activeEffect = effect;
  39637. // Matrices
  39638. this.bindOnlyWorldMatrix(world);
  39639. // Normal Matrix
  39640. if (defines.OBJECTSPACE_NORMALMAP) {
  39641. world.toNormalMatrix(this._normalMatrix);
  39642. this.bindOnlyNormalMatrix(this._normalMatrix);
  39643. }
  39644. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39645. // Bones
  39646. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39647. if (mustRebind) {
  39648. this._uniformBuffer.bindToEffect(effect, "Material");
  39649. this.bindViewProjection(effect);
  39650. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39651. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39652. // Fresnel
  39653. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39654. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39655. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39656. }
  39657. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39658. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39659. }
  39660. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39661. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39662. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39663. }
  39664. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39665. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39666. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39667. }
  39668. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39669. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39670. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39671. }
  39672. }
  39673. // Textures
  39674. if (scene.texturesEnabled) {
  39675. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39676. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39677. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39678. }
  39679. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39680. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39681. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39682. }
  39683. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39684. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39685. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39686. }
  39687. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39688. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39689. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39690. if (this._reflectionTexture.boundingBoxSize) {
  39691. var cubeTexture = this._reflectionTexture;
  39692. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39693. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39694. }
  39695. }
  39696. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39697. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39698. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39699. }
  39700. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39701. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39702. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39703. }
  39704. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39705. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39706. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39707. }
  39708. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39709. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39710. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39711. if (scene._mirroredCameraPosition) {
  39712. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39713. }
  39714. else {
  39715. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39716. }
  39717. }
  39718. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39719. var depth = 1.0;
  39720. if (!this._refractionTexture.isCube) {
  39721. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39722. if (this._refractionTexture.depth) {
  39723. depth = this._refractionTexture.depth;
  39724. }
  39725. }
  39726. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39727. }
  39728. }
  39729. // Point size
  39730. if (this.pointsCloud) {
  39731. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39732. }
  39733. if (defines.SPECULARTERM) {
  39734. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39735. }
  39736. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39737. // Diffuse
  39738. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39739. }
  39740. // Textures
  39741. if (scene.texturesEnabled) {
  39742. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39743. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39744. }
  39745. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39746. effect.setTexture("ambientSampler", this._ambientTexture);
  39747. }
  39748. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39749. effect.setTexture("opacitySampler", this._opacityTexture);
  39750. }
  39751. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39752. if (this._reflectionTexture.isCube) {
  39753. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39754. }
  39755. else {
  39756. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39757. }
  39758. }
  39759. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39760. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39761. }
  39762. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39763. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39764. }
  39765. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39766. effect.setTexture("specularSampler", this._specularTexture);
  39767. }
  39768. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39769. effect.setTexture("bumpSampler", this._bumpTexture);
  39770. }
  39771. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39772. var depth = 1.0;
  39773. if (this._refractionTexture.isCube) {
  39774. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39775. }
  39776. else {
  39777. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39778. }
  39779. }
  39780. }
  39781. // Clip plane
  39782. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39783. // Colors
  39784. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39785. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39786. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39787. }
  39788. if (mustRebind || !this.isFrozen) {
  39789. // Lights
  39790. if (scene.lightsEnabled && !this._disableLighting) {
  39791. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39792. }
  39793. // View
  39794. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39795. this.bindView(effect);
  39796. }
  39797. // Fog
  39798. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39799. // Morph targets
  39800. if (defines.NUM_MORPH_INFLUENCERS) {
  39801. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39802. }
  39803. // Log. depth
  39804. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39805. // image processing
  39806. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39807. this._imageProcessingConfiguration.bind(this._activeEffect);
  39808. }
  39809. }
  39810. this._uniformBuffer.update();
  39811. this._afterBind(mesh, this._activeEffect);
  39812. };
  39813. StandardMaterial.prototype.getAnimatables = function () {
  39814. var results = [];
  39815. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39816. results.push(this._diffuseTexture);
  39817. }
  39818. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39819. results.push(this._ambientTexture);
  39820. }
  39821. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39822. results.push(this._opacityTexture);
  39823. }
  39824. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39825. results.push(this._reflectionTexture);
  39826. }
  39827. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39828. results.push(this._emissiveTexture);
  39829. }
  39830. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39831. results.push(this._specularTexture);
  39832. }
  39833. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39834. results.push(this._bumpTexture);
  39835. }
  39836. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39837. results.push(this._lightmapTexture);
  39838. }
  39839. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39840. results.push(this._refractionTexture);
  39841. }
  39842. return results;
  39843. };
  39844. StandardMaterial.prototype.getActiveTextures = function () {
  39845. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39846. if (this._diffuseTexture) {
  39847. activeTextures.push(this._diffuseTexture);
  39848. }
  39849. if (this._ambientTexture) {
  39850. activeTextures.push(this._ambientTexture);
  39851. }
  39852. if (this._opacityTexture) {
  39853. activeTextures.push(this._opacityTexture);
  39854. }
  39855. if (this._reflectionTexture) {
  39856. activeTextures.push(this._reflectionTexture);
  39857. }
  39858. if (this._emissiveTexture) {
  39859. activeTextures.push(this._emissiveTexture);
  39860. }
  39861. if (this._specularTexture) {
  39862. activeTextures.push(this._specularTexture);
  39863. }
  39864. if (this._bumpTexture) {
  39865. activeTextures.push(this._bumpTexture);
  39866. }
  39867. if (this._lightmapTexture) {
  39868. activeTextures.push(this._lightmapTexture);
  39869. }
  39870. if (this._refractionTexture) {
  39871. activeTextures.push(this._refractionTexture);
  39872. }
  39873. return activeTextures;
  39874. };
  39875. StandardMaterial.prototype.hasTexture = function (texture) {
  39876. if (_super.prototype.hasTexture.call(this, texture)) {
  39877. return true;
  39878. }
  39879. if (this._diffuseTexture === texture) {
  39880. return true;
  39881. }
  39882. if (this._ambientTexture === texture) {
  39883. return true;
  39884. }
  39885. if (this._opacityTexture === texture) {
  39886. return true;
  39887. }
  39888. if (this._reflectionTexture === texture) {
  39889. return true;
  39890. }
  39891. if (this._emissiveTexture === texture) {
  39892. return true;
  39893. }
  39894. if (this._specularTexture === texture) {
  39895. return true;
  39896. }
  39897. if (this._bumpTexture === texture) {
  39898. return true;
  39899. }
  39900. if (this._lightmapTexture === texture) {
  39901. return true;
  39902. }
  39903. if (this._refractionTexture === texture) {
  39904. return true;
  39905. }
  39906. return false;
  39907. };
  39908. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39909. if (forceDisposeTextures) {
  39910. if (this._diffuseTexture) {
  39911. this._diffuseTexture.dispose();
  39912. }
  39913. if (this._ambientTexture) {
  39914. this._ambientTexture.dispose();
  39915. }
  39916. if (this._opacityTexture) {
  39917. this._opacityTexture.dispose();
  39918. }
  39919. if (this._reflectionTexture) {
  39920. this._reflectionTexture.dispose();
  39921. }
  39922. if (this._emissiveTexture) {
  39923. this._emissiveTexture.dispose();
  39924. }
  39925. if (this._specularTexture) {
  39926. this._specularTexture.dispose();
  39927. }
  39928. if (this._bumpTexture) {
  39929. this._bumpTexture.dispose();
  39930. }
  39931. if (this._lightmapTexture) {
  39932. this._lightmapTexture.dispose();
  39933. }
  39934. if (this._refractionTexture) {
  39935. this._refractionTexture.dispose();
  39936. }
  39937. }
  39938. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39939. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39940. }
  39941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39942. };
  39943. StandardMaterial.prototype.clone = function (name) {
  39944. var _this = this;
  39945. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39946. result.name = name;
  39947. result.id = name;
  39948. return result;
  39949. };
  39950. StandardMaterial.prototype.serialize = function () {
  39951. return BABYLON.SerializationHelper.Serialize(this);
  39952. };
  39953. // Statics
  39954. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39955. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39956. };
  39957. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39958. get: function () {
  39959. return StandardMaterial._DiffuseTextureEnabled;
  39960. },
  39961. set: function (value) {
  39962. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39963. return;
  39964. }
  39965. StandardMaterial._DiffuseTextureEnabled = value;
  39966. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39967. },
  39968. enumerable: true,
  39969. configurable: true
  39970. });
  39971. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39972. get: function () {
  39973. return StandardMaterial._AmbientTextureEnabled;
  39974. },
  39975. set: function (value) {
  39976. if (StandardMaterial._AmbientTextureEnabled === value) {
  39977. return;
  39978. }
  39979. StandardMaterial._AmbientTextureEnabled = value;
  39980. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39986. get: function () {
  39987. return StandardMaterial._OpacityTextureEnabled;
  39988. },
  39989. set: function (value) {
  39990. if (StandardMaterial._OpacityTextureEnabled === value) {
  39991. return;
  39992. }
  39993. StandardMaterial._OpacityTextureEnabled = value;
  39994. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39995. },
  39996. enumerable: true,
  39997. configurable: true
  39998. });
  39999. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40000. get: function () {
  40001. return StandardMaterial._ReflectionTextureEnabled;
  40002. },
  40003. set: function (value) {
  40004. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40005. return;
  40006. }
  40007. StandardMaterial._ReflectionTextureEnabled = value;
  40008. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40009. },
  40010. enumerable: true,
  40011. configurable: true
  40012. });
  40013. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40014. get: function () {
  40015. return StandardMaterial._EmissiveTextureEnabled;
  40016. },
  40017. set: function (value) {
  40018. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40019. return;
  40020. }
  40021. StandardMaterial._EmissiveTextureEnabled = value;
  40022. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40023. },
  40024. enumerable: true,
  40025. configurable: true
  40026. });
  40027. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40028. get: function () {
  40029. return StandardMaterial._SpecularTextureEnabled;
  40030. },
  40031. set: function (value) {
  40032. if (StandardMaterial._SpecularTextureEnabled === value) {
  40033. return;
  40034. }
  40035. StandardMaterial._SpecularTextureEnabled = value;
  40036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40037. },
  40038. enumerable: true,
  40039. configurable: true
  40040. });
  40041. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40042. get: function () {
  40043. return StandardMaterial._BumpTextureEnabled;
  40044. },
  40045. set: function (value) {
  40046. if (StandardMaterial._BumpTextureEnabled === value) {
  40047. return;
  40048. }
  40049. StandardMaterial._BumpTextureEnabled = value;
  40050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40051. },
  40052. enumerable: true,
  40053. configurable: true
  40054. });
  40055. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40056. get: function () {
  40057. return StandardMaterial._LightmapTextureEnabled;
  40058. },
  40059. set: function (value) {
  40060. if (StandardMaterial._LightmapTextureEnabled === value) {
  40061. return;
  40062. }
  40063. StandardMaterial._LightmapTextureEnabled = value;
  40064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40065. },
  40066. enumerable: true,
  40067. configurable: true
  40068. });
  40069. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40070. get: function () {
  40071. return StandardMaterial._RefractionTextureEnabled;
  40072. },
  40073. set: function (value) {
  40074. if (StandardMaterial._RefractionTextureEnabled === value) {
  40075. return;
  40076. }
  40077. StandardMaterial._RefractionTextureEnabled = value;
  40078. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40079. },
  40080. enumerable: true,
  40081. configurable: true
  40082. });
  40083. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40084. get: function () {
  40085. return StandardMaterial._ColorGradingTextureEnabled;
  40086. },
  40087. set: function (value) {
  40088. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40089. return;
  40090. }
  40091. StandardMaterial._ColorGradingTextureEnabled = value;
  40092. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40093. },
  40094. enumerable: true,
  40095. configurable: true
  40096. });
  40097. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40098. get: function () {
  40099. return StandardMaterial._FresnelEnabled;
  40100. },
  40101. set: function (value) {
  40102. if (StandardMaterial._FresnelEnabled === value) {
  40103. return;
  40104. }
  40105. StandardMaterial._FresnelEnabled = value;
  40106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40107. },
  40108. enumerable: true,
  40109. configurable: true
  40110. });
  40111. // Flags used to enable or disable a type of texture for all Standard Materials
  40112. StandardMaterial._DiffuseTextureEnabled = true;
  40113. StandardMaterial._AmbientTextureEnabled = true;
  40114. StandardMaterial._OpacityTextureEnabled = true;
  40115. StandardMaterial._ReflectionTextureEnabled = true;
  40116. StandardMaterial._EmissiveTextureEnabled = true;
  40117. StandardMaterial._SpecularTextureEnabled = true;
  40118. StandardMaterial._BumpTextureEnabled = true;
  40119. StandardMaterial._LightmapTextureEnabled = true;
  40120. StandardMaterial._RefractionTextureEnabled = true;
  40121. StandardMaterial._ColorGradingTextureEnabled = true;
  40122. StandardMaterial._FresnelEnabled = true;
  40123. __decorate([
  40124. BABYLON.serializeAsTexture("diffuseTexture")
  40125. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40126. __decorate([
  40127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40128. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40129. __decorate([
  40130. BABYLON.serializeAsTexture("ambientTexture")
  40131. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40132. __decorate([
  40133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40134. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40135. __decorate([
  40136. BABYLON.serializeAsTexture("opacityTexture")
  40137. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40138. __decorate([
  40139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40140. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40141. __decorate([
  40142. BABYLON.serializeAsTexture("reflectionTexture")
  40143. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40144. __decorate([
  40145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40146. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40147. __decorate([
  40148. BABYLON.serializeAsTexture("emissiveTexture")
  40149. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40150. __decorate([
  40151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40152. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40153. __decorate([
  40154. BABYLON.serializeAsTexture("specularTexture")
  40155. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40156. __decorate([
  40157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40158. ], StandardMaterial.prototype, "specularTexture", void 0);
  40159. __decorate([
  40160. BABYLON.serializeAsTexture("bumpTexture")
  40161. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40162. __decorate([
  40163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40164. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40165. __decorate([
  40166. BABYLON.serializeAsTexture("lightmapTexture")
  40167. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40168. __decorate([
  40169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40170. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40171. __decorate([
  40172. BABYLON.serializeAsTexture("refractionTexture")
  40173. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40174. __decorate([
  40175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40176. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40177. __decorate([
  40178. BABYLON.serializeAsColor3("ambient")
  40179. ], StandardMaterial.prototype, "ambientColor", void 0);
  40180. __decorate([
  40181. BABYLON.serializeAsColor3("diffuse")
  40182. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40183. __decorate([
  40184. BABYLON.serializeAsColor3("specular")
  40185. ], StandardMaterial.prototype, "specularColor", void 0);
  40186. __decorate([
  40187. BABYLON.serializeAsColor3("emissive")
  40188. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40189. __decorate([
  40190. BABYLON.serialize()
  40191. ], StandardMaterial.prototype, "specularPower", void 0);
  40192. __decorate([
  40193. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40194. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40195. __decorate([
  40196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40197. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40198. __decorate([
  40199. BABYLON.serialize("useEmissiveAsIllumination")
  40200. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40201. __decorate([
  40202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40203. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40204. __decorate([
  40205. BABYLON.serialize("linkEmissiveWithDiffuse")
  40206. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40207. __decorate([
  40208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40209. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40210. __decorate([
  40211. BABYLON.serialize("useSpecularOverAlpha")
  40212. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40213. __decorate([
  40214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40215. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40216. __decorate([
  40217. BABYLON.serialize("useReflectionOverAlpha")
  40218. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40219. __decorate([
  40220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40221. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40222. __decorate([
  40223. BABYLON.serialize("disableLighting")
  40224. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40225. __decorate([
  40226. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40227. ], StandardMaterial.prototype, "disableLighting", void 0);
  40228. __decorate([
  40229. BABYLON.serialize("useObjectSpaceNormalMap")
  40230. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40231. __decorate([
  40232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40233. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40234. __decorate([
  40235. BABYLON.serialize("useParallax")
  40236. ], StandardMaterial.prototype, "_useParallax", void 0);
  40237. __decorate([
  40238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40239. ], StandardMaterial.prototype, "useParallax", void 0);
  40240. __decorate([
  40241. BABYLON.serialize("useParallaxOcclusion")
  40242. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40243. __decorate([
  40244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40245. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40246. __decorate([
  40247. BABYLON.serialize()
  40248. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40249. __decorate([
  40250. BABYLON.serialize("roughness")
  40251. ], StandardMaterial.prototype, "_roughness", void 0);
  40252. __decorate([
  40253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40254. ], StandardMaterial.prototype, "roughness", void 0);
  40255. __decorate([
  40256. BABYLON.serialize()
  40257. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40258. __decorate([
  40259. BABYLON.serialize()
  40260. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40261. __decorate([
  40262. BABYLON.serialize("useLightmapAsShadowmap")
  40263. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40264. __decorate([
  40265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40266. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40267. __decorate([
  40268. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40269. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40270. __decorate([
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40272. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40273. __decorate([
  40274. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40275. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40276. __decorate([
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40278. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40279. __decorate([
  40280. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40281. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40282. __decorate([
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40284. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40285. __decorate([
  40286. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40287. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40288. __decorate([
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40290. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40291. __decorate([
  40292. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40293. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40294. __decorate([
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40296. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40297. __decorate([
  40298. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40299. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40300. __decorate([
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40302. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40303. __decorate([
  40304. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40305. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40306. __decorate([
  40307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40308. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40309. __decorate([
  40310. BABYLON.serialize("maxSimultaneousLights")
  40311. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40312. __decorate([
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40314. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40315. __decorate([
  40316. BABYLON.serialize("invertNormalMapX")
  40317. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40318. __decorate([
  40319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40320. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40321. __decorate([
  40322. BABYLON.serialize("invertNormalMapY")
  40323. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40324. __decorate([
  40325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40326. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40327. __decorate([
  40328. BABYLON.serialize("twoSidedLighting")
  40329. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40330. __decorate([
  40331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40332. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40333. __decorate([
  40334. BABYLON.serialize()
  40335. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40336. return StandardMaterial;
  40337. }(BABYLON.PushMaterial));
  40338. BABYLON.StandardMaterial = StandardMaterial;
  40339. })(BABYLON || (BABYLON = {}));
  40340. //# sourceMappingURL=babylon.standardMaterial.js.map
  40341. var BABYLON;
  40342. (function (BABYLON) {
  40343. /**
  40344. * Manages the defines for the PBR Material.
  40345. */
  40346. var PBRMaterialDefines = /** @class */ (function (_super) {
  40347. __extends(PBRMaterialDefines, _super);
  40348. /**
  40349. * Initializes the PBR Material defines.
  40350. */
  40351. function PBRMaterialDefines() {
  40352. var _this = _super.call(this) || this;
  40353. _this.PBR = true;
  40354. _this.MAINUV1 = false;
  40355. _this.MAINUV2 = false;
  40356. _this.UV1 = false;
  40357. _this.UV2 = false;
  40358. _this.ALBEDO = false;
  40359. _this.ALBEDODIRECTUV = 0;
  40360. _this.VERTEXCOLOR = false;
  40361. _this.AMBIENT = false;
  40362. _this.AMBIENTDIRECTUV = 0;
  40363. _this.AMBIENTINGRAYSCALE = false;
  40364. _this.OPACITY = false;
  40365. _this.VERTEXALPHA = false;
  40366. _this.OPACITYDIRECTUV = 0;
  40367. _this.OPACITYRGB = false;
  40368. _this.ALPHATEST = false;
  40369. _this.DEPTHPREPASS = false;
  40370. _this.ALPHABLEND = false;
  40371. _this.ALPHAFROMALBEDO = false;
  40372. _this.ALPHATESTVALUE = 0.5;
  40373. _this.SPECULAROVERALPHA = false;
  40374. _this.RADIANCEOVERALPHA = false;
  40375. _this.ALPHAFRESNEL = false;
  40376. _this.LINEARALPHAFRESNEL = false;
  40377. _this.PREMULTIPLYALPHA = false;
  40378. _this.EMISSIVE = false;
  40379. _this.EMISSIVEDIRECTUV = 0;
  40380. _this.REFLECTIVITY = false;
  40381. _this.REFLECTIVITYDIRECTUV = 0;
  40382. _this.SPECULARTERM = false;
  40383. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40384. _this.MICROSURFACEAUTOMATIC = false;
  40385. _this.LODBASEDMICROSFURACE = false;
  40386. _this.MICROSURFACEMAP = false;
  40387. _this.MICROSURFACEMAPDIRECTUV = 0;
  40388. _this.METALLICWORKFLOW = false;
  40389. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40390. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40391. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40392. _this.AOSTOREINMETALMAPRED = false;
  40393. _this.ENVIRONMENTBRDF = false;
  40394. _this.NORMAL = false;
  40395. _this.TANGENT = false;
  40396. _this.BUMP = false;
  40397. _this.BUMPDIRECTUV = 0;
  40398. _this.OBJECTSPACE_NORMALMAP = false;
  40399. _this.PARALLAX = false;
  40400. _this.PARALLAXOCCLUSION = false;
  40401. _this.NORMALXYSCALE = true;
  40402. _this.LIGHTMAP = false;
  40403. _this.LIGHTMAPDIRECTUV = 0;
  40404. _this.USELIGHTMAPASSHADOWMAP = false;
  40405. _this.REFLECTION = false;
  40406. _this.REFLECTIONMAP_3D = false;
  40407. _this.REFLECTIONMAP_SPHERICAL = false;
  40408. _this.REFLECTIONMAP_PLANAR = false;
  40409. _this.REFLECTIONMAP_CUBIC = false;
  40410. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40411. _this.REFLECTIONMAP_PROJECTION = false;
  40412. _this.REFLECTIONMAP_SKYBOX = false;
  40413. _this.REFLECTIONMAP_EXPLICIT = false;
  40414. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40415. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40416. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40417. _this.INVERTCUBICMAP = false;
  40418. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40419. _this.USESPHERICALINVERTEX = false;
  40420. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40421. _this.LODINREFLECTIONALPHA = false;
  40422. _this.GAMMAREFLECTION = false;
  40423. _this.RADIANCEOCCLUSION = false;
  40424. _this.HORIZONOCCLUSION = false;
  40425. _this.REFRACTION = false;
  40426. _this.REFRACTIONMAP_3D = false;
  40427. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40428. _this.LODINREFRACTIONALPHA = false;
  40429. _this.GAMMAREFRACTION = false;
  40430. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40431. _this.INSTANCES = false;
  40432. _this.NUM_BONE_INFLUENCERS = 0;
  40433. _this.BonesPerMesh = 0;
  40434. _this.NONUNIFORMSCALING = false;
  40435. _this.MORPHTARGETS = false;
  40436. _this.MORPHTARGETS_NORMAL = false;
  40437. _this.MORPHTARGETS_TANGENT = false;
  40438. _this.NUM_MORPH_INFLUENCERS = 0;
  40439. _this.IMAGEPROCESSING = false;
  40440. _this.VIGNETTE = false;
  40441. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40442. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40443. _this.TONEMAPPING = false;
  40444. _this.CONTRAST = false;
  40445. _this.COLORCURVES = false;
  40446. _this.COLORGRADING = false;
  40447. _this.COLORGRADING3D = false;
  40448. _this.SAMPLER3DGREENDEPTH = false;
  40449. _this.SAMPLER3DBGRMAP = false;
  40450. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40451. _this.EXPOSURE = false;
  40452. _this.GRAIN = false;
  40453. _this.USEPHYSICALLIGHTFALLOFF = false;
  40454. _this.TWOSIDEDLIGHTING = false;
  40455. _this.SHADOWFLOAT = false;
  40456. _this.CLIPPLANE = false;
  40457. _this.POINTSIZE = false;
  40458. _this.FOG = false;
  40459. _this.LOGARITHMICDEPTH = false;
  40460. _this.FORCENORMALFORWARD = false;
  40461. _this.rebuild();
  40462. return _this;
  40463. }
  40464. /**
  40465. * Resets the PBR Material defines.
  40466. */
  40467. PBRMaterialDefines.prototype.reset = function () {
  40468. _super.prototype.reset.call(this);
  40469. this.ALPHATESTVALUE = 0.5;
  40470. this.PBR = true;
  40471. };
  40472. return PBRMaterialDefines;
  40473. }(BABYLON.MaterialDefines));
  40474. /**
  40475. * The Physically based material base class of BJS.
  40476. *
  40477. * This offers the main features of a standard PBR material.
  40478. * For more information, please refer to the documentation :
  40479. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40480. */
  40481. var PBRBaseMaterial = /** @class */ (function (_super) {
  40482. __extends(PBRBaseMaterial, _super);
  40483. /**
  40484. * Instantiates a new PBRMaterial instance.
  40485. *
  40486. * @param name The material name
  40487. * @param scene The scene the material will be use in.
  40488. */
  40489. function PBRBaseMaterial(name, scene) {
  40490. var _this = _super.call(this, name, scene) || this;
  40491. /**
  40492. * Intensity of the direct lights e.g. the four lights available in your scene.
  40493. * This impacts both the direct diffuse and specular highlights.
  40494. */
  40495. _this._directIntensity = 1.0;
  40496. /**
  40497. * Intensity of the emissive part of the material.
  40498. * This helps controlling the emissive effect without modifying the emissive color.
  40499. */
  40500. _this._emissiveIntensity = 1.0;
  40501. /**
  40502. * Intensity of the environment e.g. how much the environment will light the object
  40503. * either through harmonics for rough material or through the refelction for shiny ones.
  40504. */
  40505. _this._environmentIntensity = 1.0;
  40506. /**
  40507. * This is a special control allowing the reduction of the specular highlights coming from the
  40508. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40509. */
  40510. _this._specularIntensity = 1.0;
  40511. /**
  40512. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40513. */
  40514. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40515. /**
  40516. * Debug Control allowing disabling the bump map on this material.
  40517. */
  40518. _this._disableBumpMap = false;
  40519. /**
  40520. * AKA Occlusion Texture Intensity in other nomenclature.
  40521. */
  40522. _this._ambientTextureStrength = 1.0;
  40523. /**
  40524. * The color of a material in ambient lighting.
  40525. */
  40526. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40527. /**
  40528. * AKA Diffuse Color in other nomenclature.
  40529. */
  40530. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40531. /**
  40532. * AKA Specular Color in other nomenclature.
  40533. */
  40534. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40535. /**
  40536. * The color applied when light is reflected from a material.
  40537. */
  40538. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40539. /**
  40540. * The color applied when light is emitted from a material.
  40541. */
  40542. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40543. /**
  40544. * AKA Glossiness in other nomenclature.
  40545. */
  40546. _this._microSurface = 0.9;
  40547. /**
  40548. * source material index of refraction (IOR)' / 'destination material IOR.
  40549. */
  40550. _this._indexOfRefraction = 0.66;
  40551. /**
  40552. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40553. */
  40554. _this._invertRefractionY = false;
  40555. /**
  40556. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40557. * Materials half opaque for instance using refraction could benefit from this control.
  40558. */
  40559. _this._linkRefractionWithTransparency = false;
  40560. /**
  40561. * Specifies that the material will use the light map as a show map.
  40562. */
  40563. _this._useLightmapAsShadowmap = false;
  40564. /**
  40565. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40566. * makes the reflect vector face the model (under horizon).
  40567. */
  40568. _this._useHorizonOcclusion = true;
  40569. /**
  40570. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40571. * too much the area relying on ambient texture to define their ambient occlusion.
  40572. */
  40573. _this._useRadianceOcclusion = true;
  40574. /**
  40575. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40576. */
  40577. _this._useAlphaFromAlbedoTexture = false;
  40578. /**
  40579. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40580. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40581. */
  40582. _this._useSpecularOverAlpha = true;
  40583. /**
  40584. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40585. */
  40586. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40587. /**
  40588. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40589. */
  40590. _this._useRoughnessFromMetallicTextureAlpha = true;
  40591. /**
  40592. * Specifies if the metallic texture contains the roughness information in its green channel.
  40593. */
  40594. _this._useRoughnessFromMetallicTextureGreen = false;
  40595. /**
  40596. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40597. */
  40598. _this._useMetallnessFromMetallicTextureBlue = false;
  40599. /**
  40600. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40601. */
  40602. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40603. /**
  40604. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40605. */
  40606. _this._useAmbientInGrayScale = false;
  40607. /**
  40608. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40609. * The material will try to infer what glossiness each pixel should be.
  40610. */
  40611. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40612. /**
  40613. * BJS is using an harcoded light falloff based on a manually sets up range.
  40614. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40615. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40616. */
  40617. _this._usePhysicalLightFalloff = true;
  40618. /**
  40619. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40620. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40621. */
  40622. _this._useRadianceOverAlpha = true;
  40623. /**
  40624. * Allows using an object space normal map (instead of tangent space).
  40625. */
  40626. _this._useObjectSpaceNormalMap = false;
  40627. /**
  40628. * Allows using the bump map in parallax mode.
  40629. */
  40630. _this._useParallax = false;
  40631. /**
  40632. * Allows using the bump map in parallax occlusion mode.
  40633. */
  40634. _this._useParallaxOcclusion = false;
  40635. /**
  40636. * Controls the scale bias of the parallax mode.
  40637. */
  40638. _this._parallaxScaleBias = 0.05;
  40639. /**
  40640. * If sets to true, disables all the lights affecting the material.
  40641. */
  40642. _this._disableLighting = false;
  40643. /**
  40644. * Number of Simultaneous lights allowed on the material.
  40645. */
  40646. _this._maxSimultaneousLights = 4;
  40647. /**
  40648. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40649. */
  40650. _this._invertNormalMapX = false;
  40651. /**
  40652. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40653. */
  40654. _this._invertNormalMapY = false;
  40655. /**
  40656. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40657. */
  40658. _this._twoSidedLighting = false;
  40659. /**
  40660. * Defines the alpha limits in alpha test mode.
  40661. */
  40662. _this._alphaCutOff = 0.4;
  40663. /**
  40664. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40665. */
  40666. _this._forceAlphaTest = false;
  40667. /**
  40668. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40669. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40670. */
  40671. _this._useAlphaFresnel = false;
  40672. /**
  40673. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40674. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40675. */
  40676. _this._useLinearAlphaFresnel = false;
  40677. /**
  40678. * The transparency mode of the material.
  40679. */
  40680. _this._transparencyMode = null;
  40681. /**
  40682. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40683. * from cos thetav and roughness:
  40684. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40685. */
  40686. _this._environmentBRDFTexture = null;
  40687. /**
  40688. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40689. */
  40690. _this._forceIrradianceInFragment = false;
  40691. /**
  40692. * Force normal to face away from face.
  40693. */
  40694. _this._forceNormalForward = false;
  40695. /**
  40696. * Stores the available render targets.
  40697. */
  40698. _this._renderTargets = new BABYLON.SmartArray(16);
  40699. /**
  40700. * Sets the global ambient color for the material used in lighting calculations.
  40701. */
  40702. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40703. // Setup the default processing configuration to the scene.
  40704. _this._attachImageProcessingConfiguration(null);
  40705. _this.getRenderTargetTextures = function () {
  40706. _this._renderTargets.reset();
  40707. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40708. _this._renderTargets.push(_this._reflectionTexture);
  40709. }
  40710. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40711. _this._renderTargets.push(_this._refractionTexture);
  40712. }
  40713. return _this._renderTargets;
  40714. };
  40715. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40716. return _this;
  40717. }
  40718. /**
  40719. * Attaches a new image processing configuration to the PBR Material.
  40720. * @param configuration
  40721. */
  40722. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40723. var _this = this;
  40724. if (configuration === this._imageProcessingConfiguration) {
  40725. return;
  40726. }
  40727. // Detaches observer.
  40728. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40729. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40730. }
  40731. // Pick the scene configuration if needed.
  40732. if (!configuration) {
  40733. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40734. }
  40735. else {
  40736. this._imageProcessingConfiguration = configuration;
  40737. }
  40738. // Attaches observer.
  40739. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40740. _this._markAllSubMeshesAsImageProcessingDirty();
  40741. });
  40742. };
  40743. /**
  40744. * Gets the name of the material class.
  40745. */
  40746. PBRBaseMaterial.prototype.getClassName = function () {
  40747. return "PBRBaseMaterial";
  40748. };
  40749. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40750. /**
  40751. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40752. */
  40753. get: function () {
  40754. return this._useLogarithmicDepth;
  40755. },
  40756. /**
  40757. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40758. */
  40759. set: function (value) {
  40760. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40761. },
  40762. enumerable: true,
  40763. configurable: true
  40764. });
  40765. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40766. /**
  40767. * Gets the current transparency mode.
  40768. */
  40769. get: function () {
  40770. return this._transparencyMode;
  40771. },
  40772. /**
  40773. * Sets the transparency mode of the material.
  40774. */
  40775. set: function (value) {
  40776. if (this._transparencyMode === value) {
  40777. return;
  40778. }
  40779. this._transparencyMode = value;
  40780. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40781. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40782. },
  40783. enumerable: true,
  40784. configurable: true
  40785. });
  40786. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40787. /**
  40788. * Returns true if alpha blending should be disabled.
  40789. */
  40790. get: function () {
  40791. return (this._linkRefractionWithTransparency ||
  40792. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40793. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40794. },
  40795. enumerable: true,
  40796. configurable: true
  40797. });
  40798. /**
  40799. * Specifies whether or not this material should be rendered in alpha blend mode.
  40800. */
  40801. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40802. if (this._disableAlphaBlending) {
  40803. return false;
  40804. }
  40805. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40806. };
  40807. /**
  40808. * Specifies if the mesh will require alpha blending.
  40809. * @param mesh - BJS mesh.
  40810. */
  40811. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40812. if (this._disableAlphaBlending) {
  40813. return false;
  40814. }
  40815. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40816. };
  40817. /**
  40818. * Specifies whether or not this material should be rendered in alpha test mode.
  40819. */
  40820. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40821. if (this._forceAlphaTest) {
  40822. return true;
  40823. }
  40824. if (this._linkRefractionWithTransparency) {
  40825. return false;
  40826. }
  40827. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40828. };
  40829. /**
  40830. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40831. */
  40832. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40833. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40834. };
  40835. /**
  40836. * Gets the texture used for the alpha test.
  40837. */
  40838. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40839. return this._albedoTexture;
  40840. };
  40841. /**
  40842. * Specifies that the submesh is ready to be used.
  40843. * @param mesh - BJS mesh.
  40844. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40845. * @param useInstances - Specifies that instances should be used.
  40846. * @returns - boolean indicating that the submesh is ready or not.
  40847. */
  40848. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40849. if (subMesh.effect && this.isFrozen) {
  40850. if (this._wasPreviouslyReady) {
  40851. return true;
  40852. }
  40853. }
  40854. if (!subMesh._materialDefines) {
  40855. subMesh._materialDefines = new PBRMaterialDefines();
  40856. }
  40857. var defines = subMesh._materialDefines;
  40858. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40859. if (defines._renderId === this.getScene().getRenderId()) {
  40860. return true;
  40861. }
  40862. }
  40863. var scene = this.getScene();
  40864. var engine = scene.getEngine();
  40865. if (defines._areTexturesDirty) {
  40866. if (scene.texturesEnabled) {
  40867. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40868. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40869. return false;
  40870. }
  40871. }
  40872. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40873. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40874. return false;
  40875. }
  40876. }
  40877. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40878. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40879. return false;
  40880. }
  40881. }
  40882. var reflectionTexture = this._getReflectionTexture();
  40883. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40884. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40885. return false;
  40886. }
  40887. }
  40888. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40889. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40890. return false;
  40891. }
  40892. }
  40893. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40894. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40895. return false;
  40896. }
  40897. }
  40898. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40899. if (this._metallicTexture) {
  40900. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40901. return false;
  40902. }
  40903. }
  40904. else if (this._reflectivityTexture) {
  40905. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40906. return false;
  40907. }
  40908. }
  40909. if (this._microSurfaceTexture) {
  40910. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40911. return false;
  40912. }
  40913. }
  40914. }
  40915. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40916. // Bump texture cannot be not blocking.
  40917. if (!this._bumpTexture.isReady()) {
  40918. return false;
  40919. }
  40920. }
  40921. var refractionTexture = this._getRefractionTexture();
  40922. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40923. if (!refractionTexture.isReadyOrNotBlocking()) {
  40924. return false;
  40925. }
  40926. }
  40927. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40928. // This is blocking.
  40929. if (!this._environmentBRDFTexture.isReady()) {
  40930. return false;
  40931. }
  40932. }
  40933. }
  40934. }
  40935. if (defines._areImageProcessingDirty) {
  40936. if (!this._imageProcessingConfiguration.isReady()) {
  40937. return false;
  40938. }
  40939. }
  40940. if (!engine.getCaps().standardDerivatives) {
  40941. var bufferMesh = null;
  40942. if (mesh.getClassName() === "InstancedMesh") {
  40943. bufferMesh = mesh.sourceMesh;
  40944. }
  40945. else if (mesh.getClassName() === "Mesh") {
  40946. bufferMesh = mesh;
  40947. }
  40948. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40949. bufferMesh.createNormals(true);
  40950. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40951. }
  40952. }
  40953. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40954. if (effect) {
  40955. scene.resetCachedMaterial();
  40956. subMesh.setEffect(effect, defines);
  40957. this.buildUniformLayout();
  40958. }
  40959. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40960. return false;
  40961. }
  40962. defines._renderId = scene.getRenderId();
  40963. this._wasPreviouslyReady = true;
  40964. return true;
  40965. };
  40966. /**
  40967. * Specifies if the material uses metallic roughness workflow.
  40968. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40969. */
  40970. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40971. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40972. return true;
  40973. }
  40974. return false;
  40975. };
  40976. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40977. if (onCompiled === void 0) { onCompiled = null; }
  40978. if (onError === void 0) { onError = null; }
  40979. if (useInstances === void 0) { useInstances = null; }
  40980. if (useClipPlane === void 0) { useClipPlane = null; }
  40981. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40982. if (!defines.isDirty) {
  40983. return null;
  40984. }
  40985. defines.markAsProcessed();
  40986. var scene = this.getScene();
  40987. var engine = scene.getEngine();
  40988. // Fallbacks
  40989. var fallbacks = new BABYLON.EffectFallbacks();
  40990. var fallbackRank = 0;
  40991. if (defines.USESPHERICALINVERTEX) {
  40992. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40993. }
  40994. if (defines.FOG) {
  40995. fallbacks.addFallback(fallbackRank, "FOG");
  40996. }
  40997. if (defines.POINTSIZE) {
  40998. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40999. }
  41000. if (defines.LOGARITHMICDEPTH) {
  41001. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41002. }
  41003. if (defines.PARALLAX) {
  41004. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41005. }
  41006. if (defines.PARALLAXOCCLUSION) {
  41007. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41008. }
  41009. if (defines.ENVIRONMENTBRDF) {
  41010. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41011. }
  41012. if (defines.TANGENT) {
  41013. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41014. }
  41015. if (defines.BUMP) {
  41016. fallbacks.addFallback(fallbackRank++, "BUMP");
  41017. }
  41018. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41019. if (defines.SPECULARTERM) {
  41020. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41021. }
  41022. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41023. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41024. }
  41025. if (defines.LIGHTMAP) {
  41026. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41027. }
  41028. if (defines.NORMAL) {
  41029. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41030. }
  41031. if (defines.AMBIENT) {
  41032. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41033. }
  41034. if (defines.EMISSIVE) {
  41035. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41036. }
  41037. if (defines.VERTEXCOLOR) {
  41038. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41039. }
  41040. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41041. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41042. }
  41043. if (defines.MORPHTARGETS) {
  41044. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41045. }
  41046. //Attributes
  41047. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41048. if (defines.NORMAL) {
  41049. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41050. }
  41051. if (defines.TANGENT) {
  41052. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41053. }
  41054. if (defines.UV1) {
  41055. attribs.push(BABYLON.VertexBuffer.UVKind);
  41056. }
  41057. if (defines.UV2) {
  41058. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41059. }
  41060. if (defines.VERTEXCOLOR) {
  41061. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41062. }
  41063. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41064. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41065. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41066. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41067. "vFogInfos", "vFogColor", "pointSize",
  41068. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41069. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41070. "mBones",
  41071. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41072. "vLightingIntensity",
  41073. "logarithmicDepthConstant",
  41074. "vSphericalX", "vSphericalY", "vSphericalZ",
  41075. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41076. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41077. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41078. "vTangentSpaceParams"
  41079. ];
  41080. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41081. "bumpSampler", "lightmapSampler", "opacitySampler",
  41082. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41083. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41084. "microSurfaceSampler", "environmentBrdfSampler"];
  41085. var uniformBuffers = ["Material", "Scene"];
  41086. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41087. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41088. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41089. uniformsNames: uniforms,
  41090. uniformBuffersNames: uniformBuffers,
  41091. samplers: samplers,
  41092. defines: defines,
  41093. maxSimultaneousLights: this._maxSimultaneousLights
  41094. });
  41095. var join = defines.toString();
  41096. return engine.createEffect("pbr", {
  41097. attributes: attribs,
  41098. uniformsNames: uniforms,
  41099. uniformBuffersNames: uniformBuffers,
  41100. samplers: samplers,
  41101. defines: join,
  41102. fallbacks: fallbacks,
  41103. onCompiled: onCompiled,
  41104. onError: onError,
  41105. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41106. }, engine);
  41107. };
  41108. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41109. if (useInstances === void 0) { useInstances = null; }
  41110. if (useClipPlane === void 0) { useClipPlane = null; }
  41111. var scene = this.getScene();
  41112. var engine = scene.getEngine();
  41113. // Lights
  41114. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41115. defines._needNormals = true;
  41116. // Textures
  41117. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41118. if (defines._areTexturesDirty) {
  41119. defines._needUVs = false;
  41120. if (scene.texturesEnabled) {
  41121. if (scene.getEngine().getCaps().textureLOD) {
  41122. defines.LODBASEDMICROSFURACE = true;
  41123. }
  41124. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41125. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41126. }
  41127. else {
  41128. defines.ALBEDO = false;
  41129. }
  41130. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41131. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41132. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41133. }
  41134. else {
  41135. defines.AMBIENT = false;
  41136. }
  41137. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41138. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41139. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41140. }
  41141. else {
  41142. defines.OPACITY = false;
  41143. }
  41144. var reflectionTexture = this._getReflectionTexture();
  41145. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41146. defines.REFLECTION = true;
  41147. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41148. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41149. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41150. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41151. defines.INVERTCUBICMAP = true;
  41152. }
  41153. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41154. switch (reflectionTexture.coordinatesMode) {
  41155. case BABYLON.Texture.CUBIC_MODE:
  41156. case BABYLON.Texture.INVCUBIC_MODE:
  41157. defines.REFLECTIONMAP_CUBIC = true;
  41158. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41159. break;
  41160. case BABYLON.Texture.EXPLICIT_MODE:
  41161. defines.REFLECTIONMAP_EXPLICIT = true;
  41162. break;
  41163. case BABYLON.Texture.PLANAR_MODE:
  41164. defines.REFLECTIONMAP_PLANAR = true;
  41165. break;
  41166. case BABYLON.Texture.PROJECTION_MODE:
  41167. defines.REFLECTIONMAP_PROJECTION = true;
  41168. break;
  41169. case BABYLON.Texture.SKYBOX_MODE:
  41170. defines.REFLECTIONMAP_SKYBOX = true;
  41171. break;
  41172. case BABYLON.Texture.SPHERICAL_MODE:
  41173. defines.REFLECTIONMAP_SPHERICAL = true;
  41174. break;
  41175. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41176. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41177. break;
  41178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41179. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41180. break;
  41181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41182. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41183. break;
  41184. }
  41185. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41186. if (reflectionTexture.sphericalPolynomial) {
  41187. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41188. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41189. defines.USESPHERICALINVERTEX = false;
  41190. }
  41191. else {
  41192. defines.USESPHERICALINVERTEX = true;
  41193. }
  41194. }
  41195. }
  41196. }
  41197. else {
  41198. defines.REFLECTION = false;
  41199. defines.REFLECTIONMAP_3D = false;
  41200. defines.REFLECTIONMAP_SPHERICAL = false;
  41201. defines.REFLECTIONMAP_PLANAR = false;
  41202. defines.REFLECTIONMAP_CUBIC = false;
  41203. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41204. defines.REFLECTIONMAP_PROJECTION = false;
  41205. defines.REFLECTIONMAP_SKYBOX = false;
  41206. defines.REFLECTIONMAP_EXPLICIT = false;
  41207. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41208. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41209. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41210. defines.INVERTCUBICMAP = false;
  41211. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41212. defines.USESPHERICALINVERTEX = false;
  41213. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41214. defines.LODINREFLECTIONALPHA = false;
  41215. defines.GAMMAREFLECTION = false;
  41216. }
  41217. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41219. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41220. }
  41221. else {
  41222. defines.LIGHTMAP = false;
  41223. }
  41224. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41226. }
  41227. else {
  41228. defines.EMISSIVE = false;
  41229. }
  41230. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41231. if (this._metallicTexture) {
  41232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41233. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41234. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41235. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41236. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41237. }
  41238. else if (this._reflectivityTexture) {
  41239. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41240. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41241. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41242. }
  41243. else {
  41244. defines.REFLECTIVITY = false;
  41245. }
  41246. if (this._microSurfaceTexture) {
  41247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41248. }
  41249. else {
  41250. defines.MICROSURFACEMAP = false;
  41251. }
  41252. }
  41253. else {
  41254. defines.REFLECTIVITY = false;
  41255. defines.MICROSURFACEMAP = false;
  41256. }
  41257. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41259. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41260. defines.PARALLAX = true;
  41261. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41262. }
  41263. else {
  41264. defines.PARALLAX = false;
  41265. }
  41266. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41267. }
  41268. else {
  41269. defines.BUMP = false;
  41270. }
  41271. var refractionTexture = this._getRefractionTexture();
  41272. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41273. defines.REFRACTION = true;
  41274. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41275. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41276. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41277. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41278. if (this._linkRefractionWithTransparency) {
  41279. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41280. }
  41281. }
  41282. else {
  41283. defines.REFRACTION = false;
  41284. }
  41285. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41286. defines.ENVIRONMENTBRDF = true;
  41287. }
  41288. else {
  41289. defines.ENVIRONMENTBRDF = false;
  41290. }
  41291. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41292. defines.ALPHAFROMALBEDO = true;
  41293. }
  41294. else {
  41295. defines.ALPHAFROMALBEDO = false;
  41296. }
  41297. }
  41298. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41299. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41300. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41301. if (!this.backFaceCulling && this._twoSidedLighting) {
  41302. defines.TWOSIDEDLIGHTING = true;
  41303. }
  41304. else {
  41305. defines.TWOSIDEDLIGHTING = false;
  41306. }
  41307. defines.ALPHATESTVALUE = this._alphaCutOff;
  41308. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41309. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41310. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41311. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41312. }
  41313. if (defines._areImageProcessingDirty) {
  41314. this._imageProcessingConfiguration.prepareDefines(defines);
  41315. }
  41316. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41317. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41318. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41319. // Misc.
  41320. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41321. // Values that need to be evaluated on every frame
  41322. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41323. // Attribs
  41324. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41325. };
  41326. /**
  41327. * Force shader compilation
  41328. */
  41329. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41330. var _this = this;
  41331. var localOptions = __assign({ clipPlane: false }, options);
  41332. var defines = new PBRMaterialDefines();
  41333. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41334. if (effect.isReady()) {
  41335. if (onCompiled) {
  41336. onCompiled(this);
  41337. }
  41338. }
  41339. else {
  41340. effect.onCompileObservable.add(function () {
  41341. if (onCompiled) {
  41342. onCompiled(_this);
  41343. }
  41344. });
  41345. }
  41346. };
  41347. /**
  41348. * Initializes the uniform buffer layout for the shader.
  41349. */
  41350. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41351. // Order is important !
  41352. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41353. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41354. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41355. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41356. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41357. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41358. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41359. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41360. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41361. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41362. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41363. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41364. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41365. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41366. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41367. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41368. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41369. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41370. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41371. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41372. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41373. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41374. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41375. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41376. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41377. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41378. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41379. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41380. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41381. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41382. this._uniformBuffer.addUniform("pointSize", 1);
  41383. this._uniformBuffer.create();
  41384. };
  41385. /**
  41386. * Unbinds the textures.
  41387. */
  41388. PBRBaseMaterial.prototype.unbind = function () {
  41389. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41390. this._uniformBuffer.setTexture("reflectionSampler", null);
  41391. }
  41392. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41393. this._uniformBuffer.setTexture("refractionSampler", null);
  41394. }
  41395. _super.prototype.unbind.call(this);
  41396. };
  41397. /**
  41398. * Binds the submesh data.
  41399. * @param world - The world matrix.
  41400. * @param mesh - The BJS mesh.
  41401. * @param subMesh - A submesh of the BJS mesh.
  41402. */
  41403. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41404. var scene = this.getScene();
  41405. var defines = subMesh._materialDefines;
  41406. if (!defines) {
  41407. return;
  41408. }
  41409. var effect = subMesh.effect;
  41410. if (!effect) {
  41411. return;
  41412. }
  41413. this._activeEffect = effect;
  41414. // Matrices
  41415. this.bindOnlyWorldMatrix(world);
  41416. // Normal Matrix
  41417. if (defines.OBJECTSPACE_NORMALMAP) {
  41418. world.toNormalMatrix(this._normalMatrix);
  41419. this.bindOnlyNormalMatrix(this._normalMatrix);
  41420. }
  41421. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41422. // Bones
  41423. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41424. var reflectionTexture = null;
  41425. if (mustRebind) {
  41426. this._uniformBuffer.bindToEffect(effect, "Material");
  41427. this.bindViewProjection(effect);
  41428. reflectionTexture = this._getReflectionTexture();
  41429. var refractionTexture = this._getRefractionTexture();
  41430. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41431. // Texture uniforms
  41432. if (scene.texturesEnabled) {
  41433. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41434. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41435. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41436. }
  41437. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41438. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41439. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41440. }
  41441. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41442. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41443. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41444. }
  41445. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41446. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41447. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41448. if (reflectionTexture.boundingBoxSize) {
  41449. var cubeTexture = reflectionTexture;
  41450. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41451. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41452. }
  41453. var polynomials = reflectionTexture.sphericalPolynomial;
  41454. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41455. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41456. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41457. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41458. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41459. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41460. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41461. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41462. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41463. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41464. }
  41465. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41466. }
  41467. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41468. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41469. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41470. }
  41471. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41472. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41473. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41474. }
  41475. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41476. if (this._metallicTexture) {
  41477. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41478. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41479. }
  41480. else if (this._reflectivityTexture) {
  41481. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41482. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41483. }
  41484. if (this._microSurfaceTexture) {
  41485. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41486. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41487. }
  41488. }
  41489. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41490. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41491. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41492. if (scene._mirroredCameraPosition) {
  41493. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41494. }
  41495. else {
  41496. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41497. }
  41498. }
  41499. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41500. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41501. var depth = 1.0;
  41502. if (!refractionTexture.isCube) {
  41503. if (refractionTexture.depth) {
  41504. depth = refractionTexture.depth;
  41505. }
  41506. }
  41507. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41508. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41509. }
  41510. }
  41511. // Point size
  41512. if (this.pointsCloud) {
  41513. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41514. }
  41515. // Colors
  41516. if (defines.METALLICWORKFLOW) {
  41517. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41518. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41519. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41520. }
  41521. else {
  41522. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41523. }
  41524. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41525. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41526. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41527. // Misc
  41528. this._lightingInfos.x = this._directIntensity;
  41529. this._lightingInfos.y = this._emissiveIntensity;
  41530. this._lightingInfos.z = this._environmentIntensity;
  41531. this._lightingInfos.w = this._specularIntensity;
  41532. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41533. }
  41534. // Textures
  41535. if (scene.texturesEnabled) {
  41536. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41537. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41538. }
  41539. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41540. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41541. }
  41542. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41543. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41544. }
  41545. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41546. if (defines.LODBASEDMICROSFURACE) {
  41547. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41548. }
  41549. else {
  41550. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41551. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41552. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41553. }
  41554. }
  41555. if (defines.ENVIRONMENTBRDF) {
  41556. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41557. }
  41558. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41559. if (defines.LODBASEDMICROSFURACE) {
  41560. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41561. }
  41562. else {
  41563. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41564. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41565. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41566. }
  41567. }
  41568. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41569. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41570. }
  41571. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41572. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41573. }
  41574. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41575. if (this._metallicTexture) {
  41576. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41577. }
  41578. else if (this._reflectivityTexture) {
  41579. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41580. }
  41581. if (this._microSurfaceTexture) {
  41582. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41583. }
  41584. }
  41585. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41586. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41587. }
  41588. }
  41589. // Clip plane
  41590. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41591. // Colors
  41592. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41593. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41594. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41595. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41596. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41597. }
  41598. if (mustRebind || !this.isFrozen) {
  41599. // Lights
  41600. if (scene.lightsEnabled && !this._disableLighting) {
  41601. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41602. }
  41603. // View
  41604. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41605. this.bindView(effect);
  41606. }
  41607. // Fog
  41608. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41609. // Morph targets
  41610. if (defines.NUM_MORPH_INFLUENCERS) {
  41611. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41612. }
  41613. // image processing
  41614. this._imageProcessingConfiguration.bind(this._activeEffect);
  41615. // Log. depth
  41616. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41617. }
  41618. this._uniformBuffer.update();
  41619. this._afterBind(mesh);
  41620. };
  41621. /**
  41622. * Returns the animatable textures.
  41623. * @returns - Array of animatable textures.
  41624. */
  41625. PBRBaseMaterial.prototype.getAnimatables = function () {
  41626. var results = [];
  41627. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41628. results.push(this._albedoTexture);
  41629. }
  41630. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41631. results.push(this._ambientTexture);
  41632. }
  41633. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41634. results.push(this._opacityTexture);
  41635. }
  41636. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41637. results.push(this._reflectionTexture);
  41638. }
  41639. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41640. results.push(this._emissiveTexture);
  41641. }
  41642. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41643. results.push(this._metallicTexture);
  41644. }
  41645. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41646. results.push(this._reflectivityTexture);
  41647. }
  41648. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41649. results.push(this._bumpTexture);
  41650. }
  41651. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41652. results.push(this._lightmapTexture);
  41653. }
  41654. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41655. results.push(this._refractionTexture);
  41656. }
  41657. return results;
  41658. };
  41659. /**
  41660. * Returns the texture used for reflections.
  41661. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41662. */
  41663. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41664. if (this._reflectionTexture) {
  41665. return this._reflectionTexture;
  41666. }
  41667. return this.getScene().environmentTexture;
  41668. };
  41669. /**
  41670. * Returns the texture used for refraction or null if none is used.
  41671. * @returns - Refection texture if present. If no refraction texture and refraction
  41672. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41673. */
  41674. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41675. if (this._refractionTexture) {
  41676. return this._refractionTexture;
  41677. }
  41678. if (this._linkRefractionWithTransparency) {
  41679. return this.getScene().environmentTexture;
  41680. }
  41681. return null;
  41682. };
  41683. /**
  41684. * Disposes the resources of the material.
  41685. * @param forceDisposeEffect - Forces the disposal of effects.
  41686. * @param forceDisposeTextures - Forces the disposal of all textures.
  41687. */
  41688. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41689. if (forceDisposeTextures) {
  41690. if (this._albedoTexture) {
  41691. this._albedoTexture.dispose();
  41692. }
  41693. if (this._ambientTexture) {
  41694. this._ambientTexture.dispose();
  41695. }
  41696. if (this._opacityTexture) {
  41697. this._opacityTexture.dispose();
  41698. }
  41699. if (this._reflectionTexture) {
  41700. this._reflectionTexture.dispose();
  41701. }
  41702. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41703. this._environmentBRDFTexture.dispose();
  41704. }
  41705. if (this._emissiveTexture) {
  41706. this._emissiveTexture.dispose();
  41707. }
  41708. if (this._metallicTexture) {
  41709. this._metallicTexture.dispose();
  41710. }
  41711. if (this._reflectivityTexture) {
  41712. this._reflectivityTexture.dispose();
  41713. }
  41714. if (this._bumpTexture) {
  41715. this._bumpTexture.dispose();
  41716. }
  41717. if (this._lightmapTexture) {
  41718. this._lightmapTexture.dispose();
  41719. }
  41720. if (this._refractionTexture) {
  41721. this._refractionTexture.dispose();
  41722. }
  41723. }
  41724. this._renderTargets.dispose();
  41725. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41726. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41727. }
  41728. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41729. };
  41730. /**
  41731. * Stores the reflectivity values based on metallic roughness workflow.
  41732. */
  41733. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41734. __decorate([
  41735. BABYLON.serializeAsImageProcessingConfiguration()
  41736. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41737. __decorate([
  41738. BABYLON.serialize()
  41739. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41740. __decorate([
  41741. BABYLON.serialize()
  41742. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41743. return PBRBaseMaterial;
  41744. }(BABYLON.PushMaterial));
  41745. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41746. })(BABYLON || (BABYLON = {}));
  41747. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41748. var BABYLON;
  41749. (function (BABYLON) {
  41750. /**
  41751. * The Physically based simple base material of BJS.
  41752. *
  41753. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41754. * It is used as the base class for both the specGloss and metalRough conventions.
  41755. */
  41756. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41757. __extends(PBRBaseSimpleMaterial, _super);
  41758. /**
  41759. * Instantiates a new PBRMaterial instance.
  41760. *
  41761. * @param name The material name
  41762. * @param scene The scene the material will be use in.
  41763. */
  41764. function PBRBaseSimpleMaterial(name, scene) {
  41765. var _this = _super.call(this, name, scene) || this;
  41766. /**
  41767. * Number of Simultaneous lights allowed on the material.
  41768. */
  41769. _this.maxSimultaneousLights = 4;
  41770. /**
  41771. * If sets to true, disables all the lights affecting the material.
  41772. */
  41773. _this.disableLighting = false;
  41774. /**
  41775. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41776. */
  41777. _this.invertNormalMapX = false;
  41778. /**
  41779. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41780. */
  41781. _this.invertNormalMapY = false;
  41782. /**
  41783. * Emissivie color used to self-illuminate the model.
  41784. */
  41785. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41786. /**
  41787. * Occlusion Channel Strenght.
  41788. */
  41789. _this.occlusionStrength = 1.0;
  41790. _this.useLightmapAsShadowmap = false;
  41791. _this._useAlphaFromAlbedoTexture = true;
  41792. _this._useAmbientInGrayScale = true;
  41793. return _this;
  41794. }
  41795. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41796. /**
  41797. * Gets the current double sided mode.
  41798. */
  41799. get: function () {
  41800. return this._twoSidedLighting;
  41801. },
  41802. /**
  41803. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41804. */
  41805. set: function (value) {
  41806. if (this._twoSidedLighting === value) {
  41807. return;
  41808. }
  41809. this._twoSidedLighting = value;
  41810. this.backFaceCulling = !value;
  41811. this._markAllSubMeshesAsTexturesDirty();
  41812. },
  41813. enumerable: true,
  41814. configurable: true
  41815. });
  41816. /**
  41817. * Return the active textures of the material.
  41818. */
  41819. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41820. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41821. if (this.environmentTexture) {
  41822. activeTextures.push(this.environmentTexture);
  41823. }
  41824. if (this.normalTexture) {
  41825. activeTextures.push(this.normalTexture);
  41826. }
  41827. if (this.emissiveTexture) {
  41828. activeTextures.push(this.emissiveTexture);
  41829. }
  41830. if (this.occlusionTexture) {
  41831. activeTextures.push(this.occlusionTexture);
  41832. }
  41833. if (this.lightmapTexture) {
  41834. activeTextures.push(this.lightmapTexture);
  41835. }
  41836. return activeTextures;
  41837. };
  41838. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41839. if (_super.prototype.hasTexture.call(this, texture)) {
  41840. return true;
  41841. }
  41842. if (this.lightmapTexture === texture) {
  41843. return true;
  41844. }
  41845. return false;
  41846. };
  41847. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41848. return "PBRBaseSimpleMaterial";
  41849. };
  41850. __decorate([
  41851. BABYLON.serialize(),
  41852. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41853. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41854. __decorate([
  41855. BABYLON.serialize(),
  41856. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41857. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41858. __decorate([
  41859. BABYLON.serializeAsTexture(),
  41860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41861. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41862. __decorate([
  41863. BABYLON.serialize(),
  41864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41865. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41866. __decorate([
  41867. BABYLON.serialize(),
  41868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41869. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41870. __decorate([
  41871. BABYLON.serializeAsTexture(),
  41872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41873. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41874. __decorate([
  41875. BABYLON.serializeAsColor3("emissive"),
  41876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41877. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41878. __decorate([
  41879. BABYLON.serializeAsTexture(),
  41880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41881. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41882. __decorate([
  41883. BABYLON.serialize(),
  41884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41885. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41886. __decorate([
  41887. BABYLON.serializeAsTexture(),
  41888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41889. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41890. __decorate([
  41891. BABYLON.serialize(),
  41892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41893. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41894. __decorate([
  41895. BABYLON.serialize()
  41896. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41897. __decorate([
  41898. BABYLON.serializeAsTexture(),
  41899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41900. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41901. __decorate([
  41902. BABYLON.serialize(),
  41903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41904. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41905. return PBRBaseSimpleMaterial;
  41906. }(BABYLON.PBRBaseMaterial));
  41907. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41908. })(BABYLON || (BABYLON = {}));
  41909. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41910. var BABYLON;
  41911. (function (BABYLON) {
  41912. /**
  41913. * The Physically based material of BJS.
  41914. *
  41915. * This offers the main features of a standard PBR material.
  41916. * For more information, please refer to the documentation :
  41917. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41918. */
  41919. var PBRMaterial = /** @class */ (function (_super) {
  41920. __extends(PBRMaterial, _super);
  41921. /**
  41922. * Instantiates a new PBRMaterial instance.
  41923. *
  41924. * @param name The material name
  41925. * @param scene The scene the material will be use in.
  41926. */
  41927. function PBRMaterial(name, scene) {
  41928. var _this = _super.call(this, name, scene) || this;
  41929. /**
  41930. * Intensity of the direct lights e.g. the four lights available in your scene.
  41931. * This impacts both the direct diffuse and specular highlights.
  41932. */
  41933. _this.directIntensity = 1.0;
  41934. /**
  41935. * Intensity of the emissive part of the material.
  41936. * This helps controlling the emissive effect without modifying the emissive color.
  41937. */
  41938. _this.emissiveIntensity = 1.0;
  41939. /**
  41940. * Intensity of the environment e.g. how much the environment will light the object
  41941. * either through harmonics for rough material or through the refelction for shiny ones.
  41942. */
  41943. _this.environmentIntensity = 1.0;
  41944. /**
  41945. * This is a special control allowing the reduction of the specular highlights coming from the
  41946. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41947. */
  41948. _this.specularIntensity = 1.0;
  41949. /**
  41950. * Debug Control allowing disabling the bump map on this material.
  41951. */
  41952. _this.disableBumpMap = false;
  41953. /**
  41954. * AKA Occlusion Texture Intensity in other nomenclature.
  41955. */
  41956. _this.ambientTextureStrength = 1.0;
  41957. /**
  41958. * The color of a material in ambient lighting.
  41959. */
  41960. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41961. /**
  41962. * AKA Diffuse Color in other nomenclature.
  41963. */
  41964. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41965. /**
  41966. * AKA Specular Color in other nomenclature.
  41967. */
  41968. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41969. /**
  41970. * The color reflected from the material.
  41971. */
  41972. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41973. /**
  41974. * The color emitted from the material.
  41975. */
  41976. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41977. /**
  41978. * AKA Glossiness in other nomenclature.
  41979. */
  41980. _this.microSurface = 1.0;
  41981. /**
  41982. * source material index of refraction (IOR)' / 'destination material IOR.
  41983. */
  41984. _this.indexOfRefraction = 0.66;
  41985. /**
  41986. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41987. */
  41988. _this.invertRefractionY = false;
  41989. /**
  41990. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41991. * Materials half opaque for instance using refraction could benefit from this control.
  41992. */
  41993. _this.linkRefractionWithTransparency = false;
  41994. _this.useLightmapAsShadowmap = false;
  41995. /**
  41996. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41997. */
  41998. _this.useAlphaFromAlbedoTexture = false;
  41999. /**
  42000. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42001. */
  42002. _this.forceAlphaTest = false;
  42003. /**
  42004. * Defines the alpha limits in alpha test mode.
  42005. */
  42006. _this.alphaCutOff = 0.4;
  42007. /**
  42008. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42009. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42010. */
  42011. _this.useSpecularOverAlpha = true;
  42012. /**
  42013. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42014. */
  42015. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42016. /**
  42017. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42018. */
  42019. _this.useRoughnessFromMetallicTextureAlpha = true;
  42020. /**
  42021. * Specifies if the metallic texture contains the roughness information in its green channel.
  42022. */
  42023. _this.useRoughnessFromMetallicTextureGreen = false;
  42024. /**
  42025. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42026. */
  42027. _this.useMetallnessFromMetallicTextureBlue = false;
  42028. /**
  42029. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42030. */
  42031. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42032. /**
  42033. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42034. */
  42035. _this.useAmbientInGrayScale = false;
  42036. /**
  42037. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42038. * The material will try to infer what glossiness each pixel should be.
  42039. */
  42040. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42041. /**
  42042. * BJS is using an harcoded light falloff based on a manually sets up range.
  42043. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42044. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42045. */
  42046. _this.usePhysicalLightFalloff = true;
  42047. /**
  42048. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42049. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42050. */
  42051. _this.useRadianceOverAlpha = true;
  42052. /**
  42053. * Allows using an object space normal map (instead of tangent space).
  42054. */
  42055. _this.useObjectSpaceNormalMap = false;
  42056. /**
  42057. * Allows using the bump map in parallax mode.
  42058. */
  42059. _this.useParallax = false;
  42060. /**
  42061. * Allows using the bump map in parallax occlusion mode.
  42062. */
  42063. _this.useParallaxOcclusion = false;
  42064. /**
  42065. * Controls the scale bias of the parallax mode.
  42066. */
  42067. _this.parallaxScaleBias = 0.05;
  42068. /**
  42069. * If sets to true, disables all the lights affecting the material.
  42070. */
  42071. _this.disableLighting = false;
  42072. /**
  42073. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42074. */
  42075. _this.forceIrradianceInFragment = false;
  42076. /**
  42077. * Number of Simultaneous lights allowed on the material.
  42078. */
  42079. _this.maxSimultaneousLights = 4;
  42080. /**
  42081. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42082. */
  42083. _this.invertNormalMapX = false;
  42084. /**
  42085. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42086. */
  42087. _this.invertNormalMapY = false;
  42088. /**
  42089. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42090. */
  42091. _this.twoSidedLighting = false;
  42092. /**
  42093. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42094. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42095. */
  42096. _this.useAlphaFresnel = false;
  42097. /**
  42098. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42099. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42100. */
  42101. _this.useLinearAlphaFresnel = false;
  42102. /**
  42103. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42104. * And/Or occlude the blended part.
  42105. */
  42106. _this.environmentBRDFTexture = null;
  42107. /**
  42108. * Force normal to face away from face.
  42109. */
  42110. _this.forceNormalForward = false;
  42111. /**
  42112. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42113. * makes the reflect vector face the model (under horizon).
  42114. */
  42115. _this.useHorizonOcclusion = true;
  42116. /**
  42117. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42118. * too much the area relying on ambient texture to define their ambient occlusion.
  42119. */
  42120. _this.useRadianceOcclusion = true;
  42121. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42122. return _this;
  42123. }
  42124. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42125. /**
  42126. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42127. */
  42128. get: function () {
  42129. return this._PBRMATERIAL_OPAQUE;
  42130. },
  42131. enumerable: true,
  42132. configurable: true
  42133. });
  42134. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42135. /**
  42136. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42137. */
  42138. get: function () {
  42139. return this._PBRMATERIAL_ALPHATEST;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42145. /**
  42146. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42147. */
  42148. get: function () {
  42149. return this._PBRMATERIAL_ALPHABLEND;
  42150. },
  42151. enumerable: true,
  42152. configurable: true
  42153. });
  42154. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42155. /**
  42156. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42157. * They are also discarded below the alpha cutoff threshold to improve performances.
  42158. */
  42159. get: function () {
  42160. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42161. },
  42162. enumerable: true,
  42163. configurable: true
  42164. });
  42165. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42166. /**
  42167. * Gets the image processing configuration used either in this material.
  42168. */
  42169. get: function () {
  42170. return this._imageProcessingConfiguration;
  42171. },
  42172. /**
  42173. * Sets the Default image processing configuration used either in the this material.
  42174. *
  42175. * If sets to null, the scene one is in use.
  42176. */
  42177. set: function (value) {
  42178. this._attachImageProcessingConfiguration(value);
  42179. // Ensure the effect will be rebuilt.
  42180. this._markAllSubMeshesAsTexturesDirty();
  42181. },
  42182. enumerable: true,
  42183. configurable: true
  42184. });
  42185. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42186. /**
  42187. * Gets wether the color curves effect is enabled.
  42188. */
  42189. get: function () {
  42190. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42191. },
  42192. /**
  42193. * Sets wether the color curves effect is enabled.
  42194. */
  42195. set: function (value) {
  42196. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42197. },
  42198. enumerable: true,
  42199. configurable: true
  42200. });
  42201. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42202. /**
  42203. * Gets wether the color grading effect is enabled.
  42204. */
  42205. get: function () {
  42206. return this.imageProcessingConfiguration.colorGradingEnabled;
  42207. },
  42208. /**
  42209. * Gets wether the color grading effect is enabled.
  42210. */
  42211. set: function (value) {
  42212. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42213. },
  42214. enumerable: true,
  42215. configurable: true
  42216. });
  42217. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42218. /**
  42219. * Gets wether tonemapping is enabled or not.
  42220. */
  42221. get: function () {
  42222. return this._imageProcessingConfiguration.toneMappingEnabled;
  42223. },
  42224. /**
  42225. * Sets wether tonemapping is enabled or not
  42226. */
  42227. set: function (value) {
  42228. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42229. },
  42230. enumerable: true,
  42231. configurable: true
  42232. });
  42233. ;
  42234. ;
  42235. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42236. /**
  42237. * The camera exposure used on this material.
  42238. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42239. * This corresponds to a photographic exposure.
  42240. */
  42241. get: function () {
  42242. return this._imageProcessingConfiguration.exposure;
  42243. },
  42244. /**
  42245. * The camera exposure used on this material.
  42246. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42247. * This corresponds to a photographic exposure.
  42248. */
  42249. set: function (value) {
  42250. this._imageProcessingConfiguration.exposure = value;
  42251. },
  42252. enumerable: true,
  42253. configurable: true
  42254. });
  42255. ;
  42256. ;
  42257. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42258. /**
  42259. * Gets The camera contrast used on this material.
  42260. */
  42261. get: function () {
  42262. return this._imageProcessingConfiguration.contrast;
  42263. },
  42264. /**
  42265. * Sets The camera contrast used on this material.
  42266. */
  42267. set: function (value) {
  42268. this._imageProcessingConfiguration.contrast = value;
  42269. },
  42270. enumerable: true,
  42271. configurable: true
  42272. });
  42273. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42274. /**
  42275. * Gets the Color Grading 2D Lookup Texture.
  42276. */
  42277. get: function () {
  42278. return this._imageProcessingConfiguration.colorGradingTexture;
  42279. },
  42280. /**
  42281. * Sets the Color Grading 2D Lookup Texture.
  42282. */
  42283. set: function (value) {
  42284. this._imageProcessingConfiguration.colorGradingTexture = value;
  42285. },
  42286. enumerable: true,
  42287. configurable: true
  42288. });
  42289. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42290. /**
  42291. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42292. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42293. * 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;
  42294. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42295. */
  42296. get: function () {
  42297. return this._imageProcessingConfiguration.colorCurves;
  42298. },
  42299. /**
  42300. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42301. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42302. * 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;
  42303. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42304. */
  42305. set: function (value) {
  42306. this._imageProcessingConfiguration.colorCurves = value;
  42307. },
  42308. enumerable: true,
  42309. configurable: true
  42310. });
  42311. /**
  42312. * Returns the name of this material class.
  42313. */
  42314. PBRMaterial.prototype.getClassName = function () {
  42315. return "PBRMaterial";
  42316. };
  42317. /**
  42318. * Returns an array of the actively used textures.
  42319. * @returns - Array of BaseTextures
  42320. */
  42321. PBRMaterial.prototype.getActiveTextures = function () {
  42322. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42323. if (this._albedoTexture) {
  42324. activeTextures.push(this._albedoTexture);
  42325. }
  42326. if (this._ambientTexture) {
  42327. activeTextures.push(this._ambientTexture);
  42328. }
  42329. if (this._opacityTexture) {
  42330. activeTextures.push(this._opacityTexture);
  42331. }
  42332. if (this._reflectionTexture) {
  42333. activeTextures.push(this._reflectionTexture);
  42334. }
  42335. if (this._emissiveTexture) {
  42336. activeTextures.push(this._emissiveTexture);
  42337. }
  42338. if (this._reflectivityTexture) {
  42339. activeTextures.push(this._reflectivityTexture);
  42340. }
  42341. if (this._metallicTexture) {
  42342. activeTextures.push(this._metallicTexture);
  42343. }
  42344. if (this._microSurfaceTexture) {
  42345. activeTextures.push(this._microSurfaceTexture);
  42346. }
  42347. if (this._bumpTexture) {
  42348. activeTextures.push(this._bumpTexture);
  42349. }
  42350. if (this._lightmapTexture) {
  42351. activeTextures.push(this._lightmapTexture);
  42352. }
  42353. if (this._refractionTexture) {
  42354. activeTextures.push(this._refractionTexture);
  42355. }
  42356. return activeTextures;
  42357. };
  42358. /**
  42359. * Checks to see if a texture is used in the material.
  42360. * @param texture - Base texture to use.
  42361. * @returns - Boolean specifying if a texture is used in the material.
  42362. */
  42363. PBRMaterial.prototype.hasTexture = function (texture) {
  42364. if (_super.prototype.hasTexture.call(this, texture)) {
  42365. return true;
  42366. }
  42367. if (this._albedoTexture === texture) {
  42368. return true;
  42369. }
  42370. if (this._ambientTexture === texture) {
  42371. return true;
  42372. }
  42373. if (this._opacityTexture === texture) {
  42374. return true;
  42375. }
  42376. if (this._reflectionTexture === texture) {
  42377. return true;
  42378. }
  42379. if (this._reflectivityTexture === texture) {
  42380. return true;
  42381. }
  42382. if (this._metallicTexture === texture) {
  42383. return true;
  42384. }
  42385. if (this._microSurfaceTexture === texture) {
  42386. return true;
  42387. }
  42388. if (this._bumpTexture === texture) {
  42389. return true;
  42390. }
  42391. if (this._lightmapTexture === texture) {
  42392. return true;
  42393. }
  42394. if (this._refractionTexture === texture) {
  42395. return true;
  42396. }
  42397. return false;
  42398. };
  42399. /**
  42400. * Makes a duplicate of the current material.
  42401. * @param name - name to use for the new material.
  42402. */
  42403. PBRMaterial.prototype.clone = function (name) {
  42404. var _this = this;
  42405. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42406. clone.id = name;
  42407. clone.name = name;
  42408. return clone;
  42409. };
  42410. /**
  42411. * Serializes this PBR Material.
  42412. * @returns - An object with the serialized material.
  42413. */
  42414. PBRMaterial.prototype.serialize = function () {
  42415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42416. serializationObject.customType = "BABYLON.PBRMaterial";
  42417. return serializationObject;
  42418. };
  42419. // Statics
  42420. /**
  42421. * Parses a PBR Material from a serialized object.
  42422. * @param source - Serialized object.
  42423. * @param scene - BJS scene instance.
  42424. * @param rootUrl - url for the scene object
  42425. * @returns - PBRMaterial
  42426. */
  42427. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42428. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42429. };
  42430. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42431. /**
  42432. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42433. */
  42434. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42435. /**
  42436. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42437. */
  42438. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42439. /**
  42440. * 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.
  42441. * They are also discarded below the alpha cutoff threshold to improve performances.
  42442. */
  42443. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42447. ], PBRMaterial.prototype, "directIntensity", void 0);
  42448. __decorate([
  42449. BABYLON.serialize(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42451. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42452. __decorate([
  42453. BABYLON.serialize(),
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42456. __decorate([
  42457. BABYLON.serialize(),
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42460. __decorate([
  42461. BABYLON.serialize(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42463. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42464. __decorate([
  42465. BABYLON.serializeAsTexture(),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsTexture(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42475. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42476. __decorate([
  42477. BABYLON.serializeAsTexture(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42479. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42480. __decorate([
  42481. BABYLON.serializeAsTexture(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42483. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42484. __decorate([
  42485. BABYLON.serializeAsTexture(),
  42486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42487. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42488. __decorate([
  42489. BABYLON.serializeAsTexture(),
  42490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42491. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42492. __decorate([
  42493. BABYLON.serializeAsTexture(),
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42495. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42496. __decorate([
  42497. BABYLON.serialize(),
  42498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42499. ], PBRMaterial.prototype, "metallic", void 0);
  42500. __decorate([
  42501. BABYLON.serialize(),
  42502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42503. ], PBRMaterial.prototype, "roughness", void 0);
  42504. __decorate([
  42505. BABYLON.serializeAsTexture(),
  42506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42507. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42508. __decorate([
  42509. BABYLON.serializeAsTexture(),
  42510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42511. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42512. __decorate([
  42513. BABYLON.serializeAsTexture(),
  42514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42515. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42516. __decorate([
  42517. BABYLON.serializeAsTexture(),
  42518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42519. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42520. __decorate([
  42521. BABYLON.serializeAsColor3("ambient"),
  42522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42523. ], PBRMaterial.prototype, "ambientColor", void 0);
  42524. __decorate([
  42525. BABYLON.serializeAsColor3("albedo"),
  42526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42527. ], PBRMaterial.prototype, "albedoColor", void 0);
  42528. __decorate([
  42529. BABYLON.serializeAsColor3("reflectivity"),
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42532. __decorate([
  42533. BABYLON.serializeAsColor3("reflection"),
  42534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42535. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42536. __decorate([
  42537. BABYLON.serializeAsColor3("emissive"),
  42538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42539. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42540. __decorate([
  42541. BABYLON.serialize(),
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], PBRMaterial.prototype, "microSurface", void 0);
  42544. __decorate([
  42545. BABYLON.serialize(),
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42547. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42548. __decorate([
  42549. BABYLON.serialize(),
  42550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42551. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42552. __decorate([
  42553. BABYLON.serialize(),
  42554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42555. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42556. __decorate([
  42557. BABYLON.serialize(),
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42559. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42560. __decorate([
  42561. BABYLON.serialize(),
  42562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42563. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42564. __decorate([
  42565. BABYLON.serialize(),
  42566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42567. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42568. __decorate([
  42569. BABYLON.serialize(),
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42571. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42572. __decorate([
  42573. BABYLON.serialize(),
  42574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42575. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42576. __decorate([
  42577. BABYLON.serialize(),
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42579. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42580. __decorate([
  42581. BABYLON.serialize(),
  42582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42583. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42584. __decorate([
  42585. BABYLON.serialize(),
  42586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42587. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42588. __decorate([
  42589. BABYLON.serialize(),
  42590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42591. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42592. __decorate([
  42593. BABYLON.serialize(),
  42594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42595. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42596. __decorate([
  42597. BABYLON.serialize(),
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42599. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42600. __decorate([
  42601. BABYLON.serialize(),
  42602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42603. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42604. __decorate([
  42605. BABYLON.serialize(),
  42606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42607. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42608. __decorate([
  42609. BABYLON.serialize(),
  42610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42611. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42612. __decorate([
  42613. BABYLON.serialize(),
  42614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42615. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42616. __decorate([
  42617. BABYLON.serialize(),
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42619. ], PBRMaterial.prototype, "useParallax", void 0);
  42620. __decorate([
  42621. BABYLON.serialize(),
  42622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42623. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42624. __decorate([
  42625. BABYLON.serialize(),
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42627. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42628. __decorate([
  42629. BABYLON.serialize(),
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42631. ], PBRMaterial.prototype, "disableLighting", void 0);
  42632. __decorate([
  42633. BABYLON.serialize(),
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42635. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42636. __decorate([
  42637. BABYLON.serialize(),
  42638. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42639. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42640. __decorate([
  42641. BABYLON.serialize(),
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42643. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42644. __decorate([
  42645. BABYLON.serialize(),
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42647. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42648. __decorate([
  42649. BABYLON.serialize(),
  42650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42651. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42652. __decorate([
  42653. BABYLON.serialize(),
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42656. __decorate([
  42657. BABYLON.serialize(),
  42658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42659. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42660. __decorate([
  42661. BABYLON.serializeAsTexture(),
  42662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42663. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42664. __decorate([
  42665. BABYLON.serialize(),
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42668. __decorate([
  42669. BABYLON.serialize(),
  42670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42671. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42672. __decorate([
  42673. BABYLON.serialize(),
  42674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42675. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42676. return PBRMaterial;
  42677. }(BABYLON.PBRBaseMaterial));
  42678. BABYLON.PBRMaterial = PBRMaterial;
  42679. })(BABYLON || (BABYLON = {}));
  42680. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42681. var BABYLON;
  42682. (function (BABYLON) {
  42683. /**
  42684. * The PBR material of BJS following the metal roughness convention.
  42685. *
  42686. * This fits to the PBR convention in the GLTF definition:
  42687. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42688. */
  42689. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42690. __extends(PBRMetallicRoughnessMaterial, _super);
  42691. /**
  42692. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42693. *
  42694. * @param name The material name
  42695. * @param scene The scene the material will be use in.
  42696. */
  42697. function PBRMetallicRoughnessMaterial(name, scene) {
  42698. var _this = _super.call(this, name, scene) || this;
  42699. _this._useRoughnessFromMetallicTextureAlpha = false;
  42700. _this._useRoughnessFromMetallicTextureGreen = true;
  42701. _this._useMetallnessFromMetallicTextureBlue = true;
  42702. _this.metallic = 1.0;
  42703. _this.roughness = 1.0;
  42704. return _this;
  42705. }
  42706. /**
  42707. * Return the currrent class name of the material.
  42708. */
  42709. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42710. return "PBRMetallicRoughnessMaterial";
  42711. };
  42712. /**
  42713. * Return the active textures of the material.
  42714. */
  42715. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42716. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42717. if (this.baseTexture) {
  42718. activeTextures.push(this.baseTexture);
  42719. }
  42720. if (this.metallicRoughnessTexture) {
  42721. activeTextures.push(this.metallicRoughnessTexture);
  42722. }
  42723. return activeTextures;
  42724. };
  42725. /**
  42726. * Checks to see if a texture is used in the material.
  42727. * @param texture - Base texture to use.
  42728. * @returns - Boolean specifying if a texture is used in the material.
  42729. */
  42730. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42731. if (_super.prototype.hasTexture.call(this, texture)) {
  42732. return true;
  42733. }
  42734. if (this.baseTexture === texture) {
  42735. return true;
  42736. }
  42737. if (this.metallicRoughnessTexture === texture) {
  42738. return true;
  42739. }
  42740. return false;
  42741. };
  42742. /**
  42743. * Makes a duplicate of the current material.
  42744. * @param name - name to use for the new material.
  42745. */
  42746. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42747. var _this = this;
  42748. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42749. clone.id = name;
  42750. clone.name = name;
  42751. return clone;
  42752. };
  42753. /**
  42754. * Serialize the material to a parsable JSON object.
  42755. */
  42756. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42758. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42759. return serializationObject;
  42760. };
  42761. /**
  42762. * Parses a JSON object correponding to the serialize function.
  42763. */
  42764. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42765. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42766. };
  42767. __decorate([
  42768. BABYLON.serializeAsColor3(),
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42770. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42771. __decorate([
  42772. BABYLON.serializeAsTexture(),
  42773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42774. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42775. __decorate([
  42776. BABYLON.serialize(),
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42779. __decorate([
  42780. BABYLON.serialize(),
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42783. __decorate([
  42784. BABYLON.serializeAsTexture(),
  42785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42786. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42787. return PBRMetallicRoughnessMaterial;
  42788. }(BABYLON.PBRBaseSimpleMaterial));
  42789. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42790. })(BABYLON || (BABYLON = {}));
  42791. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42792. var BABYLON;
  42793. (function (BABYLON) {
  42794. /**
  42795. * The PBR material of BJS following the specular glossiness convention.
  42796. *
  42797. * This fits to the PBR convention in the GLTF definition:
  42798. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42799. */
  42800. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42801. __extends(PBRSpecularGlossinessMaterial, _super);
  42802. /**
  42803. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42804. *
  42805. * @param name The material name
  42806. * @param scene The scene the material will be use in.
  42807. */
  42808. function PBRSpecularGlossinessMaterial(name, scene) {
  42809. var _this = _super.call(this, name, scene) || this;
  42810. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42811. return _this;
  42812. }
  42813. /**
  42814. * Return the currrent class name of the material.
  42815. */
  42816. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42817. return "PBRSpecularGlossinessMaterial";
  42818. };
  42819. /**
  42820. * Return the active textures of the material.
  42821. */
  42822. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42823. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42824. if (this.diffuseTexture) {
  42825. activeTextures.push(this.diffuseTexture);
  42826. }
  42827. if (this.specularGlossinessTexture) {
  42828. activeTextures.push(this.specularGlossinessTexture);
  42829. }
  42830. return activeTextures;
  42831. };
  42832. /**
  42833. * Checks to see if a texture is used in the material.
  42834. * @param texture - Base texture to use.
  42835. * @returns - Boolean specifying if a texture is used in the material.
  42836. */
  42837. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42838. if (_super.prototype.hasTexture.call(this, texture)) {
  42839. return true;
  42840. }
  42841. if (this.diffuseTexture === texture) {
  42842. return true;
  42843. }
  42844. if (this.specularGlossinessTexture === texture) {
  42845. return true;
  42846. }
  42847. return false;
  42848. };
  42849. /**
  42850. * Makes a duplicate of the current material.
  42851. * @param name - name to use for the new material.
  42852. */
  42853. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42854. var _this = this;
  42855. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42856. clone.id = name;
  42857. clone.name = name;
  42858. return clone;
  42859. };
  42860. /**
  42861. * Serialize the material to a parsable JSON object.
  42862. */
  42863. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42864. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42865. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42866. return serializationObject;
  42867. };
  42868. /**
  42869. * Parses a JSON object correponding to the serialize function.
  42870. */
  42871. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42872. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42873. };
  42874. __decorate([
  42875. BABYLON.serializeAsColor3("diffuse"),
  42876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42877. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42878. __decorate([
  42879. BABYLON.serializeAsTexture(),
  42880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42881. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42882. __decorate([
  42883. BABYLON.serializeAsColor3("specular"),
  42884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42885. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42886. __decorate([
  42887. BABYLON.serialize(),
  42888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42889. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42890. __decorate([
  42891. BABYLON.serializeAsTexture(),
  42892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42893. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42894. return PBRSpecularGlossinessMaterial;
  42895. }(BABYLON.PBRBaseSimpleMaterial));
  42896. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42897. })(BABYLON || (BABYLON = {}));
  42898. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42899. var BABYLON;
  42900. (function (BABYLON) {
  42901. BABYLON.CameraInputTypes = {};
  42902. var CameraInputsManager = /** @class */ (function () {
  42903. function CameraInputsManager(camera) {
  42904. this.attached = {};
  42905. this.camera = camera;
  42906. this.checkInputs = function () { };
  42907. }
  42908. /**
  42909. * Add an input method to a camera.
  42910. * builtin inputs example: camera.inputs.addGamepad();
  42911. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42912. * @param input camera input method
  42913. */
  42914. CameraInputsManager.prototype.add = function (input) {
  42915. var type = input.getSimpleName();
  42916. if (this.attached[type]) {
  42917. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42918. return;
  42919. }
  42920. this.attached[type] = input;
  42921. input.camera = this.camera;
  42922. //for checkInputs, we are dynamically creating a function
  42923. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42924. if (input.checkInputs) {
  42925. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42926. }
  42927. if (this.attachedElement) {
  42928. input.attachControl(this.attachedElement);
  42929. }
  42930. };
  42931. /**
  42932. * Remove a specific input method from a camera
  42933. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42934. * @param inputToRemove camera input method
  42935. */
  42936. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42937. for (var cam in this.attached) {
  42938. var input = this.attached[cam];
  42939. if (input === inputToRemove) {
  42940. input.detachControl(this.attachedElement);
  42941. input.camera = null;
  42942. delete this.attached[cam];
  42943. this.rebuildInputCheck();
  42944. }
  42945. }
  42946. };
  42947. CameraInputsManager.prototype.removeByType = function (inputType) {
  42948. for (var cam in this.attached) {
  42949. var input = this.attached[cam];
  42950. if (input.getClassName() === inputType) {
  42951. input.detachControl(this.attachedElement);
  42952. input.camera = null;
  42953. delete this.attached[cam];
  42954. this.rebuildInputCheck();
  42955. }
  42956. }
  42957. };
  42958. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42959. var current = this.checkInputs;
  42960. return function () {
  42961. current();
  42962. fn();
  42963. };
  42964. };
  42965. CameraInputsManager.prototype.attachInput = function (input) {
  42966. if (this.attachedElement) {
  42967. input.attachControl(this.attachedElement, this.noPreventDefault);
  42968. }
  42969. };
  42970. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42971. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42972. if (this.attachedElement) {
  42973. return;
  42974. }
  42975. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42976. this.attachedElement = element;
  42977. this.noPreventDefault = noPreventDefault;
  42978. for (var cam in this.attached) {
  42979. this.attached[cam].attachControl(element, noPreventDefault);
  42980. }
  42981. };
  42982. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42983. if (disconnect === void 0) { disconnect = false; }
  42984. if (this.attachedElement !== element) {
  42985. return;
  42986. }
  42987. for (var cam in this.attached) {
  42988. this.attached[cam].detachControl(element);
  42989. if (disconnect) {
  42990. this.attached[cam].camera = null;
  42991. }
  42992. }
  42993. this.attachedElement = null;
  42994. };
  42995. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42996. this.checkInputs = function () { };
  42997. for (var cam in this.attached) {
  42998. var input = this.attached[cam];
  42999. if (input.checkInputs) {
  43000. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43001. }
  43002. }
  43003. };
  43004. /**
  43005. * Remove all attached input methods from a camera
  43006. */
  43007. CameraInputsManager.prototype.clear = function () {
  43008. if (this.attachedElement) {
  43009. this.detachElement(this.attachedElement, true);
  43010. }
  43011. this.attached = {};
  43012. this.attachedElement = null;
  43013. this.checkInputs = function () { };
  43014. };
  43015. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43016. var inputs = {};
  43017. for (var cam in this.attached) {
  43018. var input = this.attached[cam];
  43019. var res = BABYLON.SerializationHelper.Serialize(input);
  43020. inputs[input.getClassName()] = res;
  43021. }
  43022. serializedCamera.inputsmgr = inputs;
  43023. };
  43024. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43025. var parsedInputs = parsedCamera.inputsmgr;
  43026. if (parsedInputs) {
  43027. this.clear();
  43028. for (var n in parsedInputs) {
  43029. var construct = BABYLON.CameraInputTypes[n];
  43030. if (construct) {
  43031. var parsedinput = parsedInputs[n];
  43032. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43033. this.add(input);
  43034. }
  43035. }
  43036. }
  43037. else {
  43038. //2016-03-08 this part is for managing backward compatibility
  43039. for (var n in this.attached) {
  43040. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43041. if (construct) {
  43042. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43043. this.remove(this.attached[n]);
  43044. this.add(input);
  43045. }
  43046. }
  43047. }
  43048. };
  43049. return CameraInputsManager;
  43050. }());
  43051. BABYLON.CameraInputsManager = CameraInputsManager;
  43052. })(BABYLON || (BABYLON = {}));
  43053. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43054. var BABYLON;
  43055. (function (BABYLON) {
  43056. var TargetCamera = /** @class */ (function (_super) {
  43057. __extends(TargetCamera, _super);
  43058. function TargetCamera(name, position, scene) {
  43059. var _this = _super.call(this, name, position, scene) || this;
  43060. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43061. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43062. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43063. _this.speed = 2.0;
  43064. _this.noRotationConstraint = false;
  43065. _this.lockedTarget = null;
  43066. _this._currentTarget = BABYLON.Vector3.Zero();
  43067. _this._viewMatrix = BABYLON.Matrix.Zero();
  43068. _this._camMatrix = BABYLON.Matrix.Zero();
  43069. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43070. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43071. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43072. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43073. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43074. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43075. _this._tempMatrix = BABYLON.Matrix.Zero();
  43076. return _this;
  43077. }
  43078. TargetCamera.prototype.getFrontPosition = function (distance) {
  43079. this.getWorldMatrix();
  43080. var direction = this.getTarget().subtract(this.position);
  43081. direction.normalize();
  43082. direction.scaleInPlace(distance);
  43083. return this.globalPosition.add(direction);
  43084. };
  43085. TargetCamera.prototype._getLockedTargetPosition = function () {
  43086. if (!this.lockedTarget) {
  43087. return null;
  43088. }
  43089. if (this.lockedTarget.absolutePosition) {
  43090. this.lockedTarget.computeWorldMatrix();
  43091. }
  43092. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43093. };
  43094. TargetCamera.prototype.storeState = function () {
  43095. this._storedPosition = this.position.clone();
  43096. this._storedRotation = this.rotation.clone();
  43097. if (this.rotationQuaternion) {
  43098. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43099. }
  43100. return _super.prototype.storeState.call(this);
  43101. };
  43102. /**
  43103. * Restored camera state. You must call storeState() first
  43104. */
  43105. TargetCamera.prototype._restoreStateValues = function () {
  43106. if (!_super.prototype._restoreStateValues.call(this)) {
  43107. return false;
  43108. }
  43109. this.position = this._storedPosition.clone();
  43110. this.rotation = this._storedRotation.clone();
  43111. if (this.rotationQuaternion) {
  43112. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43113. }
  43114. this.cameraDirection.copyFromFloats(0, 0, 0);
  43115. this.cameraRotation.copyFromFloats(0, 0);
  43116. return true;
  43117. };
  43118. // Cache
  43119. TargetCamera.prototype._initCache = function () {
  43120. _super.prototype._initCache.call(this);
  43121. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43122. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43123. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43124. };
  43125. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43126. if (!ignoreParentClass) {
  43127. _super.prototype._updateCache.call(this);
  43128. }
  43129. var lockedTargetPosition = this._getLockedTargetPosition();
  43130. if (!lockedTargetPosition) {
  43131. this._cache.lockedTarget = null;
  43132. }
  43133. else {
  43134. if (!this._cache.lockedTarget) {
  43135. this._cache.lockedTarget = lockedTargetPosition.clone();
  43136. }
  43137. else {
  43138. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43139. }
  43140. }
  43141. this._cache.rotation.copyFrom(this.rotation);
  43142. if (this.rotationQuaternion)
  43143. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43144. };
  43145. // Synchronized
  43146. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43147. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43148. return false;
  43149. }
  43150. var lockedTargetPosition = this._getLockedTargetPosition();
  43151. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43152. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43153. };
  43154. // Methods
  43155. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43156. var engine = this.getEngine();
  43157. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43158. };
  43159. // Target
  43160. TargetCamera.prototype.setTarget = function (target) {
  43161. this.upVector.normalize();
  43162. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43163. this._camMatrix.invert();
  43164. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43165. var vDir = target.subtract(this.position);
  43166. if (vDir.x >= 0.0) {
  43167. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43168. }
  43169. else {
  43170. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43171. }
  43172. this.rotation.z = 0;
  43173. if (isNaN(this.rotation.x)) {
  43174. this.rotation.x = 0;
  43175. }
  43176. if (isNaN(this.rotation.y)) {
  43177. this.rotation.y = 0;
  43178. }
  43179. if (isNaN(this.rotation.z)) {
  43180. this.rotation.z = 0;
  43181. }
  43182. if (this.rotationQuaternion) {
  43183. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43184. }
  43185. };
  43186. /**
  43187. * Return the current target position of the camera. This value is expressed in local space.
  43188. */
  43189. TargetCamera.prototype.getTarget = function () {
  43190. return this._currentTarget;
  43191. };
  43192. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43193. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43194. };
  43195. TargetCamera.prototype._updatePosition = function () {
  43196. if (this.parent) {
  43197. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43198. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43199. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43200. return;
  43201. }
  43202. this.position.addInPlace(this.cameraDirection);
  43203. };
  43204. TargetCamera.prototype._checkInputs = function () {
  43205. var needToMove = this._decideIfNeedsToMove();
  43206. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43207. // Move
  43208. if (needToMove) {
  43209. this._updatePosition();
  43210. }
  43211. // Rotate
  43212. if (needToRotate) {
  43213. this.rotation.x += this.cameraRotation.x;
  43214. this.rotation.y += this.cameraRotation.y;
  43215. //rotate, if quaternion is set and rotation was used
  43216. if (this.rotationQuaternion) {
  43217. var len = this.rotation.lengthSquared();
  43218. if (len) {
  43219. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43220. }
  43221. }
  43222. if (!this.noRotationConstraint) {
  43223. var limit = (Math.PI / 2) * 0.95;
  43224. if (this.rotation.x > limit)
  43225. this.rotation.x = limit;
  43226. if (this.rotation.x < -limit)
  43227. this.rotation.x = -limit;
  43228. }
  43229. }
  43230. // Inertia
  43231. if (needToMove) {
  43232. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43233. this.cameraDirection.x = 0;
  43234. }
  43235. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43236. this.cameraDirection.y = 0;
  43237. }
  43238. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43239. this.cameraDirection.z = 0;
  43240. }
  43241. this.cameraDirection.scaleInPlace(this.inertia);
  43242. }
  43243. if (needToRotate) {
  43244. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43245. this.cameraRotation.x = 0;
  43246. }
  43247. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43248. this.cameraRotation.y = 0;
  43249. }
  43250. this.cameraRotation.scaleInPlace(this.inertia);
  43251. }
  43252. _super.prototype._checkInputs.call(this);
  43253. };
  43254. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43255. if (this.rotationQuaternion) {
  43256. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43257. }
  43258. else {
  43259. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43260. }
  43261. //update the up vector!
  43262. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43263. };
  43264. TargetCamera.prototype._getViewMatrix = function () {
  43265. if (this.lockedTarget) {
  43266. this.setTarget(this._getLockedTargetPosition());
  43267. }
  43268. // Compute
  43269. this._updateCameraRotationMatrix();
  43270. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43271. // Computing target and final matrix
  43272. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43273. if (this.getScene().useRightHandedSystem) {
  43274. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43275. }
  43276. else {
  43277. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43278. }
  43279. return this._viewMatrix;
  43280. };
  43281. /**
  43282. * @override
  43283. * Override Camera.createRigCamera
  43284. */
  43285. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43286. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43287. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43288. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43289. if (!this.rotationQuaternion) {
  43290. this.rotationQuaternion = new BABYLON.Quaternion();
  43291. }
  43292. rigCamera._cameraRigParams = {};
  43293. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43294. }
  43295. return rigCamera;
  43296. }
  43297. return null;
  43298. };
  43299. /**
  43300. * @override
  43301. * Override Camera._updateRigCameras
  43302. */
  43303. TargetCamera.prototype._updateRigCameras = function () {
  43304. var camLeft = this._rigCameras[0];
  43305. var camRight = this._rigCameras[1];
  43306. switch (this.cameraRigMode) {
  43307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43309. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43311. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43312. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43313. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43314. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43315. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43316. camLeft.setTarget(this.getTarget());
  43317. camRight.setTarget(this.getTarget());
  43318. break;
  43319. case BABYLON.Camera.RIG_MODE_VR:
  43320. if (camLeft.rotationQuaternion) {
  43321. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43322. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43323. }
  43324. else {
  43325. camLeft.rotation.copyFrom(this.rotation);
  43326. camRight.rotation.copyFrom(this.rotation);
  43327. }
  43328. camLeft.position.copyFrom(this.position);
  43329. camRight.position.copyFrom(this.position);
  43330. break;
  43331. }
  43332. _super.prototype._updateRigCameras.call(this);
  43333. };
  43334. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43335. if (!this._rigCamTransformMatrix) {
  43336. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43337. }
  43338. var target = this.getTarget();
  43339. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43340. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43341. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43342. };
  43343. TargetCamera.prototype.getClassName = function () {
  43344. return "TargetCamera";
  43345. };
  43346. __decorate([
  43347. BABYLON.serializeAsVector3()
  43348. ], TargetCamera.prototype, "rotation", void 0);
  43349. __decorate([
  43350. BABYLON.serialize()
  43351. ], TargetCamera.prototype, "speed", void 0);
  43352. __decorate([
  43353. BABYLON.serializeAsMeshReference("lockedTargetId")
  43354. ], TargetCamera.prototype, "lockedTarget", void 0);
  43355. return TargetCamera;
  43356. }(BABYLON.Camera));
  43357. BABYLON.TargetCamera = TargetCamera;
  43358. })(BABYLON || (BABYLON = {}));
  43359. //# sourceMappingURL=babylon.targetCamera.js.map
  43360. var BABYLON;
  43361. (function (BABYLON) {
  43362. var FreeCameraMouseInput = /** @class */ (function () {
  43363. function FreeCameraMouseInput(touchEnabled) {
  43364. if (touchEnabled === void 0) { touchEnabled = true; }
  43365. this.touchEnabled = touchEnabled;
  43366. this.buttons = [0, 1, 2];
  43367. this.angularSensibility = 2000.0;
  43368. this.previousPosition = null;
  43369. }
  43370. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43371. var _this = this;
  43372. var engine = this.camera.getEngine();
  43373. if (!this._pointerInput) {
  43374. this._pointerInput = function (p, s) {
  43375. var evt = p.event;
  43376. if (engine.isInVRExclusivePointerMode) {
  43377. return;
  43378. }
  43379. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43380. return;
  43381. }
  43382. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43383. return;
  43384. }
  43385. var srcElement = (evt.srcElement || evt.target);
  43386. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43387. try {
  43388. srcElement.setPointerCapture(evt.pointerId);
  43389. }
  43390. catch (e) {
  43391. //Nothing to do with the error. Execution will continue.
  43392. }
  43393. _this.previousPosition = {
  43394. x: evt.clientX,
  43395. y: evt.clientY
  43396. };
  43397. if (!noPreventDefault) {
  43398. evt.preventDefault();
  43399. element.focus();
  43400. }
  43401. }
  43402. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43403. try {
  43404. srcElement.releasePointerCapture(evt.pointerId);
  43405. }
  43406. catch (e) {
  43407. //Nothing to do with the error.
  43408. }
  43409. _this.previousPosition = null;
  43410. if (!noPreventDefault) {
  43411. evt.preventDefault();
  43412. }
  43413. }
  43414. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43415. if (!_this.previousPosition || engine.isPointerLock) {
  43416. return;
  43417. }
  43418. var offsetX = evt.clientX - _this.previousPosition.x;
  43419. var offsetY = evt.clientY - _this.previousPosition.y;
  43420. if (_this.camera.getScene().useRightHandedSystem) {
  43421. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43422. }
  43423. else {
  43424. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43425. }
  43426. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43427. _this.previousPosition = {
  43428. x: evt.clientX,
  43429. y: evt.clientY
  43430. };
  43431. if (!noPreventDefault) {
  43432. evt.preventDefault();
  43433. }
  43434. }
  43435. };
  43436. }
  43437. this._onMouseMove = function (evt) {
  43438. if (!engine.isPointerLock) {
  43439. return;
  43440. }
  43441. if (engine.isInVRExclusivePointerMode) {
  43442. return;
  43443. }
  43444. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43445. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43446. if (_this.camera.getScene().useRightHandedSystem) {
  43447. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43448. }
  43449. else {
  43450. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43451. }
  43452. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43453. _this.previousPosition = null;
  43454. if (!noPreventDefault) {
  43455. evt.preventDefault();
  43456. }
  43457. };
  43458. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43459. element.addEventListener("mousemove", this._onMouseMove, false);
  43460. };
  43461. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43462. if (this._observer && element) {
  43463. this.camera.getScene().onPointerObservable.remove(this._observer);
  43464. if (this._onMouseMove) {
  43465. element.removeEventListener("mousemove", this._onMouseMove);
  43466. }
  43467. this._observer = null;
  43468. this._onMouseMove = null;
  43469. this.previousPosition = null;
  43470. }
  43471. };
  43472. FreeCameraMouseInput.prototype.getClassName = function () {
  43473. return "FreeCameraMouseInput";
  43474. };
  43475. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43476. return "mouse";
  43477. };
  43478. __decorate([
  43479. BABYLON.serialize()
  43480. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43481. __decorate([
  43482. BABYLON.serialize()
  43483. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43484. return FreeCameraMouseInput;
  43485. }());
  43486. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43487. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43488. })(BABYLON || (BABYLON = {}));
  43489. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43490. var BABYLON;
  43491. (function (BABYLON) {
  43492. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43493. function FreeCameraKeyboardMoveInput() {
  43494. this._keys = new Array();
  43495. this.keysUp = [38];
  43496. this.keysDown = [40];
  43497. this.keysLeft = [37];
  43498. this.keysRight = [39];
  43499. }
  43500. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43501. var _this = this;
  43502. if (this._onCanvasBlurObserver) {
  43503. return;
  43504. }
  43505. this._scene = this.camera.getScene();
  43506. this._engine = this._scene.getEngine();
  43507. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43508. _this._keys = [];
  43509. });
  43510. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43511. var evt = info.event;
  43512. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43513. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43514. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43515. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43516. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43517. var index = _this._keys.indexOf(evt.keyCode);
  43518. if (index === -1) {
  43519. _this._keys.push(evt.keyCode);
  43520. }
  43521. if (!noPreventDefault) {
  43522. evt.preventDefault();
  43523. }
  43524. }
  43525. }
  43526. else {
  43527. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43528. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43529. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43530. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43531. var index = _this._keys.indexOf(evt.keyCode);
  43532. if (index >= 0) {
  43533. _this._keys.splice(index, 1);
  43534. }
  43535. if (!noPreventDefault) {
  43536. evt.preventDefault();
  43537. }
  43538. }
  43539. }
  43540. });
  43541. };
  43542. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43543. if (this._scene) {
  43544. if (this._onKeyboardObserver) {
  43545. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43546. }
  43547. if (this._onCanvasBlurObserver) {
  43548. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43549. }
  43550. this._onKeyboardObserver = null;
  43551. this._onCanvasBlurObserver = null;
  43552. }
  43553. this._keys = [];
  43554. };
  43555. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43556. if (this._onKeyboardObserver) {
  43557. var camera = this.camera;
  43558. // Keyboard
  43559. for (var index = 0; index < this._keys.length; index++) {
  43560. var keyCode = this._keys[index];
  43561. var speed = camera._computeLocalCameraSpeed();
  43562. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43563. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43564. }
  43565. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43566. camera._localDirection.copyFromFloats(0, 0, speed);
  43567. }
  43568. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43569. camera._localDirection.copyFromFloats(speed, 0, 0);
  43570. }
  43571. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43572. camera._localDirection.copyFromFloats(0, 0, -speed);
  43573. }
  43574. if (camera.getScene().useRightHandedSystem) {
  43575. camera._localDirection.z *= -1;
  43576. }
  43577. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43578. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43579. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43580. }
  43581. }
  43582. };
  43583. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43584. return "FreeCameraKeyboardMoveInput";
  43585. };
  43586. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43587. this._keys = [];
  43588. };
  43589. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43590. return "keyboard";
  43591. };
  43592. __decorate([
  43593. BABYLON.serialize()
  43594. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43595. __decorate([
  43596. BABYLON.serialize()
  43597. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43598. __decorate([
  43599. BABYLON.serialize()
  43600. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43601. __decorate([
  43602. BABYLON.serialize()
  43603. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43604. return FreeCameraKeyboardMoveInput;
  43605. }());
  43606. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43607. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43608. })(BABYLON || (BABYLON = {}));
  43609. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43610. var BABYLON;
  43611. (function (BABYLON) {
  43612. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43613. __extends(FreeCameraInputsManager, _super);
  43614. function FreeCameraInputsManager(camera) {
  43615. return _super.call(this, camera) || this;
  43616. }
  43617. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43618. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43619. return this;
  43620. };
  43621. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43622. if (touchEnabled === void 0) { touchEnabled = true; }
  43623. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43624. return this;
  43625. };
  43626. FreeCameraInputsManager.prototype.addGamepad = function () {
  43627. this.add(new BABYLON.FreeCameraGamepadInput());
  43628. return this;
  43629. };
  43630. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43631. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43632. return this;
  43633. };
  43634. FreeCameraInputsManager.prototype.addTouch = function () {
  43635. this.add(new BABYLON.FreeCameraTouchInput());
  43636. return this;
  43637. };
  43638. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43639. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43640. return this;
  43641. };
  43642. return FreeCameraInputsManager;
  43643. }(BABYLON.CameraInputsManager));
  43644. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43645. })(BABYLON || (BABYLON = {}));
  43646. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43647. var BABYLON;
  43648. (function (BABYLON) {
  43649. var FreeCamera = /** @class */ (function (_super) {
  43650. __extends(FreeCamera, _super);
  43651. function FreeCamera(name, position, scene) {
  43652. var _this = _super.call(this, name, position, scene) || this;
  43653. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43654. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43655. _this.checkCollisions = false;
  43656. _this.applyGravity = false;
  43657. _this._needMoveForGravity = false;
  43658. _this._oldPosition = BABYLON.Vector3.Zero();
  43659. _this._diffPosition = BABYLON.Vector3.Zero();
  43660. _this._newPosition = BABYLON.Vector3.Zero();
  43661. // Collisions
  43662. _this._collisionMask = -1;
  43663. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43664. if (collidedMesh === void 0) { collidedMesh = null; }
  43665. //TODO move this to the collision coordinator!
  43666. if (_this.getScene().workerCollisions)
  43667. newPosition.multiplyInPlace(_this._collider._radius);
  43668. var updatePosition = function (newPos) {
  43669. _this._newPosition.copyFrom(newPos);
  43670. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43671. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43672. _this.position.addInPlace(_this._diffPosition);
  43673. if (_this.onCollide && collidedMesh) {
  43674. _this.onCollide(collidedMesh);
  43675. }
  43676. }
  43677. };
  43678. updatePosition(newPosition);
  43679. };
  43680. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43681. _this.inputs.addKeyboard().addMouse();
  43682. return _this;
  43683. }
  43684. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43685. //-- begin properties for backward compatibility for inputs
  43686. /**
  43687. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43688. * Higher values reduce sensitivity.
  43689. */
  43690. get: function () {
  43691. var mouse = this.inputs.attached["mouse"];
  43692. if (mouse)
  43693. return mouse.angularSensibility;
  43694. return 0;
  43695. },
  43696. /**
  43697. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43698. * Higher values reduce sensitivity.
  43699. */
  43700. set: function (value) {
  43701. var mouse = this.inputs.attached["mouse"];
  43702. if (mouse)
  43703. mouse.angularSensibility = value;
  43704. },
  43705. enumerable: true,
  43706. configurable: true
  43707. });
  43708. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43709. get: function () {
  43710. var keyboard = this.inputs.attached["keyboard"];
  43711. if (keyboard)
  43712. return keyboard.keysUp;
  43713. return [];
  43714. },
  43715. set: function (value) {
  43716. var keyboard = this.inputs.attached["keyboard"];
  43717. if (keyboard)
  43718. keyboard.keysUp = value;
  43719. },
  43720. enumerable: true,
  43721. configurable: true
  43722. });
  43723. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43724. get: function () {
  43725. var keyboard = this.inputs.attached["keyboard"];
  43726. if (keyboard)
  43727. return keyboard.keysDown;
  43728. return [];
  43729. },
  43730. set: function (value) {
  43731. var keyboard = this.inputs.attached["keyboard"];
  43732. if (keyboard)
  43733. keyboard.keysDown = value;
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43739. get: function () {
  43740. var keyboard = this.inputs.attached["keyboard"];
  43741. if (keyboard)
  43742. return keyboard.keysLeft;
  43743. return [];
  43744. },
  43745. set: function (value) {
  43746. var keyboard = this.inputs.attached["keyboard"];
  43747. if (keyboard)
  43748. keyboard.keysLeft = value;
  43749. },
  43750. enumerable: true,
  43751. configurable: true
  43752. });
  43753. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43754. get: function () {
  43755. var keyboard = this.inputs.attached["keyboard"];
  43756. if (keyboard)
  43757. return keyboard.keysRight;
  43758. return [];
  43759. },
  43760. set: function (value) {
  43761. var keyboard = this.inputs.attached["keyboard"];
  43762. if (keyboard)
  43763. keyboard.keysRight = value;
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. // Controls
  43769. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43770. this.inputs.attachElement(element, noPreventDefault);
  43771. };
  43772. FreeCamera.prototype.detachControl = function (element) {
  43773. this.inputs.detachElement(element);
  43774. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43775. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43776. };
  43777. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43778. get: function () {
  43779. return this._collisionMask;
  43780. },
  43781. set: function (mask) {
  43782. this._collisionMask = !isNaN(mask) ? mask : -1;
  43783. },
  43784. enumerable: true,
  43785. configurable: true
  43786. });
  43787. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43788. var globalPosition;
  43789. if (this.parent) {
  43790. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43791. }
  43792. else {
  43793. globalPosition = this.position;
  43794. }
  43795. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43796. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43797. if (!this._collider) {
  43798. this._collider = new BABYLON.Collider();
  43799. }
  43800. this._collider._radius = this.ellipsoid;
  43801. this._collider.collisionMask = this._collisionMask;
  43802. //no need for clone, as long as gravity is not on.
  43803. var actualDisplacement = displacement;
  43804. //add gravity to the direction to prevent the dual-collision checking
  43805. if (this.applyGravity) {
  43806. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43807. actualDisplacement = displacement.add(this.getScene().gravity);
  43808. }
  43809. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43810. };
  43811. FreeCamera.prototype._checkInputs = function () {
  43812. if (!this._localDirection) {
  43813. this._localDirection = BABYLON.Vector3.Zero();
  43814. this._transformedDirection = BABYLON.Vector3.Zero();
  43815. }
  43816. this.inputs.checkInputs();
  43817. _super.prototype._checkInputs.call(this);
  43818. };
  43819. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43820. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43821. };
  43822. FreeCamera.prototype._updatePosition = function () {
  43823. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43824. this._collideWithWorld(this.cameraDirection);
  43825. }
  43826. else {
  43827. _super.prototype._updatePosition.call(this);
  43828. }
  43829. };
  43830. FreeCamera.prototype.dispose = function () {
  43831. this.inputs.clear();
  43832. _super.prototype.dispose.call(this);
  43833. };
  43834. FreeCamera.prototype.getClassName = function () {
  43835. return "FreeCamera";
  43836. };
  43837. __decorate([
  43838. BABYLON.serializeAsVector3()
  43839. ], FreeCamera.prototype, "ellipsoid", void 0);
  43840. __decorate([
  43841. BABYLON.serializeAsVector3()
  43842. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43843. __decorate([
  43844. BABYLON.serialize()
  43845. ], FreeCamera.prototype, "checkCollisions", void 0);
  43846. __decorate([
  43847. BABYLON.serialize()
  43848. ], FreeCamera.prototype, "applyGravity", void 0);
  43849. return FreeCamera;
  43850. }(BABYLON.TargetCamera));
  43851. BABYLON.FreeCamera = FreeCamera;
  43852. })(BABYLON || (BABYLON = {}));
  43853. //# sourceMappingURL=babylon.freeCamera.js.map
  43854. var BABYLON;
  43855. (function (BABYLON) {
  43856. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43857. function ArcRotateCameraKeyboardMoveInput() {
  43858. this._keys = new Array();
  43859. this.keysUp = [38];
  43860. this.keysDown = [40];
  43861. this.keysLeft = [37];
  43862. this.keysRight = [39];
  43863. this.keysReset = [220];
  43864. this.panningSensibility = 50.0;
  43865. this.zoomingSensibility = 25.0;
  43866. this.useAltToZoom = true;
  43867. }
  43868. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43869. var _this = this;
  43870. if (this._onCanvasBlurObserver) {
  43871. return;
  43872. }
  43873. this._scene = this.camera.getScene();
  43874. this._engine = this._scene.getEngine();
  43875. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43876. _this._keys = [];
  43877. });
  43878. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43879. var evt = info.event;
  43880. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43881. _this._ctrlPressed = evt.ctrlKey;
  43882. _this._altPressed = evt.altKey;
  43883. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43884. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43885. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43886. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43887. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43888. var index = _this._keys.indexOf(evt.keyCode);
  43889. if (index === -1) {
  43890. _this._keys.push(evt.keyCode);
  43891. }
  43892. if (evt.preventDefault) {
  43893. if (!noPreventDefault) {
  43894. evt.preventDefault();
  43895. }
  43896. }
  43897. }
  43898. }
  43899. else {
  43900. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43901. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43902. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43903. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43904. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43905. var index = _this._keys.indexOf(evt.keyCode);
  43906. if (index >= 0) {
  43907. _this._keys.splice(index, 1);
  43908. }
  43909. if (evt.preventDefault) {
  43910. if (!noPreventDefault) {
  43911. evt.preventDefault();
  43912. }
  43913. }
  43914. }
  43915. }
  43916. });
  43917. };
  43918. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43919. if (this._scene) {
  43920. if (this._onKeyboardObserver) {
  43921. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43922. }
  43923. if (this._onCanvasBlurObserver) {
  43924. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43925. }
  43926. this._onKeyboardObserver = null;
  43927. this._onCanvasBlurObserver = null;
  43928. }
  43929. this._keys = [];
  43930. };
  43931. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43932. if (this._onKeyboardObserver) {
  43933. var camera = this.camera;
  43934. for (var index = 0; index < this._keys.length; index++) {
  43935. var keyCode = this._keys[index];
  43936. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43937. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43938. camera.inertialPanningX -= 1 / this.panningSensibility;
  43939. }
  43940. else {
  43941. camera.inertialAlphaOffset -= 0.01;
  43942. }
  43943. }
  43944. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43945. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43946. camera.inertialPanningY += 1 / this.panningSensibility;
  43947. }
  43948. else if (this._altPressed && this.useAltToZoom) {
  43949. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43950. }
  43951. else {
  43952. camera.inertialBetaOffset -= 0.01;
  43953. }
  43954. }
  43955. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43956. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43957. camera.inertialPanningX += 1 / this.panningSensibility;
  43958. }
  43959. else {
  43960. camera.inertialAlphaOffset += 0.01;
  43961. }
  43962. }
  43963. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43964. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43965. camera.inertialPanningY -= 1 / this.panningSensibility;
  43966. }
  43967. else if (this._altPressed && this.useAltToZoom) {
  43968. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43969. }
  43970. else {
  43971. camera.inertialBetaOffset += 0.01;
  43972. }
  43973. }
  43974. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43975. camera.restoreState();
  43976. }
  43977. }
  43978. }
  43979. };
  43980. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43981. return "ArcRotateCameraKeyboardMoveInput";
  43982. };
  43983. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43984. return "keyboard";
  43985. };
  43986. __decorate([
  43987. BABYLON.serialize()
  43988. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43989. __decorate([
  43990. BABYLON.serialize()
  43991. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43992. __decorate([
  43993. BABYLON.serialize()
  43994. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43995. __decorate([
  43996. BABYLON.serialize()
  43997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43998. __decorate([
  43999. BABYLON.serialize()
  44000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44001. __decorate([
  44002. BABYLON.serialize()
  44003. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44004. __decorate([
  44005. BABYLON.serialize()
  44006. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44007. __decorate([
  44008. BABYLON.serialize()
  44009. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44010. return ArcRotateCameraKeyboardMoveInput;
  44011. }());
  44012. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44013. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44014. })(BABYLON || (BABYLON = {}));
  44015. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44016. var BABYLON;
  44017. (function (BABYLON) {
  44018. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44019. function ArcRotateCameraMouseWheelInput() {
  44020. this.wheelPrecision = 3.0;
  44021. /**
  44022. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44023. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44024. */
  44025. this.wheelDeltaPercentage = 0;
  44026. }
  44027. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44028. var _this = this;
  44029. this._wheel = function (p, s) {
  44030. //sanity check - this should be a PointerWheel event.
  44031. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44032. return;
  44033. var event = p.event;
  44034. var delta = 0;
  44035. if (event.wheelDelta) {
  44036. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44037. }
  44038. else if (event.detail) {
  44039. delta = -event.detail / _this.wheelPrecision;
  44040. }
  44041. if (delta)
  44042. _this.camera.inertialRadiusOffset += delta;
  44043. if (event.preventDefault) {
  44044. if (!noPreventDefault) {
  44045. event.preventDefault();
  44046. }
  44047. }
  44048. };
  44049. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44050. };
  44051. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44052. if (this._observer && element) {
  44053. this.camera.getScene().onPointerObservable.remove(this._observer);
  44054. this._observer = null;
  44055. this._wheel = null;
  44056. }
  44057. };
  44058. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44059. return "ArcRotateCameraMouseWheelInput";
  44060. };
  44061. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44062. return "mousewheel";
  44063. };
  44064. __decorate([
  44065. BABYLON.serialize()
  44066. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44067. __decorate([
  44068. BABYLON.serialize()
  44069. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44070. return ArcRotateCameraMouseWheelInput;
  44071. }());
  44072. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44073. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44074. })(BABYLON || (BABYLON = {}));
  44075. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44076. var BABYLON;
  44077. (function (BABYLON) {
  44078. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44079. function ArcRotateCameraPointersInput() {
  44080. this.buttons = [0, 1, 2];
  44081. this.angularSensibilityX = 1000.0;
  44082. this.angularSensibilityY = 1000.0;
  44083. this.pinchPrecision = 12.0;
  44084. /**
  44085. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44086. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44087. */
  44088. this.pinchDeltaPercentage = 0;
  44089. this.panningSensibility = 1000.0;
  44090. this.multiTouchPanning = true;
  44091. this.multiTouchPanAndZoom = true;
  44092. this._isPanClick = false;
  44093. this.pinchInwards = true;
  44094. }
  44095. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44096. var _this = this;
  44097. var engine = this.camera.getEngine();
  44098. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44099. var pointA = null;
  44100. var pointB = null;
  44101. var previousPinchSquaredDistance = 0;
  44102. var initialDistance = 0;
  44103. var twoFingerActivityCount = 0;
  44104. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44105. this._pointerInput = function (p, s) {
  44106. var evt = p.event;
  44107. var isTouch = p.event.pointerType === "touch";
  44108. if (engine.isInVRExclusivePointerMode) {
  44109. return;
  44110. }
  44111. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44112. return;
  44113. }
  44114. var srcElement = (evt.srcElement || evt.target);
  44115. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44116. try {
  44117. srcElement.setPointerCapture(evt.pointerId);
  44118. }
  44119. catch (e) {
  44120. //Nothing to do with the error. Execution will continue.
  44121. }
  44122. // Manage panning with pan button click
  44123. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44124. // manage pointers
  44125. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44126. if (pointA === null) {
  44127. pointA = cacheSoloPointer;
  44128. }
  44129. else if (pointB === null) {
  44130. pointB = cacheSoloPointer;
  44131. }
  44132. if (!noPreventDefault) {
  44133. evt.preventDefault();
  44134. element.focus();
  44135. }
  44136. }
  44137. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44138. _this.camera.restoreState();
  44139. }
  44140. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44141. try {
  44142. srcElement.releasePointerCapture(evt.pointerId);
  44143. }
  44144. catch (e) {
  44145. //Nothing to do with the error.
  44146. }
  44147. cacheSoloPointer = null;
  44148. previousPinchSquaredDistance = 0;
  44149. previousMultiTouchPanPosition.isPaning = false;
  44150. previousMultiTouchPanPosition.isPinching = false;
  44151. twoFingerActivityCount = 0;
  44152. initialDistance = 0;
  44153. if (!isTouch) {
  44154. pointB = null; // Mouse and pen are mono pointer
  44155. }
  44156. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44157. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44158. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44159. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44160. if (engine.badOS) {
  44161. pointA = pointB = null;
  44162. }
  44163. else {
  44164. //only remove the impacted pointer in case of multitouch allowing on most
  44165. //platforms switching from rotate to zoom and pan seamlessly.
  44166. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44167. pointA = pointB;
  44168. pointB = null;
  44169. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44170. }
  44171. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44172. pointB = null;
  44173. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44174. }
  44175. else {
  44176. pointA = pointB = null;
  44177. }
  44178. }
  44179. if (!noPreventDefault) {
  44180. evt.preventDefault();
  44181. }
  44182. }
  44183. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44184. if (!noPreventDefault) {
  44185. evt.preventDefault();
  44186. }
  44187. // One button down
  44188. if (pointA && pointB === null && cacheSoloPointer) {
  44189. if (_this.panningSensibility !== 0 &&
  44190. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44191. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44192. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44193. }
  44194. else {
  44195. var offsetX = evt.clientX - cacheSoloPointer.x;
  44196. var offsetY = evt.clientY - cacheSoloPointer.y;
  44197. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44198. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44199. }
  44200. cacheSoloPointer.x = evt.clientX;
  44201. cacheSoloPointer.y = evt.clientY;
  44202. }
  44203. else if (pointA && pointB) {
  44204. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44205. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44206. ed.x = evt.clientX;
  44207. ed.y = evt.clientY;
  44208. var direction = _this.pinchInwards ? 1 : -1;
  44209. var distX = pointA.x - pointB.x;
  44210. var distY = pointA.y - pointB.y;
  44211. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44212. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44213. if (previousPinchSquaredDistance === 0) {
  44214. initialDistance = pinchDistance;
  44215. previousPinchSquaredDistance = pinchSquaredDistance;
  44216. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44217. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44218. return;
  44219. }
  44220. if (_this.multiTouchPanAndZoom) {
  44221. if (_this.pinchDeltaPercentage) {
  44222. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44223. }
  44224. else {
  44225. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44226. (_this.pinchPrecision *
  44227. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44228. direction);
  44229. }
  44230. if (_this.panningSensibility !== 0) {
  44231. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44232. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44233. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44234. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44235. previousMultiTouchPanPosition.x = pointersCenterX;
  44236. previousMultiTouchPanPosition.y = pointersCenterY;
  44237. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44238. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44239. }
  44240. }
  44241. else {
  44242. twoFingerActivityCount++;
  44243. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44244. if (_this.pinchDeltaPercentage) {
  44245. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44246. }
  44247. else {
  44248. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44249. (_this.pinchPrecision *
  44250. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44251. direction);
  44252. }
  44253. previousMultiTouchPanPosition.isPaning = false;
  44254. previousMultiTouchPanPosition.isPinching = true;
  44255. }
  44256. else {
  44257. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44258. if (!previousMultiTouchPanPosition.isPaning) {
  44259. previousMultiTouchPanPosition.isPaning = true;
  44260. previousMultiTouchPanPosition.isPinching = false;
  44261. previousMultiTouchPanPosition.x = ed.x;
  44262. previousMultiTouchPanPosition.y = ed.y;
  44263. return;
  44264. }
  44265. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44266. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44267. }
  44268. }
  44269. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44270. previousMultiTouchPanPosition.x = ed.x;
  44271. previousMultiTouchPanPosition.y = ed.y;
  44272. }
  44273. }
  44274. previousPinchSquaredDistance = pinchSquaredDistance;
  44275. }
  44276. }
  44277. };
  44278. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44279. this._onContextMenu = function (evt) {
  44280. evt.preventDefault();
  44281. };
  44282. if (!this.camera._useCtrlForPanning) {
  44283. element.addEventListener("contextmenu", this._onContextMenu, false);
  44284. }
  44285. this._onLostFocus = function () {
  44286. //this._keys = [];
  44287. pointA = pointB = null;
  44288. previousPinchSquaredDistance = 0;
  44289. previousMultiTouchPanPosition.isPaning = false;
  44290. previousMultiTouchPanPosition.isPinching = false;
  44291. twoFingerActivityCount = 0;
  44292. cacheSoloPointer = null;
  44293. initialDistance = 0;
  44294. };
  44295. this._onMouseMove = function (evt) {
  44296. if (!engine.isPointerLock) {
  44297. return;
  44298. }
  44299. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44300. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44301. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44302. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44303. if (!noPreventDefault) {
  44304. evt.preventDefault();
  44305. }
  44306. };
  44307. this._onGestureStart = function (e) {
  44308. if (window.MSGesture === undefined) {
  44309. return;
  44310. }
  44311. if (!_this._MSGestureHandler) {
  44312. _this._MSGestureHandler = new MSGesture();
  44313. _this._MSGestureHandler.target = element;
  44314. }
  44315. _this._MSGestureHandler.addPointer(e.pointerId);
  44316. };
  44317. this._onGesture = function (e) {
  44318. _this.camera.radius *= e.scale;
  44319. if (e.preventDefault) {
  44320. if (!noPreventDefault) {
  44321. e.stopPropagation();
  44322. e.preventDefault();
  44323. }
  44324. }
  44325. };
  44326. element.addEventListener("mousemove", this._onMouseMove, false);
  44327. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44328. element.addEventListener("MSGestureChange", this._onGesture, false);
  44329. BABYLON.Tools.RegisterTopRootEvents([
  44330. { name: "blur", handler: this._onLostFocus }
  44331. ]);
  44332. };
  44333. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44334. if (this._onLostFocus) {
  44335. BABYLON.Tools.UnregisterTopRootEvents([
  44336. { name: "blur", handler: this._onLostFocus }
  44337. ]);
  44338. }
  44339. if (element && this._observer) {
  44340. this.camera.getScene().onPointerObservable.remove(this._observer);
  44341. this._observer = null;
  44342. if (this._onContextMenu) {
  44343. element.removeEventListener("contextmenu", this._onContextMenu);
  44344. }
  44345. if (this._onMouseMove) {
  44346. element.removeEventListener("mousemove", this._onMouseMove);
  44347. }
  44348. if (this._onGestureStart) {
  44349. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44350. }
  44351. if (this._onGesture) {
  44352. element.removeEventListener("MSGestureChange", this._onGesture);
  44353. }
  44354. this._isPanClick = false;
  44355. this.pinchInwards = true;
  44356. this._onMouseMove = null;
  44357. this._onGestureStart = null;
  44358. this._onGesture = null;
  44359. this._MSGestureHandler = null;
  44360. this._onLostFocus = null;
  44361. this._onContextMenu = null;
  44362. }
  44363. };
  44364. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44365. return "ArcRotateCameraPointersInput";
  44366. };
  44367. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44368. return "pointers";
  44369. };
  44370. __decorate([
  44371. BABYLON.serialize()
  44372. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44373. __decorate([
  44374. BABYLON.serialize()
  44375. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44376. __decorate([
  44377. BABYLON.serialize()
  44378. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44379. __decorate([
  44380. BABYLON.serialize()
  44381. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44382. __decorate([
  44383. BABYLON.serialize()
  44384. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44385. __decorate([
  44386. BABYLON.serialize()
  44387. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44388. __decorate([
  44389. BABYLON.serialize()
  44390. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44391. __decorate([
  44392. BABYLON.serialize()
  44393. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44394. return ArcRotateCameraPointersInput;
  44395. }());
  44396. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44397. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44398. })(BABYLON || (BABYLON = {}));
  44399. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44400. var BABYLON;
  44401. (function (BABYLON) {
  44402. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44403. __extends(ArcRotateCameraInputsManager, _super);
  44404. function ArcRotateCameraInputsManager(camera) {
  44405. return _super.call(this, camera) || this;
  44406. }
  44407. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44408. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44409. return this;
  44410. };
  44411. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44412. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44413. return this;
  44414. };
  44415. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44416. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44417. return this;
  44418. };
  44419. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44420. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44421. return this;
  44422. };
  44423. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44424. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44425. return this;
  44426. };
  44427. return ArcRotateCameraInputsManager;
  44428. }(BABYLON.CameraInputsManager));
  44429. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44430. })(BABYLON || (BABYLON = {}));
  44431. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44432. var BABYLON;
  44433. (function (BABYLON) {
  44434. var ArcRotateCamera = /** @class */ (function (_super) {
  44435. __extends(ArcRotateCamera, _super);
  44436. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44437. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44438. _this.inertialAlphaOffset = 0;
  44439. _this.inertialBetaOffset = 0;
  44440. _this.inertialRadiusOffset = 0;
  44441. _this.lowerAlphaLimit = null;
  44442. _this.upperAlphaLimit = null;
  44443. _this.lowerBetaLimit = 0.01;
  44444. _this.upperBetaLimit = Math.PI;
  44445. _this.lowerRadiusLimit = null;
  44446. _this.upperRadiusLimit = null;
  44447. _this.inertialPanningX = 0;
  44448. _this.inertialPanningY = 0;
  44449. _this.pinchToPanMaxDistance = 20;
  44450. _this.panningDistanceLimit = null;
  44451. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44452. _this.panningInertia = 0.9;
  44453. //-- end properties for backward compatibility for inputs
  44454. _this.zoomOnFactor = 1;
  44455. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44456. _this.allowUpsideDown = true;
  44457. _this._viewMatrix = new BABYLON.Matrix();
  44458. // Panning
  44459. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44460. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44461. _this.checkCollisions = false;
  44462. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44463. _this._previousPosition = BABYLON.Vector3.Zero();
  44464. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44465. _this._newPosition = BABYLON.Vector3.Zero();
  44466. _this._computationVector = BABYLON.Vector3.Zero();
  44467. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44468. if (collidedMesh === void 0) { collidedMesh = null; }
  44469. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44470. newPosition.multiplyInPlace(_this._collider._radius);
  44471. }
  44472. if (!collidedMesh) {
  44473. _this._previousPosition.copyFrom(_this.position);
  44474. }
  44475. else {
  44476. _this.setPosition(newPosition);
  44477. if (_this.onCollide) {
  44478. _this.onCollide(collidedMesh);
  44479. }
  44480. }
  44481. // Recompute because of constraints
  44482. var cosa = Math.cos(_this.alpha);
  44483. var sina = Math.sin(_this.alpha);
  44484. var cosb = Math.cos(_this.beta);
  44485. var sinb = Math.sin(_this.beta);
  44486. if (sinb === 0) {
  44487. sinb = 0.0001;
  44488. }
  44489. var target = _this._getTargetPosition();
  44490. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44491. target.addToRef(_this._computationVector, _this._newPosition);
  44492. _this.position.copyFrom(_this._newPosition);
  44493. var up = _this.upVector;
  44494. if (_this.allowUpsideDown && _this.beta < 0) {
  44495. up = up.clone();
  44496. up = up.negate();
  44497. }
  44498. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44499. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44500. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44501. _this._collisionTriggered = false;
  44502. };
  44503. _this._target = BABYLON.Vector3.Zero();
  44504. if (target) {
  44505. _this.setTarget(target);
  44506. }
  44507. _this.alpha = alpha;
  44508. _this.beta = beta;
  44509. _this.radius = radius;
  44510. _this.getViewMatrix();
  44511. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44512. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44513. return _this;
  44514. }
  44515. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44516. get: function () {
  44517. return this._target;
  44518. },
  44519. set: function (value) {
  44520. this.setTarget(value);
  44521. },
  44522. enumerable: true,
  44523. configurable: true
  44524. });
  44525. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44526. //-- begin properties for backward compatibility for inputs
  44527. get: function () {
  44528. var pointers = this.inputs.attached["pointers"];
  44529. if (pointers)
  44530. return pointers.angularSensibilityX;
  44531. return 0;
  44532. },
  44533. set: function (value) {
  44534. var pointers = this.inputs.attached["pointers"];
  44535. if (pointers) {
  44536. pointers.angularSensibilityX = value;
  44537. }
  44538. },
  44539. enumerable: true,
  44540. configurable: true
  44541. });
  44542. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44543. get: function () {
  44544. var pointers = this.inputs.attached["pointers"];
  44545. if (pointers)
  44546. return pointers.angularSensibilityY;
  44547. return 0;
  44548. },
  44549. set: function (value) {
  44550. var pointers = this.inputs.attached["pointers"];
  44551. if (pointers) {
  44552. pointers.angularSensibilityY = value;
  44553. }
  44554. },
  44555. enumerable: true,
  44556. configurable: true
  44557. });
  44558. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44559. get: function () {
  44560. var pointers = this.inputs.attached["pointers"];
  44561. if (pointers)
  44562. return pointers.pinchPrecision;
  44563. return 0;
  44564. },
  44565. set: function (value) {
  44566. var pointers = this.inputs.attached["pointers"];
  44567. if (pointers) {
  44568. pointers.pinchPrecision = value;
  44569. }
  44570. },
  44571. enumerable: true,
  44572. configurable: true
  44573. });
  44574. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44575. get: function () {
  44576. var pointers = this.inputs.attached["pointers"];
  44577. if (pointers)
  44578. return pointers.pinchDeltaPercentage;
  44579. return 0;
  44580. },
  44581. set: function (value) {
  44582. var pointers = this.inputs.attached["pointers"];
  44583. if (pointers) {
  44584. pointers.pinchDeltaPercentage = value;
  44585. }
  44586. },
  44587. enumerable: true,
  44588. configurable: true
  44589. });
  44590. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44591. get: function () {
  44592. var pointers = this.inputs.attached["pointers"];
  44593. if (pointers)
  44594. return pointers.panningSensibility;
  44595. return 0;
  44596. },
  44597. set: function (value) {
  44598. var pointers = this.inputs.attached["pointers"];
  44599. if (pointers) {
  44600. pointers.panningSensibility = value;
  44601. }
  44602. },
  44603. enumerable: true,
  44604. configurable: true
  44605. });
  44606. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44607. get: function () {
  44608. var keyboard = this.inputs.attached["keyboard"];
  44609. if (keyboard)
  44610. return keyboard.keysUp;
  44611. return [];
  44612. },
  44613. set: function (value) {
  44614. var keyboard = this.inputs.attached["keyboard"];
  44615. if (keyboard)
  44616. keyboard.keysUp = value;
  44617. },
  44618. enumerable: true,
  44619. configurable: true
  44620. });
  44621. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44622. get: function () {
  44623. var keyboard = this.inputs.attached["keyboard"];
  44624. if (keyboard)
  44625. return keyboard.keysDown;
  44626. return [];
  44627. },
  44628. set: function (value) {
  44629. var keyboard = this.inputs.attached["keyboard"];
  44630. if (keyboard)
  44631. keyboard.keysDown = value;
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44637. get: function () {
  44638. var keyboard = this.inputs.attached["keyboard"];
  44639. if (keyboard)
  44640. return keyboard.keysLeft;
  44641. return [];
  44642. },
  44643. set: function (value) {
  44644. var keyboard = this.inputs.attached["keyboard"];
  44645. if (keyboard)
  44646. keyboard.keysLeft = value;
  44647. },
  44648. enumerable: true,
  44649. configurable: true
  44650. });
  44651. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44652. get: function () {
  44653. var keyboard = this.inputs.attached["keyboard"];
  44654. if (keyboard)
  44655. return keyboard.keysRight;
  44656. return [];
  44657. },
  44658. set: function (value) {
  44659. var keyboard = this.inputs.attached["keyboard"];
  44660. if (keyboard)
  44661. keyboard.keysRight = value;
  44662. },
  44663. enumerable: true,
  44664. configurable: true
  44665. });
  44666. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44667. get: function () {
  44668. var mousewheel = this.inputs.attached["mousewheel"];
  44669. if (mousewheel)
  44670. return mousewheel.wheelPrecision;
  44671. return 0;
  44672. },
  44673. set: function (value) {
  44674. var mousewheel = this.inputs.attached["mousewheel"];
  44675. if (mousewheel)
  44676. mousewheel.wheelPrecision = value;
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44682. get: function () {
  44683. var mousewheel = this.inputs.attached["mousewheel"];
  44684. if (mousewheel)
  44685. return mousewheel.wheelDeltaPercentage;
  44686. return 0;
  44687. },
  44688. set: function (value) {
  44689. var mousewheel = this.inputs.attached["mousewheel"];
  44690. if (mousewheel)
  44691. mousewheel.wheelDeltaPercentage = value;
  44692. },
  44693. enumerable: true,
  44694. configurable: true
  44695. });
  44696. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44697. get: function () {
  44698. return this._bouncingBehavior;
  44699. },
  44700. enumerable: true,
  44701. configurable: true
  44702. });
  44703. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44704. get: function () {
  44705. return this._bouncingBehavior != null;
  44706. },
  44707. set: function (value) {
  44708. if (value === this.useBouncingBehavior) {
  44709. return;
  44710. }
  44711. if (value) {
  44712. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44713. this.addBehavior(this._bouncingBehavior);
  44714. }
  44715. else if (this._bouncingBehavior) {
  44716. this.removeBehavior(this._bouncingBehavior);
  44717. this._bouncingBehavior = null;
  44718. }
  44719. },
  44720. enumerable: true,
  44721. configurable: true
  44722. });
  44723. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44724. get: function () {
  44725. return this._framingBehavior;
  44726. },
  44727. enumerable: true,
  44728. configurable: true
  44729. });
  44730. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44731. get: function () {
  44732. return this._framingBehavior != null;
  44733. },
  44734. set: function (value) {
  44735. if (value === this.useFramingBehavior) {
  44736. return;
  44737. }
  44738. if (value) {
  44739. this._framingBehavior = new BABYLON.FramingBehavior();
  44740. this.addBehavior(this._framingBehavior);
  44741. }
  44742. else if (this._framingBehavior) {
  44743. this.removeBehavior(this._framingBehavior);
  44744. this._framingBehavior = null;
  44745. }
  44746. },
  44747. enumerable: true,
  44748. configurable: true
  44749. });
  44750. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44751. get: function () {
  44752. return this._autoRotationBehavior;
  44753. },
  44754. enumerable: true,
  44755. configurable: true
  44756. });
  44757. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44758. get: function () {
  44759. return this._autoRotationBehavior != null;
  44760. },
  44761. set: function (value) {
  44762. if (value === this.useAutoRotationBehavior) {
  44763. return;
  44764. }
  44765. if (value) {
  44766. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44767. this.addBehavior(this._autoRotationBehavior);
  44768. }
  44769. else if (this._autoRotationBehavior) {
  44770. this.removeBehavior(this._autoRotationBehavior);
  44771. this._autoRotationBehavior = null;
  44772. }
  44773. },
  44774. enumerable: true,
  44775. configurable: true
  44776. });
  44777. // Cache
  44778. ArcRotateCamera.prototype._initCache = function () {
  44779. _super.prototype._initCache.call(this);
  44780. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44781. this._cache.alpha = undefined;
  44782. this._cache.beta = undefined;
  44783. this._cache.radius = undefined;
  44784. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44785. };
  44786. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44787. if (!ignoreParentClass) {
  44788. _super.prototype._updateCache.call(this);
  44789. }
  44790. this._cache._target.copyFrom(this._getTargetPosition());
  44791. this._cache.alpha = this.alpha;
  44792. this._cache.beta = this.beta;
  44793. this._cache.radius = this.radius;
  44794. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44795. };
  44796. ArcRotateCamera.prototype._getTargetPosition = function () {
  44797. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44798. var pos = this._targetHost.getAbsolutePosition();
  44799. if (this._targetBoundingCenter) {
  44800. pos.addToRef(this._targetBoundingCenter, this._target);
  44801. }
  44802. else {
  44803. this._target.copyFrom(pos);
  44804. }
  44805. }
  44806. var lockedTargetPosition = this._getLockedTargetPosition();
  44807. if (lockedTargetPosition) {
  44808. return lockedTargetPosition;
  44809. }
  44810. return this._target;
  44811. };
  44812. ArcRotateCamera.prototype.storeState = function () {
  44813. this._storedAlpha = this.alpha;
  44814. this._storedBeta = this.beta;
  44815. this._storedRadius = this.radius;
  44816. this._storedTarget = this._getTargetPosition().clone();
  44817. return _super.prototype.storeState.call(this);
  44818. };
  44819. /**
  44820. * Restored camera state. You must call storeState() first
  44821. */
  44822. ArcRotateCamera.prototype._restoreStateValues = function () {
  44823. if (!_super.prototype._restoreStateValues.call(this)) {
  44824. return false;
  44825. }
  44826. this.alpha = this._storedAlpha;
  44827. this.beta = this._storedBeta;
  44828. this.radius = this._storedRadius;
  44829. this.setTarget(this._storedTarget.clone());
  44830. this.inertialAlphaOffset = 0;
  44831. this.inertialBetaOffset = 0;
  44832. this.inertialRadiusOffset = 0;
  44833. this.inertialPanningX = 0;
  44834. this.inertialPanningY = 0;
  44835. return true;
  44836. };
  44837. // Synchronized
  44838. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44839. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44840. return false;
  44841. return this._cache._target.equals(this._getTargetPosition())
  44842. && this._cache.alpha === this.alpha
  44843. && this._cache.beta === this.beta
  44844. && this._cache.radius === this.radius
  44845. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44846. };
  44847. // Methods
  44848. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44849. var _this = this;
  44850. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44851. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44852. this._useCtrlForPanning = useCtrlForPanning;
  44853. this._panningMouseButton = panningMouseButton;
  44854. this.inputs.attachElement(element, noPreventDefault);
  44855. this._reset = function () {
  44856. _this.inertialAlphaOffset = 0;
  44857. _this.inertialBetaOffset = 0;
  44858. _this.inertialRadiusOffset = 0;
  44859. _this.inertialPanningX = 0;
  44860. _this.inertialPanningY = 0;
  44861. };
  44862. };
  44863. ArcRotateCamera.prototype.detachControl = function (element) {
  44864. this.inputs.detachElement(element);
  44865. if (this._reset) {
  44866. this._reset();
  44867. }
  44868. };
  44869. ArcRotateCamera.prototype._checkInputs = function () {
  44870. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44871. if (this._collisionTriggered) {
  44872. return;
  44873. }
  44874. this.inputs.checkInputs();
  44875. // Inertia
  44876. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44877. if (this.getScene().useRightHandedSystem) {
  44878. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44879. }
  44880. else {
  44881. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44882. }
  44883. this.beta += this.inertialBetaOffset;
  44884. this.radius -= this.inertialRadiusOffset;
  44885. this.inertialAlphaOffset *= this.inertia;
  44886. this.inertialBetaOffset *= this.inertia;
  44887. this.inertialRadiusOffset *= this.inertia;
  44888. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44889. this.inertialAlphaOffset = 0;
  44890. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44891. this.inertialBetaOffset = 0;
  44892. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44893. this.inertialRadiusOffset = 0;
  44894. }
  44895. // Panning inertia
  44896. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44897. if (!this._localDirection) {
  44898. this._localDirection = BABYLON.Vector3.Zero();
  44899. this._transformedDirection = BABYLON.Vector3.Zero();
  44900. }
  44901. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44902. this._localDirection.multiplyInPlace(this.panningAxis);
  44903. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44904. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44905. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44906. if (!this.panningAxis.y) {
  44907. this._transformedDirection.y = 0;
  44908. }
  44909. if (!this._targetHost) {
  44910. if (this.panningDistanceLimit) {
  44911. this._transformedDirection.addInPlace(this._target);
  44912. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44913. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44914. this._target.copyFrom(this._transformedDirection);
  44915. }
  44916. }
  44917. else {
  44918. this._target.addInPlace(this._transformedDirection);
  44919. }
  44920. }
  44921. this.inertialPanningX *= this.panningInertia;
  44922. this.inertialPanningY *= this.panningInertia;
  44923. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44924. this.inertialPanningX = 0;
  44925. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44926. this.inertialPanningY = 0;
  44927. }
  44928. // Limits
  44929. this._checkLimits();
  44930. _super.prototype._checkInputs.call(this);
  44931. };
  44932. ArcRotateCamera.prototype._checkLimits = function () {
  44933. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44934. if (this.allowUpsideDown && this.beta > Math.PI) {
  44935. this.beta = this.beta - (2 * Math.PI);
  44936. }
  44937. }
  44938. else {
  44939. if (this.beta < this.lowerBetaLimit) {
  44940. this.beta = this.lowerBetaLimit;
  44941. }
  44942. }
  44943. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44944. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44945. this.beta = this.beta + (2 * Math.PI);
  44946. }
  44947. }
  44948. else {
  44949. if (this.beta > this.upperBetaLimit) {
  44950. this.beta = this.upperBetaLimit;
  44951. }
  44952. }
  44953. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44954. this.alpha = this.lowerAlphaLimit;
  44955. }
  44956. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44957. this.alpha = this.upperAlphaLimit;
  44958. }
  44959. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44960. this.radius = this.lowerRadiusLimit;
  44961. }
  44962. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44963. this.radius = this.upperRadiusLimit;
  44964. }
  44965. };
  44966. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44967. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  44968. this.radius = this._computationVector.length();
  44969. if (this.radius === 0) {
  44970. this.radius = 0.0001; // Just to avoid division by zero
  44971. }
  44972. // Alpha
  44973. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  44974. if (this._computationVector.z < 0) {
  44975. this.alpha = 2 * Math.PI - this.alpha;
  44976. }
  44977. // Beta
  44978. this.beta = Math.acos(this._computationVector.y / this.radius);
  44979. this._checkLimits();
  44980. };
  44981. ArcRotateCamera.prototype.setPosition = function (position) {
  44982. if (this.position.equals(position)) {
  44983. return;
  44984. }
  44985. this.position.copyFrom(position);
  44986. this.rebuildAnglesAndRadius();
  44987. };
  44988. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44989. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44990. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44991. if (target.getBoundingInfo) {
  44992. if (toBoundingCenter) {
  44993. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44994. }
  44995. else {
  44996. this._targetBoundingCenter = null;
  44997. }
  44998. this._targetHost = target;
  44999. this._target = this._getTargetPosition();
  45000. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45001. }
  45002. else {
  45003. var newTarget = target;
  45004. var currentTarget = this._getTargetPosition();
  45005. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45006. return;
  45007. }
  45008. this._targetHost = null;
  45009. this._target = newTarget;
  45010. this._targetBoundingCenter = null;
  45011. this.onMeshTargetChangedObservable.notifyObservers(null);
  45012. }
  45013. this.rebuildAnglesAndRadius();
  45014. };
  45015. ArcRotateCamera.prototype._getViewMatrix = function () {
  45016. // Compute
  45017. var cosa = Math.cos(this.alpha);
  45018. var sina = Math.sin(this.alpha);
  45019. var cosb = Math.cos(this.beta);
  45020. var sinb = Math.sin(this.beta);
  45021. if (sinb === 0) {
  45022. sinb = 0.0001;
  45023. }
  45024. var target = this._getTargetPosition();
  45025. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45026. target.addToRef(this._computationVector, this._newPosition);
  45027. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45028. if (!this._collider) {
  45029. this._collider = new BABYLON.Collider();
  45030. }
  45031. this._collider._radius = this.collisionRadius;
  45032. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45033. this._collisionTriggered = true;
  45034. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45035. }
  45036. else {
  45037. this.position.copyFrom(this._newPosition);
  45038. var up = this.upVector;
  45039. if (this.allowUpsideDown && sinb < 0) {
  45040. up = up.clone();
  45041. up = up.negate();
  45042. }
  45043. if (this.getScene().useRightHandedSystem) {
  45044. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45045. }
  45046. else {
  45047. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45048. }
  45049. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45050. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45051. }
  45052. this._currentTarget = target;
  45053. return this._viewMatrix;
  45054. };
  45055. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45056. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45057. meshes = meshes || this.getScene().meshes;
  45058. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45059. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45060. this.radius = distance * this.zoomOnFactor;
  45061. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45062. };
  45063. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45064. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45065. var meshesOrMinMaxVector;
  45066. var distance;
  45067. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45068. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45069. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45070. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45071. }
  45072. else {
  45073. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45074. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45075. distance = minMaxVectorAndDistance.distance;
  45076. }
  45077. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45078. if (!doNotUpdateMaxZ) {
  45079. this.maxZ = distance * 2;
  45080. }
  45081. };
  45082. /**
  45083. * @override
  45084. * Override Camera.createRigCamera
  45085. */
  45086. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45087. var alphaShift = 0;
  45088. switch (this.cameraRigMode) {
  45089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45092. case BABYLON.Camera.RIG_MODE_VR:
  45093. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45094. break;
  45095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45096. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45097. break;
  45098. }
  45099. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45100. rigCam._cameraRigParams = {};
  45101. return rigCam;
  45102. };
  45103. /**
  45104. * @override
  45105. * Override Camera._updateRigCameras
  45106. */
  45107. ArcRotateCamera.prototype._updateRigCameras = function () {
  45108. var camLeft = this._rigCameras[0];
  45109. var camRight = this._rigCameras[1];
  45110. camLeft.beta = camRight.beta = this.beta;
  45111. camLeft.radius = camRight.radius = this.radius;
  45112. switch (this.cameraRigMode) {
  45113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45116. case BABYLON.Camera.RIG_MODE_VR:
  45117. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45118. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45119. break;
  45120. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45121. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45122. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45123. break;
  45124. }
  45125. _super.prototype._updateRigCameras.call(this);
  45126. };
  45127. ArcRotateCamera.prototype.dispose = function () {
  45128. this.inputs.clear();
  45129. _super.prototype.dispose.call(this);
  45130. };
  45131. ArcRotateCamera.prototype.getClassName = function () {
  45132. return "ArcRotateCamera";
  45133. };
  45134. __decorate([
  45135. BABYLON.serialize()
  45136. ], ArcRotateCamera.prototype, "alpha", void 0);
  45137. __decorate([
  45138. BABYLON.serialize()
  45139. ], ArcRotateCamera.prototype, "beta", void 0);
  45140. __decorate([
  45141. BABYLON.serialize()
  45142. ], ArcRotateCamera.prototype, "radius", void 0);
  45143. __decorate([
  45144. BABYLON.serializeAsVector3("target")
  45145. ], ArcRotateCamera.prototype, "_target", void 0);
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45149. __decorate([
  45150. BABYLON.serialize()
  45151. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45152. __decorate([
  45153. BABYLON.serialize()
  45154. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45155. __decorate([
  45156. BABYLON.serialize()
  45157. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45158. __decorate([
  45159. BABYLON.serialize()
  45160. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45161. __decorate([
  45162. BABYLON.serialize()
  45163. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45164. __decorate([
  45165. BABYLON.serialize()
  45166. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45167. __decorate([
  45168. BABYLON.serialize()
  45169. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45170. __decorate([
  45171. BABYLON.serialize()
  45172. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45173. __decorate([
  45174. BABYLON.serialize()
  45175. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45176. __decorate([
  45177. BABYLON.serialize()
  45178. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45179. __decorate([
  45180. BABYLON.serialize()
  45181. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45182. __decorate([
  45183. BABYLON.serialize()
  45184. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45185. __decorate([
  45186. BABYLON.serializeAsVector3()
  45187. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45188. __decorate([
  45189. BABYLON.serialize()
  45190. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45191. __decorate([
  45192. BABYLON.serialize()
  45193. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45194. __decorate([
  45195. BABYLON.serialize()
  45196. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45197. return ArcRotateCamera;
  45198. }(BABYLON.TargetCamera));
  45199. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45200. })(BABYLON || (BABYLON = {}));
  45201. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45202. var BABYLON;
  45203. (function (BABYLON) {
  45204. /**
  45205. * The HemisphericLight simulates the ambient environment light,
  45206. * so the passed direction is the light reflection direction, not the incoming direction.
  45207. */
  45208. var HemisphericLight = /** @class */ (function (_super) {
  45209. __extends(HemisphericLight, _super);
  45210. /**
  45211. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45212. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45213. * The HemisphericLight can't cast shadows.
  45214. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45215. * @param name The friendly name of the light
  45216. * @param direction The direction of the light reflection
  45217. * @param scene The scene the light belongs to
  45218. */
  45219. function HemisphericLight(name, direction, scene) {
  45220. var _this = _super.call(this, name, scene) || this;
  45221. /**
  45222. * The groundColor is the light in the opposite direction to the one specified during creation.
  45223. * 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.
  45224. */
  45225. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45226. _this.direction = direction || BABYLON.Vector3.Up();
  45227. return _this;
  45228. }
  45229. HemisphericLight.prototype._buildUniformLayout = function () {
  45230. this._uniformBuffer.addUniform("vLightData", 4);
  45231. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45232. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45233. this._uniformBuffer.addUniform("vLightGround", 3);
  45234. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45235. this._uniformBuffer.addUniform("depthValues", 2);
  45236. this._uniformBuffer.create();
  45237. };
  45238. /**
  45239. * Returns the string "HemisphericLight".
  45240. * @return The class name
  45241. */
  45242. HemisphericLight.prototype.getClassName = function () {
  45243. return "HemisphericLight";
  45244. };
  45245. /**
  45246. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45247. * Returns the updated direction.
  45248. * @param target The target the direction should point to
  45249. * @return The computed direction
  45250. */
  45251. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45252. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45253. return this.direction;
  45254. };
  45255. /**
  45256. * Returns the shadow generator associated to the light.
  45257. * @returns Always null for hemispheric lights because it does not support shadows.
  45258. */
  45259. HemisphericLight.prototype.getShadowGenerator = function () {
  45260. return null;
  45261. };
  45262. /**
  45263. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45264. * @param effect The effect to update
  45265. * @param lightIndex The index of the light in the effect to update
  45266. * @returns The hemispheric light
  45267. */
  45268. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45269. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45270. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45271. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45272. return this;
  45273. };
  45274. /**
  45275. * @ignore internal use only.
  45276. */
  45277. HemisphericLight.prototype._getWorldMatrix = function () {
  45278. if (!this._worldMatrix) {
  45279. this._worldMatrix = BABYLON.Matrix.Identity();
  45280. }
  45281. return this._worldMatrix;
  45282. };
  45283. /**
  45284. * Returns the integer 3.
  45285. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45286. */
  45287. HemisphericLight.prototype.getTypeID = function () {
  45288. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45289. };
  45290. __decorate([
  45291. BABYLON.serializeAsColor3()
  45292. ], HemisphericLight.prototype, "groundColor", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsVector3()
  45295. ], HemisphericLight.prototype, "direction", void 0);
  45296. return HemisphericLight;
  45297. }(BABYLON.Light));
  45298. BABYLON.HemisphericLight = HemisphericLight;
  45299. })(BABYLON || (BABYLON = {}));
  45300. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45301. var BABYLON;
  45302. (function (BABYLON) {
  45303. /**
  45304. * Base implementation of @see IShadowLight
  45305. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45306. */
  45307. var ShadowLight = /** @class */ (function (_super) {
  45308. __extends(ShadowLight, _super);
  45309. function ShadowLight() {
  45310. var _this = _super !== null && _super.apply(this, arguments) || this;
  45311. _this._needProjectionMatrixCompute = true;
  45312. return _this;
  45313. }
  45314. ShadowLight.prototype._setPosition = function (value) {
  45315. this._position = value;
  45316. };
  45317. Object.defineProperty(ShadowLight.prototype, "position", {
  45318. /**
  45319. * Sets the position the shadow will be casted from. Also use as the light position for both
  45320. * point and spot lights.
  45321. */
  45322. get: function () {
  45323. return this._position;
  45324. },
  45325. /**
  45326. * Sets the position the shadow will be casted from. Also use as the light position for both
  45327. * point and spot lights.
  45328. */
  45329. set: function (value) {
  45330. this._setPosition(value);
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. ShadowLight.prototype._setDirection = function (value) {
  45336. this._direction = value;
  45337. };
  45338. Object.defineProperty(ShadowLight.prototype, "direction", {
  45339. /**
  45340. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45341. * Also use as the light direction on spot and directional lights.
  45342. */
  45343. get: function () {
  45344. return this._direction;
  45345. },
  45346. /**
  45347. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45348. * Also use as the light direction on spot and directional lights.
  45349. */
  45350. set: function (value) {
  45351. this._setDirection(value);
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45357. /**
  45358. * Gets the shadow projection clipping minimum z value.
  45359. */
  45360. get: function () {
  45361. return this._shadowMinZ;
  45362. },
  45363. /**
  45364. * Sets the shadow projection clipping minimum z value.
  45365. */
  45366. set: function (value) {
  45367. this._shadowMinZ = value;
  45368. this.forceProjectionMatrixCompute();
  45369. },
  45370. enumerable: true,
  45371. configurable: true
  45372. });
  45373. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45374. /**
  45375. * Sets the shadow projection clipping maximum z value.
  45376. */
  45377. get: function () {
  45378. return this._shadowMaxZ;
  45379. },
  45380. /**
  45381. * Gets the shadow projection clipping maximum z value.
  45382. */
  45383. set: function (value) {
  45384. this._shadowMaxZ = value;
  45385. this.forceProjectionMatrixCompute();
  45386. },
  45387. enumerable: true,
  45388. configurable: true
  45389. });
  45390. /**
  45391. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45392. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45393. */
  45394. ShadowLight.prototype.computeTransformedInformation = function () {
  45395. if (this.parent && this.parent.getWorldMatrix) {
  45396. if (!this.transformedPosition) {
  45397. this.transformedPosition = BABYLON.Vector3.Zero();
  45398. }
  45399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45400. // In case the direction is present.
  45401. if (this.direction) {
  45402. if (!this.transformedDirection) {
  45403. this.transformedDirection = BABYLON.Vector3.Zero();
  45404. }
  45405. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45406. }
  45407. return true;
  45408. }
  45409. return false;
  45410. };
  45411. /**
  45412. * Return the depth scale used for the shadow map.
  45413. * @returns the depth scale.
  45414. */
  45415. ShadowLight.prototype.getDepthScale = function () {
  45416. return 50.0;
  45417. };
  45418. /**
  45419. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45420. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45421. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45422. */
  45423. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45424. return this.transformedDirection ? this.transformedDirection : this.direction;
  45425. };
  45426. /**
  45427. * Returns the ShadowLight absolute position in the World.
  45428. * @returns the position vector in world space
  45429. */
  45430. ShadowLight.prototype.getAbsolutePosition = function () {
  45431. return this.transformedPosition ? this.transformedPosition : this.position;
  45432. };
  45433. /**
  45434. * Sets the ShadowLight direction toward the passed target.
  45435. * @param target The point tot target in local space
  45436. * @returns the updated ShadowLight direction
  45437. */
  45438. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45439. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45440. return this.direction;
  45441. };
  45442. /**
  45443. * Returns the light rotation in euler definition.
  45444. * @returns the x y z rotation in local space.
  45445. */
  45446. ShadowLight.prototype.getRotation = function () {
  45447. this.direction.normalize();
  45448. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45449. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45450. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45451. };
  45452. /**
  45453. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45454. * @returns true if a cube texture needs to be use
  45455. */
  45456. ShadowLight.prototype.needCube = function () {
  45457. return false;
  45458. };
  45459. /**
  45460. * Detects if the projection matrix requires to be recomputed this frame.
  45461. * @returns true if it requires to be recomputed otherwise, false.
  45462. */
  45463. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45464. return this._needProjectionMatrixCompute;
  45465. };
  45466. /**
  45467. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45468. */
  45469. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45470. this._needProjectionMatrixCompute = true;
  45471. };
  45472. /**
  45473. * Get the world matrix of the sahdow lights.
  45474. * @ignore Internal Use Only
  45475. */
  45476. ShadowLight.prototype._getWorldMatrix = function () {
  45477. if (!this._worldMatrix) {
  45478. this._worldMatrix = BABYLON.Matrix.Identity();
  45479. }
  45480. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45481. return this._worldMatrix;
  45482. };
  45483. /**
  45484. * Gets the minZ used for shadow according to both the scene and the light.
  45485. * @param activeCamera The camera we are returning the min for
  45486. * @returns the depth min z
  45487. */
  45488. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45489. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45490. };
  45491. /**
  45492. * Gets the maxZ used for shadow according to both the scene and the light.
  45493. * @param activeCamera The camera we are returning the max for
  45494. * @returns the depth max z
  45495. */
  45496. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45497. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45498. };
  45499. /**
  45500. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45501. * @param matrix The materix to updated with the projection information
  45502. * @param viewMatrix The transform matrix of the light
  45503. * @param renderList The list of mesh to render in the map
  45504. * @returns The current light
  45505. */
  45506. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45507. if (this.customProjectionMatrixBuilder) {
  45508. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45509. }
  45510. else {
  45511. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45512. }
  45513. return this;
  45514. };
  45515. __decorate([
  45516. BABYLON.serializeAsVector3()
  45517. ], ShadowLight.prototype, "position", null);
  45518. __decorate([
  45519. BABYLON.serializeAsVector3()
  45520. ], ShadowLight.prototype, "direction", null);
  45521. __decorate([
  45522. BABYLON.serialize()
  45523. ], ShadowLight.prototype, "shadowMinZ", null);
  45524. __decorate([
  45525. BABYLON.serialize()
  45526. ], ShadowLight.prototype, "shadowMaxZ", null);
  45527. return ShadowLight;
  45528. }(BABYLON.Light));
  45529. BABYLON.ShadowLight = ShadowLight;
  45530. })(BABYLON || (BABYLON = {}));
  45531. //# sourceMappingURL=babylon.shadowLight.js.map
  45532. var BABYLON;
  45533. (function (BABYLON) {
  45534. /**
  45535. * A point light is a light defined by an unique point in world space.
  45536. * The light is emitted in every direction from this point.
  45537. * A good example of a point light is a standard light bulb.
  45538. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45539. */
  45540. var PointLight = /** @class */ (function (_super) {
  45541. __extends(PointLight, _super);
  45542. /**
  45543. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45544. * A PointLight emits the light in every direction.
  45545. * It can cast shadows.
  45546. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45547. * ```javascript
  45548. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45549. * ```
  45550. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45551. * @param name The light friendly name
  45552. * @param position The position of the point light in the scene
  45553. * @param scene The scene the lights belongs to
  45554. */
  45555. function PointLight(name, position, scene) {
  45556. var _this = _super.call(this, name, scene) || this;
  45557. _this._shadowAngle = Math.PI / 2;
  45558. _this.position = position;
  45559. return _this;
  45560. }
  45561. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45562. /**
  45563. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45564. * This specifies what angle the shadow will use to be created.
  45565. *
  45566. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45567. */
  45568. get: function () {
  45569. return this._shadowAngle;
  45570. },
  45571. /**
  45572. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45573. * This specifies what angle the shadow will use to be created.
  45574. *
  45575. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45576. */
  45577. set: function (value) {
  45578. this._shadowAngle = value;
  45579. this.forceProjectionMatrixCompute();
  45580. },
  45581. enumerable: true,
  45582. configurable: true
  45583. });
  45584. Object.defineProperty(PointLight.prototype, "direction", {
  45585. /**
  45586. * Gets the direction if it has been set.
  45587. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45588. */
  45589. get: function () {
  45590. return this._direction;
  45591. },
  45592. /**
  45593. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45594. */
  45595. set: function (value) {
  45596. var previousNeedCube = this.needCube();
  45597. this._direction = value;
  45598. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45599. this._shadowGenerator.recreateShadowMap();
  45600. }
  45601. },
  45602. enumerable: true,
  45603. configurable: true
  45604. });
  45605. /**
  45606. * Returns the string "PointLight"
  45607. * @returns the class name
  45608. */
  45609. PointLight.prototype.getClassName = function () {
  45610. return "PointLight";
  45611. };
  45612. /**
  45613. * Returns the integer 0.
  45614. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45615. */
  45616. PointLight.prototype.getTypeID = function () {
  45617. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45618. };
  45619. /**
  45620. * Specifies wether or not the shadowmap should be a cube texture.
  45621. * @returns true if the shadowmap needs to be a cube texture.
  45622. */
  45623. PointLight.prototype.needCube = function () {
  45624. return !this.direction;
  45625. };
  45626. /**
  45627. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45628. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45629. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45630. */
  45631. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45632. if (this.direction) {
  45633. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45634. }
  45635. else {
  45636. switch (faceIndex) {
  45637. case 0:
  45638. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45639. case 1:
  45640. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45641. case 2:
  45642. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45643. case 3:
  45644. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45645. case 4:
  45646. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45647. case 5:
  45648. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45649. }
  45650. }
  45651. return BABYLON.Vector3.Zero();
  45652. };
  45653. /**
  45654. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45655. * - fov = PI / 2
  45656. * - aspect ratio : 1.0
  45657. * - z-near and far equal to the active camera minZ and maxZ.
  45658. * Returns the PointLight.
  45659. */
  45660. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45661. var activeCamera = this.getScene().activeCamera;
  45662. if (!activeCamera) {
  45663. return;
  45664. }
  45665. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45666. };
  45667. PointLight.prototype._buildUniformLayout = function () {
  45668. this._uniformBuffer.addUniform("vLightData", 4);
  45669. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45670. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45671. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45672. this._uniformBuffer.addUniform("depthValues", 2);
  45673. this._uniformBuffer.create();
  45674. };
  45675. /**
  45676. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45677. * @param effect The effect to update
  45678. * @param lightIndex The index of the light in the effect to update
  45679. * @returns The point light
  45680. */
  45681. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45682. if (this.computeTransformedInformation()) {
  45683. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45684. return this;
  45685. }
  45686. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45687. return this;
  45688. };
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], PointLight.prototype, "shadowAngle", null);
  45692. return PointLight;
  45693. }(BABYLON.ShadowLight));
  45694. BABYLON.PointLight = PointLight;
  45695. })(BABYLON || (BABYLON = {}));
  45696. //# sourceMappingURL=babylon.pointLight.js.map
  45697. var BABYLON;
  45698. (function (BABYLON) {
  45699. /**
  45700. * A directional light is defined by a direction (what a surprise!).
  45701. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45702. * 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.
  45703. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45704. */
  45705. var DirectionalLight = /** @class */ (function (_super) {
  45706. __extends(DirectionalLight, _super);
  45707. /**
  45708. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45709. * The directional light is emitted from everywhere in the given direction.
  45710. * It can cast shawdows.
  45711. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45712. * @param name The friendly name of the light
  45713. * @param direction The direction of the light
  45714. * @param scene The scene the light belongs to
  45715. */
  45716. function DirectionalLight(name, direction, scene) {
  45717. var _this = _super.call(this, name, scene) || this;
  45718. _this._shadowFrustumSize = 0;
  45719. _this._shadowOrthoScale = 0.5;
  45720. /**
  45721. * Automatically compute the projection matrix to best fit (including all the casters)
  45722. * on each frame.
  45723. */
  45724. _this.autoUpdateExtends = true;
  45725. // Cache
  45726. _this._orthoLeft = Number.MAX_VALUE;
  45727. _this._orthoRight = Number.MIN_VALUE;
  45728. _this._orthoTop = Number.MIN_VALUE;
  45729. _this._orthoBottom = Number.MAX_VALUE;
  45730. _this.position = direction.scale(-1.0);
  45731. _this.direction = direction;
  45732. return _this;
  45733. }
  45734. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45735. /**
  45736. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45737. */
  45738. get: function () {
  45739. return this._shadowFrustumSize;
  45740. },
  45741. /**
  45742. * Specifies a fix frustum size for the shadow generation.
  45743. */
  45744. set: function (value) {
  45745. this._shadowFrustumSize = value;
  45746. this.forceProjectionMatrixCompute();
  45747. },
  45748. enumerable: true,
  45749. configurable: true
  45750. });
  45751. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45752. /**
  45753. * Gets the shadow projection scale against the optimal computed one.
  45754. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45755. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45756. */
  45757. get: function () {
  45758. return this._shadowOrthoScale;
  45759. },
  45760. /**
  45761. * Sets the shadow projection scale against the optimal computed one.
  45762. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45763. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45764. */
  45765. set: function (value) {
  45766. this._shadowOrthoScale = value;
  45767. this.forceProjectionMatrixCompute();
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. /**
  45773. * Returns the string "DirectionalLight".
  45774. * @return The class name
  45775. */
  45776. DirectionalLight.prototype.getClassName = function () {
  45777. return "DirectionalLight";
  45778. };
  45779. /**
  45780. * Returns the integer 1.
  45781. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45782. */
  45783. DirectionalLight.prototype.getTypeID = function () {
  45784. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45785. };
  45786. /**
  45787. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45788. * Returns the DirectionalLight Shadow projection matrix.
  45789. */
  45790. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45791. if (this.shadowFrustumSize > 0) {
  45792. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45793. }
  45794. else {
  45795. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45796. }
  45797. };
  45798. /**
  45799. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45800. * Returns the DirectionalLight Shadow projection matrix.
  45801. */
  45802. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45803. var activeCamera = this.getScene().activeCamera;
  45804. if (!activeCamera) {
  45805. return;
  45806. }
  45807. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45808. };
  45809. /**
  45810. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45811. * Returns the DirectionalLight Shadow projection matrix.
  45812. */
  45813. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45814. var activeCamera = this.getScene().activeCamera;
  45815. if (!activeCamera) {
  45816. return;
  45817. }
  45818. // Check extends
  45819. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45820. var tempVector3 = BABYLON.Vector3.Zero();
  45821. this._orthoLeft = Number.MAX_VALUE;
  45822. this._orthoRight = Number.MIN_VALUE;
  45823. this._orthoTop = Number.MIN_VALUE;
  45824. this._orthoBottom = Number.MAX_VALUE;
  45825. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45826. var mesh = renderList[meshIndex];
  45827. if (!mesh) {
  45828. continue;
  45829. }
  45830. var boundingInfo = mesh.getBoundingInfo();
  45831. var boundingBox = boundingInfo.boundingBox;
  45832. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45833. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45834. if (tempVector3.x < this._orthoLeft)
  45835. this._orthoLeft = tempVector3.x;
  45836. if (tempVector3.y < this._orthoBottom)
  45837. this._orthoBottom = tempVector3.y;
  45838. if (tempVector3.x > this._orthoRight)
  45839. this._orthoRight = tempVector3.x;
  45840. if (tempVector3.y > this._orthoTop)
  45841. this._orthoTop = tempVector3.y;
  45842. }
  45843. }
  45844. }
  45845. var xOffset = this._orthoRight - this._orthoLeft;
  45846. var yOffset = this._orthoTop - this._orthoBottom;
  45847. 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);
  45848. };
  45849. DirectionalLight.prototype._buildUniformLayout = function () {
  45850. this._uniformBuffer.addUniform("vLightData", 4);
  45851. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45852. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45853. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45854. this._uniformBuffer.addUniform("depthValues", 2);
  45855. this._uniformBuffer.create();
  45856. };
  45857. /**
  45858. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45859. * @param effect The effect to update
  45860. * @param lightIndex The index of the light in the effect to update
  45861. * @returns The directional light
  45862. */
  45863. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45864. if (this.computeTransformedInformation()) {
  45865. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45866. return this;
  45867. }
  45868. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45869. return this;
  45870. };
  45871. /**
  45872. * Gets the minZ used for shadow according to both the scene and the light.
  45873. *
  45874. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45875. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45876. * @param activeCamera The camera we are returning the min for
  45877. * @returns the depth min z
  45878. */
  45879. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45880. return 1;
  45881. };
  45882. /**
  45883. * Gets the maxZ used for shadow according to both the scene and the light.
  45884. *
  45885. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45886. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45887. * @param activeCamera The camera we are returning the max for
  45888. * @returns the depth max z
  45889. */
  45890. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45891. return 1;
  45892. };
  45893. __decorate([
  45894. BABYLON.serialize()
  45895. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45896. __decorate([
  45897. BABYLON.serialize()
  45898. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45899. __decorate([
  45900. BABYLON.serialize()
  45901. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45902. return DirectionalLight;
  45903. }(BABYLON.ShadowLight));
  45904. BABYLON.DirectionalLight = DirectionalLight;
  45905. })(BABYLON || (BABYLON = {}));
  45906. //# sourceMappingURL=babylon.directionalLight.js.map
  45907. var BABYLON;
  45908. (function (BABYLON) {
  45909. /**
  45910. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45911. * These values define a cone of light starting from the position, emitting toward the direction.
  45912. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45913. * and the exponent defines the speed of the decay of the light with distance (reach).
  45914. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45915. */
  45916. var SpotLight = /** @class */ (function (_super) {
  45917. __extends(SpotLight, _super);
  45918. /**
  45919. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45920. * It can cast shadows.
  45921. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45922. * @param name The light friendly name
  45923. * @param position The position of the spot light in the scene
  45924. * @param direction The direction of the light in the scene
  45925. * @param angle The cone angle of the light in Radians
  45926. * @param exponent The light decay speed with the distance from the emission spot
  45927. * @param scene The scene the lights belongs to
  45928. */
  45929. function SpotLight(name, position, direction, angle, exponent, scene) {
  45930. var _this = _super.call(this, name, scene) || this;
  45931. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45932. _this._projectionTextureLightNear = 1e-6;
  45933. _this._projectionTextureLightFar = 1000.0;
  45934. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45935. _this._projectionTextureViewLightDirty = true;
  45936. _this._projectionTextureProjectionLightDirty = true;
  45937. _this._projectionTextureDirty = true;
  45938. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45939. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45940. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45941. _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);
  45942. _this.position = position;
  45943. _this.direction = direction;
  45944. _this.angle = angle;
  45945. _this.exponent = exponent;
  45946. return _this;
  45947. }
  45948. Object.defineProperty(SpotLight.prototype, "angle", {
  45949. /**
  45950. * Gets the cone angle of the spot light in Radians.
  45951. */
  45952. get: function () {
  45953. return this._angle;
  45954. },
  45955. /**
  45956. * Sets the cone angle of the spot light in Radians.
  45957. */
  45958. set: function (value) {
  45959. this._angle = value;
  45960. this._projectionTextureProjectionLightDirty = true;
  45961. this.forceProjectionMatrixCompute();
  45962. },
  45963. enumerable: true,
  45964. configurable: true
  45965. });
  45966. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45967. /**
  45968. * Allows scaling the angle of the light for shadow generation only.
  45969. */
  45970. get: function () {
  45971. return this._shadowAngleScale;
  45972. },
  45973. /**
  45974. * Allows scaling the angle of the light for shadow generation only.
  45975. */
  45976. set: function (value) {
  45977. this._shadowAngleScale = value;
  45978. this.forceProjectionMatrixCompute();
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45984. /**
  45985. * Allows reading the projecton texture
  45986. */
  45987. get: function () {
  45988. return this._projectionTextureMatrix;
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. ;
  45994. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45995. /**
  45996. * Gets the near clip of the Spotlight for texture projection.
  45997. */
  45998. get: function () {
  45999. return this._projectionTextureLightNear;
  46000. },
  46001. /**
  46002. * Sets the near clip of the Spotlight for texture projection.
  46003. */
  46004. set: function (value) {
  46005. this._projectionTextureLightNear = value;
  46006. this._projectionTextureProjectionLightDirty = true;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46012. /**
  46013. * Gets the far clip of the Spotlight for texture projection.
  46014. */
  46015. get: function () {
  46016. return this._projectionTextureLightFar;
  46017. },
  46018. /**
  46019. * Sets the far clip of the Spotlight for texture projection.
  46020. */
  46021. set: function (value) {
  46022. this._projectionTextureLightFar = value;
  46023. this._projectionTextureProjectionLightDirty = true;
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46029. /**
  46030. * Gets the Up vector of the Spotlight for texture projection.
  46031. */
  46032. get: function () {
  46033. return this._projectionTextureUpDirection;
  46034. },
  46035. /**
  46036. * Sets the Up vector of the Spotlight for texture projection.
  46037. */
  46038. set: function (value) {
  46039. this._projectionTextureUpDirection = value;
  46040. this._projectionTextureProjectionLightDirty = true;
  46041. },
  46042. enumerable: true,
  46043. configurable: true
  46044. });
  46045. ;
  46046. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46047. /**
  46048. * Gets the projection texture of the light.
  46049. */
  46050. get: function () {
  46051. return this._projectionTexture;
  46052. },
  46053. /**
  46054. * Sets the projection texture of the light.
  46055. */
  46056. set: function (value) {
  46057. this._projectionTexture = value;
  46058. this._projectionTextureDirty = true;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. /**
  46064. * Returns the string "SpotLight".
  46065. * @returns the class name
  46066. */
  46067. SpotLight.prototype.getClassName = function () {
  46068. return "SpotLight";
  46069. };
  46070. /**
  46071. * Returns the integer 2.
  46072. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46073. */
  46074. SpotLight.prototype.getTypeID = function () {
  46075. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46076. };
  46077. /**
  46078. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46079. */
  46080. SpotLight.prototype._setDirection = function (value) {
  46081. _super.prototype._setDirection.call(this, value);
  46082. this._projectionTextureViewLightDirty = true;
  46083. };
  46084. /**
  46085. * Overrides the position setter to recompute the projection texture view light Matrix.
  46086. */
  46087. SpotLight.prototype._setPosition = function (value) {
  46088. _super.prototype._setPosition.call(this, value);
  46089. this._projectionTextureViewLightDirty = true;
  46090. };
  46091. /**
  46092. * 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.
  46093. * Returns the SpotLight.
  46094. */
  46095. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46096. var activeCamera = this.getScene().activeCamera;
  46097. if (!activeCamera) {
  46098. return;
  46099. }
  46100. this._shadowAngleScale = this._shadowAngleScale || 1;
  46101. var angle = this._shadowAngleScale * this._angle;
  46102. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46103. };
  46104. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46105. this._projectionTextureViewLightDirty = false;
  46106. this._projectionTextureDirty = true;
  46107. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46108. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46109. };
  46110. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46111. this._projectionTextureProjectionLightDirty = false;
  46112. this._projectionTextureDirty = true;
  46113. var light_far = this.projectionTextureLightFar;
  46114. var light_near = this.projectionTextureLightNear;
  46115. var P = light_far / (light_far - light_near);
  46116. var Q = -P * light_near;
  46117. var S = 1.0 / Math.tan(this._angle / 2.0);
  46118. var A = 1.0;
  46119. 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);
  46120. };
  46121. /**
  46122. * Main function for light texture projection matrix computing.
  46123. */
  46124. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46125. this._projectionTextureDirty = false;
  46126. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46127. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46128. };
  46129. SpotLight.prototype._buildUniformLayout = function () {
  46130. this._uniformBuffer.addUniform("vLightData", 4);
  46131. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46132. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46133. this._uniformBuffer.addUniform("vLightDirection", 3);
  46134. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46135. this._uniformBuffer.addUniform("depthValues", 2);
  46136. this._uniformBuffer.create();
  46137. };
  46138. /**
  46139. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46140. * @param effect The effect to update
  46141. * @param lightIndex The index of the light in the effect to update
  46142. * @returns The spot light
  46143. */
  46144. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46145. var normalizeDirection;
  46146. if (this.computeTransformedInformation()) {
  46147. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46148. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46149. }
  46150. else {
  46151. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46152. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46153. }
  46154. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46155. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46156. if (this._projectionTextureViewLightDirty) {
  46157. this._computeProjectionTextureViewLightMatrix();
  46158. }
  46159. if (this._projectionTextureProjectionLightDirty) {
  46160. this._computeProjectionTextureProjectionLightMatrix();
  46161. }
  46162. if (this._projectionTextureDirty) {
  46163. this._computeProjectionTextureMatrix();
  46164. }
  46165. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46166. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46167. }
  46168. return this;
  46169. };
  46170. /**
  46171. * Disposes the light and the associated resources.
  46172. */
  46173. SpotLight.prototype.dispose = function () {
  46174. _super.prototype.dispose.call(this);
  46175. if (this._projectionTexture) {
  46176. this._projectionTexture.dispose();
  46177. }
  46178. };
  46179. __decorate([
  46180. BABYLON.serialize()
  46181. ], SpotLight.prototype, "angle", null);
  46182. __decorate([
  46183. BABYLON.serialize()
  46184. ], SpotLight.prototype, "shadowAngleScale", null);
  46185. __decorate([
  46186. BABYLON.serialize()
  46187. ], SpotLight.prototype, "exponent", void 0);
  46188. __decorate([
  46189. BABYLON.serialize()
  46190. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46191. __decorate([
  46192. BABYLON.serialize()
  46193. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46194. __decorate([
  46195. BABYLON.serialize()
  46196. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46197. __decorate([
  46198. BABYLON.serializeAsTexture("projectedLightTexture")
  46199. ], SpotLight.prototype, "_projectionTexture", void 0);
  46200. return SpotLight;
  46201. }(BABYLON.ShadowLight));
  46202. BABYLON.SpotLight = SpotLight;
  46203. })(BABYLON || (BABYLON = {}));
  46204. //# sourceMappingURL=babylon.spotLight.js.map
  46205. var BABYLON;
  46206. (function (BABYLON) {
  46207. /**
  46208. * Class used to override all child animations of a given target
  46209. */
  46210. var AnimationPropertiesOverride = /** @class */ (function () {
  46211. function AnimationPropertiesOverride() {
  46212. /**
  46213. * Gets or sets a value indicating if animation blending must be used
  46214. */
  46215. this.enableBlending = false;
  46216. /**
  46217. * Gets or sets the blending speed to use when enableBlending is true
  46218. */
  46219. this.blendingSpeed = 0.01;
  46220. /**
  46221. * Gets or sets the default loop mode to use
  46222. */
  46223. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46224. }
  46225. return AnimationPropertiesOverride;
  46226. }());
  46227. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46228. })(BABYLON || (BABYLON = {}));
  46229. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46230. var BABYLON;
  46231. (function (BABYLON) {
  46232. var AnimationRange = /** @class */ (function () {
  46233. function AnimationRange(name, from, to) {
  46234. this.name = name;
  46235. this.from = from;
  46236. this.to = to;
  46237. }
  46238. AnimationRange.prototype.clone = function () {
  46239. return new AnimationRange(this.name, this.from, this.to);
  46240. };
  46241. return AnimationRange;
  46242. }());
  46243. BABYLON.AnimationRange = AnimationRange;
  46244. /**
  46245. * Composed of a frame, and an action function
  46246. */
  46247. var AnimationEvent = /** @class */ (function () {
  46248. function AnimationEvent(frame, action, onlyOnce) {
  46249. this.frame = frame;
  46250. this.action = action;
  46251. this.onlyOnce = onlyOnce;
  46252. this.isDone = false;
  46253. }
  46254. return AnimationEvent;
  46255. }());
  46256. BABYLON.AnimationEvent = AnimationEvent;
  46257. var PathCursor = /** @class */ (function () {
  46258. function PathCursor(path) {
  46259. this.path = path;
  46260. this._onchange = new Array();
  46261. this.value = 0;
  46262. this.animations = new Array();
  46263. }
  46264. PathCursor.prototype.getPoint = function () {
  46265. var point = this.path.getPointAtLengthPosition(this.value);
  46266. return new BABYLON.Vector3(point.x, 0, point.y);
  46267. };
  46268. PathCursor.prototype.moveAhead = function (step) {
  46269. if (step === void 0) { step = 0.002; }
  46270. this.move(step);
  46271. return this;
  46272. };
  46273. PathCursor.prototype.moveBack = function (step) {
  46274. if (step === void 0) { step = 0.002; }
  46275. this.move(-step);
  46276. return this;
  46277. };
  46278. PathCursor.prototype.move = function (step) {
  46279. if (Math.abs(step) > 1) {
  46280. throw "step size should be less than 1.";
  46281. }
  46282. this.value += step;
  46283. this.ensureLimits();
  46284. this.raiseOnChange();
  46285. return this;
  46286. };
  46287. PathCursor.prototype.ensureLimits = function () {
  46288. while (this.value > 1) {
  46289. this.value -= 1;
  46290. }
  46291. while (this.value < 0) {
  46292. this.value += 1;
  46293. }
  46294. return this;
  46295. };
  46296. // used by animation engine
  46297. PathCursor.prototype.raiseOnChange = function () {
  46298. var _this = this;
  46299. this._onchange.forEach(function (f) { return f(_this); });
  46300. return this;
  46301. };
  46302. PathCursor.prototype.onchange = function (f) {
  46303. this._onchange.push(f);
  46304. return this;
  46305. };
  46306. return PathCursor;
  46307. }());
  46308. BABYLON.PathCursor = PathCursor;
  46309. var AnimationKeyInterpolation;
  46310. (function (AnimationKeyInterpolation) {
  46311. /**
  46312. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46313. */
  46314. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46315. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46316. var Animation = /** @class */ (function () {
  46317. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46318. this.name = name;
  46319. this.targetProperty = targetProperty;
  46320. this.framePerSecond = framePerSecond;
  46321. this.dataType = dataType;
  46322. this.loopMode = loopMode;
  46323. this.enableBlending = enableBlending;
  46324. this._runtimeAnimations = new Array();
  46325. // The set of event that will be linked to this animation
  46326. this._events = new Array();
  46327. this.blendingSpeed = 0.01;
  46328. this._ranges = {};
  46329. this.targetPropertyPath = targetProperty.split(".");
  46330. this.dataType = dataType;
  46331. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46332. }
  46333. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46334. var dataType = undefined;
  46335. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46336. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46337. }
  46338. else if (from instanceof BABYLON.Quaternion) {
  46339. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46340. }
  46341. else if (from instanceof BABYLON.Vector3) {
  46342. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46343. }
  46344. else if (from instanceof BABYLON.Vector2) {
  46345. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46346. }
  46347. else if (from instanceof BABYLON.Color3) {
  46348. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46349. }
  46350. else if (from instanceof BABYLON.Size) {
  46351. dataType = Animation.ANIMATIONTYPE_SIZE;
  46352. }
  46353. if (dataType == undefined) {
  46354. return null;
  46355. }
  46356. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46357. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46358. animation.setKeys(keys);
  46359. if (easingFunction !== undefined) {
  46360. animation.setEasingFunction(easingFunction);
  46361. }
  46362. return animation;
  46363. };
  46364. /**
  46365. * Sets up an animation.
  46366. * @param property the property to animate
  46367. * @param animationType the animation type to apply
  46368. * @param easingFunction the easing function used in the animation
  46369. * @returns The created animation
  46370. */
  46371. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46372. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46373. animation.setEasingFunction(easingFunction);
  46374. return animation;
  46375. };
  46376. /**
  46377. * Create and start an animation on a node
  46378. * @param {string} name defines the name of the global animation that will be run on all nodes
  46379. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46380. * @param {string} targetProperty defines property to animate
  46381. * @param {number} framePerSecond defines the number of frame per second yo use
  46382. * @param {number} totalFrame defines the number of frames in total
  46383. * @param {any} from defines the initial value
  46384. * @param {any} to defines the final value
  46385. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46386. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46387. * @param onAnimationEnd defines the callback to call when animation end
  46388. * @returns the animatable created for this animation
  46389. */
  46390. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46391. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46392. if (!animation) {
  46393. return null;
  46394. }
  46395. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46396. };
  46397. /**
  46398. * Create and start an animation on a node and its descendants
  46399. * @param {string} name defines the name of the global animation that will be run on all nodes
  46400. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46401. * @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.
  46402. * @param {string} targetProperty defines property to animate
  46403. * @param {number} framePerSecond defines the number of frame per second yo use
  46404. * @param {number} totalFrame defines the number of frames in total
  46405. * @param {any} from defines the initial value
  46406. * @param {any} to defines the final value
  46407. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46408. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46409. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46410. * @returns the list of animatables created for all nodes
  46411. * @example https://www.babylonjs-playground.com/#MH0VLI
  46412. */
  46413. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46414. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46415. if (!animation) {
  46416. return null;
  46417. }
  46418. var scene = node.getScene();
  46419. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46420. };
  46421. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46422. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46423. if (!animation) {
  46424. return null;
  46425. }
  46426. node.animations.push(animation);
  46427. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46428. };
  46429. /**
  46430. * Transition property of the Camera to the target Value.
  46431. * @param property The property to transition
  46432. * @param targetValue The target Value of the property
  46433. * @param host The object where the property to animate belongs
  46434. * @param scene Scene used to run the animation
  46435. * @param frameRate Framerate (in frame/s) to use
  46436. * @param transition The transition type we want to use
  46437. * @param duration The duration of the animation, in milliseconds
  46438. * @param onAnimationEnd Call back trigger at the end of the animation.
  46439. */
  46440. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46441. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46442. if (duration <= 0) {
  46443. host[property] = targetValue;
  46444. if (onAnimationEnd) {
  46445. onAnimationEnd();
  46446. }
  46447. return null;
  46448. }
  46449. var endFrame = frameRate * (duration / 1000);
  46450. transition.setKeys([{
  46451. frame: 0,
  46452. value: host[property].clone ? host[property].clone() : host[property]
  46453. },
  46454. {
  46455. frame: endFrame,
  46456. value: targetValue
  46457. }]);
  46458. if (!host.animations) {
  46459. host.animations = [];
  46460. }
  46461. host.animations.push(transition);
  46462. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46463. animation.onAnimationEnd = onAnimationEnd;
  46464. return animation;
  46465. };
  46466. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46467. /**
  46468. * Return the array of runtime animations currently using this animation
  46469. */
  46470. get: function () {
  46471. return this._runtimeAnimations;
  46472. },
  46473. enumerable: true,
  46474. configurable: true
  46475. });
  46476. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46477. get: function () {
  46478. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46479. var runtimeAnimation = _a[_i];
  46480. if (!runtimeAnimation.isStopped) {
  46481. return true;
  46482. }
  46483. }
  46484. return false;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. // Methods
  46490. /**
  46491. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46492. */
  46493. Animation.prototype.toString = function (fullDetails) {
  46494. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46495. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46496. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46497. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46498. if (fullDetails) {
  46499. ret += ", Ranges: {";
  46500. var first = true;
  46501. for (var name in this._ranges) {
  46502. if (first) {
  46503. ret += ", ";
  46504. first = false;
  46505. }
  46506. ret += name;
  46507. }
  46508. ret += "}";
  46509. }
  46510. return ret;
  46511. };
  46512. /**
  46513. * Add an event to this animation.
  46514. */
  46515. Animation.prototype.addEvent = function (event) {
  46516. this._events.push(event);
  46517. };
  46518. /**
  46519. * Remove all events found at the given frame
  46520. * @param frame
  46521. */
  46522. Animation.prototype.removeEvents = function (frame) {
  46523. for (var index = 0; index < this._events.length; index++) {
  46524. if (this._events[index].frame === frame) {
  46525. this._events.splice(index, 1);
  46526. index--;
  46527. }
  46528. }
  46529. };
  46530. Animation.prototype.getEvents = function () {
  46531. return this._events;
  46532. };
  46533. Animation.prototype.createRange = function (name, from, to) {
  46534. // check name not already in use; could happen for bones after serialized
  46535. if (!this._ranges[name]) {
  46536. this._ranges[name] = new AnimationRange(name, from, to);
  46537. }
  46538. };
  46539. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46540. if (deleteFrames === void 0) { deleteFrames = true; }
  46541. var range = this._ranges[name];
  46542. if (!range) {
  46543. return;
  46544. }
  46545. if (deleteFrames) {
  46546. var from = range.from;
  46547. var to = range.to;
  46548. // this loop MUST go high to low for multiple splices to work
  46549. for (var key = this._keys.length - 1; key >= 0; key--) {
  46550. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46551. this._keys.splice(key, 1);
  46552. }
  46553. }
  46554. }
  46555. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46556. };
  46557. Animation.prototype.getRange = function (name) {
  46558. return this._ranges[name];
  46559. };
  46560. Animation.prototype.getKeys = function () {
  46561. return this._keys;
  46562. };
  46563. Animation.prototype.getHighestFrame = function () {
  46564. var ret = 0;
  46565. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46566. if (ret < this._keys[key].frame) {
  46567. ret = this._keys[key].frame;
  46568. }
  46569. }
  46570. return ret;
  46571. };
  46572. Animation.prototype.getEasingFunction = function () {
  46573. return this._easingFunction;
  46574. };
  46575. Animation.prototype.setEasingFunction = function (easingFunction) {
  46576. this._easingFunction = easingFunction;
  46577. };
  46578. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46579. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46580. };
  46581. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46582. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46583. };
  46584. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46585. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46586. };
  46587. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46588. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46589. };
  46590. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46591. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46592. };
  46593. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46594. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46595. };
  46596. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46597. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46598. };
  46599. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46600. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46601. };
  46602. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46603. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46604. };
  46605. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46606. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46607. };
  46608. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46609. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46610. };
  46611. Animation.prototype.clone = function () {
  46612. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46613. clone.enableBlending = this.enableBlending;
  46614. clone.blendingSpeed = this.blendingSpeed;
  46615. if (this._keys) {
  46616. clone.setKeys(this._keys);
  46617. }
  46618. if (this._ranges) {
  46619. clone._ranges = {};
  46620. for (var name in this._ranges) {
  46621. var range = this._ranges[name];
  46622. if (!range) {
  46623. continue;
  46624. }
  46625. clone._ranges[name] = range.clone();
  46626. }
  46627. }
  46628. return clone;
  46629. };
  46630. Animation.prototype.setKeys = function (values) {
  46631. this._keys = values.slice(0);
  46632. };
  46633. Animation.prototype.serialize = function () {
  46634. var serializationObject = {};
  46635. serializationObject.name = this.name;
  46636. serializationObject.property = this.targetProperty;
  46637. serializationObject.framePerSecond = this.framePerSecond;
  46638. serializationObject.dataType = this.dataType;
  46639. serializationObject.loopBehavior = this.loopMode;
  46640. serializationObject.enableBlending = this.enableBlending;
  46641. serializationObject.blendingSpeed = this.blendingSpeed;
  46642. var dataType = this.dataType;
  46643. serializationObject.keys = [];
  46644. var keys = this.getKeys();
  46645. for (var index = 0; index < keys.length; index++) {
  46646. var animationKey = keys[index];
  46647. var key = {};
  46648. key.frame = animationKey.frame;
  46649. switch (dataType) {
  46650. case Animation.ANIMATIONTYPE_FLOAT:
  46651. key.values = [animationKey.value];
  46652. break;
  46653. case Animation.ANIMATIONTYPE_QUATERNION:
  46654. case Animation.ANIMATIONTYPE_MATRIX:
  46655. case Animation.ANIMATIONTYPE_VECTOR3:
  46656. case Animation.ANIMATIONTYPE_COLOR3:
  46657. key.values = animationKey.value.asArray();
  46658. break;
  46659. }
  46660. serializationObject.keys.push(key);
  46661. }
  46662. serializationObject.ranges = [];
  46663. for (var name in this._ranges) {
  46664. var source = this._ranges[name];
  46665. if (!source) {
  46666. continue;
  46667. }
  46668. var range = {};
  46669. range.name = name;
  46670. range.from = source.from;
  46671. range.to = source.to;
  46672. serializationObject.ranges.push(range);
  46673. }
  46674. return serializationObject;
  46675. };
  46676. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46677. get: function () {
  46678. return Animation._ANIMATIONTYPE_FLOAT;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46684. get: function () {
  46685. return Animation._ANIMATIONTYPE_VECTOR3;
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46691. get: function () {
  46692. return Animation._ANIMATIONTYPE_VECTOR2;
  46693. },
  46694. enumerable: true,
  46695. configurable: true
  46696. });
  46697. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46698. get: function () {
  46699. return Animation._ANIMATIONTYPE_SIZE;
  46700. },
  46701. enumerable: true,
  46702. configurable: true
  46703. });
  46704. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46705. get: function () {
  46706. return Animation._ANIMATIONTYPE_QUATERNION;
  46707. },
  46708. enumerable: true,
  46709. configurable: true
  46710. });
  46711. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46712. get: function () {
  46713. return Animation._ANIMATIONTYPE_MATRIX;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46719. get: function () {
  46720. return Animation._ANIMATIONTYPE_COLOR3;
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46726. get: function () {
  46727. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46728. },
  46729. enumerable: true,
  46730. configurable: true
  46731. });
  46732. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46733. get: function () {
  46734. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46735. },
  46736. enumerable: true,
  46737. configurable: true
  46738. });
  46739. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46740. get: function () {
  46741. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46742. },
  46743. enumerable: true,
  46744. configurable: true
  46745. });
  46746. Animation.Parse = function (parsedAnimation) {
  46747. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46748. var dataType = parsedAnimation.dataType;
  46749. var keys = [];
  46750. var data;
  46751. var index;
  46752. if (parsedAnimation.enableBlending) {
  46753. animation.enableBlending = parsedAnimation.enableBlending;
  46754. }
  46755. if (parsedAnimation.blendingSpeed) {
  46756. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46757. }
  46758. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46759. var key = parsedAnimation.keys[index];
  46760. var inTangent;
  46761. var outTangent;
  46762. switch (dataType) {
  46763. case Animation.ANIMATIONTYPE_FLOAT:
  46764. data = key.values[0];
  46765. if (key.values.length >= 1) {
  46766. inTangent = key.values[1];
  46767. }
  46768. if (key.values.length >= 2) {
  46769. outTangent = key.values[2];
  46770. }
  46771. break;
  46772. case Animation.ANIMATIONTYPE_QUATERNION:
  46773. data = BABYLON.Quaternion.FromArray(key.values);
  46774. if (key.values.length >= 8) {
  46775. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46776. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46777. inTangent = _inTangent;
  46778. }
  46779. }
  46780. if (key.values.length >= 12) {
  46781. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46782. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46783. outTangent = _outTangent;
  46784. }
  46785. }
  46786. break;
  46787. case Animation.ANIMATIONTYPE_MATRIX:
  46788. data = BABYLON.Matrix.FromArray(key.values);
  46789. break;
  46790. case Animation.ANIMATIONTYPE_COLOR3:
  46791. data = BABYLON.Color3.FromArray(key.values);
  46792. break;
  46793. case Animation.ANIMATIONTYPE_VECTOR3:
  46794. default:
  46795. data = BABYLON.Vector3.FromArray(key.values);
  46796. break;
  46797. }
  46798. var keyData = {};
  46799. keyData.frame = key.frame;
  46800. keyData.value = data;
  46801. if (inTangent != undefined) {
  46802. keyData.inTangent = inTangent;
  46803. }
  46804. if (outTangent != undefined) {
  46805. keyData.outTangent = outTangent;
  46806. }
  46807. keys.push(keyData);
  46808. }
  46809. animation.setKeys(keys);
  46810. if (parsedAnimation.ranges) {
  46811. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46812. data = parsedAnimation.ranges[index];
  46813. animation.createRange(data.name, data.from, data.to);
  46814. }
  46815. }
  46816. return animation;
  46817. };
  46818. Animation.AppendSerializedAnimations = function (source, destination) {
  46819. if (source.animations) {
  46820. destination.animations = [];
  46821. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46822. var animation = source.animations[animationIndex];
  46823. destination.animations.push(animation.serialize());
  46824. }
  46825. }
  46826. };
  46827. Animation.AllowMatricesInterpolation = false;
  46828. // Statics
  46829. Animation._ANIMATIONTYPE_FLOAT = 0;
  46830. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46831. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46832. Animation._ANIMATIONTYPE_MATRIX = 3;
  46833. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46834. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46835. Animation._ANIMATIONTYPE_SIZE = 6;
  46836. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46837. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46838. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46839. return Animation;
  46840. }());
  46841. BABYLON.Animation = Animation;
  46842. })(BABYLON || (BABYLON = {}));
  46843. //# sourceMappingURL=babylon.animation.js.map
  46844. var BABYLON;
  46845. (function (BABYLON) {
  46846. /**
  46847. * This class defines the direct association between an animation and a target
  46848. */
  46849. var TargetedAnimation = /** @class */ (function () {
  46850. function TargetedAnimation() {
  46851. }
  46852. return TargetedAnimation;
  46853. }());
  46854. BABYLON.TargetedAnimation = TargetedAnimation;
  46855. /**
  46856. * Use this class to create coordinated animations on multiple targets
  46857. */
  46858. var AnimationGroup = /** @class */ (function () {
  46859. function AnimationGroup(name, scene) {
  46860. if (scene === void 0) { scene = null; }
  46861. this.name = name;
  46862. this._targetedAnimations = new Array();
  46863. this._animatables = new Array();
  46864. this._from = Number.MAX_VALUE;
  46865. this._to = -Number.MAX_VALUE;
  46866. this._speedRatio = 1;
  46867. this.onAnimationEndObservable = new BABYLON.Observable();
  46868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46869. this._scene.animationGroups.push(this);
  46870. }
  46871. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46872. /**
  46873. * Define if the animations are started
  46874. */
  46875. get: function () {
  46876. return this._isStarted;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46882. /**
  46883. * Gets or sets the speed ratio to use for all animations
  46884. */
  46885. get: function () {
  46886. return this._speedRatio;
  46887. },
  46888. /**
  46889. * Gets or sets the speed ratio to use for all animations
  46890. */
  46891. set: function (value) {
  46892. if (this._speedRatio === value) {
  46893. return;
  46894. }
  46895. this._speedRatio = value;
  46896. for (var index = 0; index < this._animatables.length; index++) {
  46897. var animatable = this._animatables[index];
  46898. animatable.speedRatio = this._speedRatio;
  46899. }
  46900. },
  46901. enumerable: true,
  46902. configurable: true
  46903. });
  46904. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46905. /**
  46906. * Gets the targeted animations for this animation group
  46907. */
  46908. get: function () {
  46909. return this._targetedAnimations;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46915. /**
  46916. * returning the list of animatables controlled by this animation group.
  46917. */
  46918. get: function () {
  46919. return this._animatables;
  46920. },
  46921. enumerable: true,
  46922. configurable: true
  46923. });
  46924. /**
  46925. * Add an animation (with its target) in the group
  46926. * @param animation defines the animation we want to add
  46927. * @param target defines the target of the animation
  46928. * @returns the {BABYLON.TargetedAnimation} object
  46929. */
  46930. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46931. var targetedAnimation = {
  46932. animation: animation,
  46933. target: target
  46934. };
  46935. var keys = animation.getKeys();
  46936. if (this._from > keys[0].frame) {
  46937. this._from = keys[0].frame;
  46938. }
  46939. if (this._to < keys[keys.length - 1].frame) {
  46940. this._to = keys[keys.length - 1].frame;
  46941. }
  46942. this._targetedAnimations.push(targetedAnimation);
  46943. return targetedAnimation;
  46944. };
  46945. /**
  46946. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46947. * It can add constant keys at begin or end
  46948. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46949. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46950. */
  46951. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46952. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46953. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46954. beginFrame = Math.max(beginFrame, this._from);
  46955. endFrame = Math.min(endFrame, this._to);
  46956. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46957. var targetedAnimation = this._targetedAnimations[index];
  46958. var keys = targetedAnimation.animation.getKeys();
  46959. var startKey = keys[0];
  46960. var endKey = keys[keys.length - 1];
  46961. if (startKey.frame > beginFrame) {
  46962. var newKey = {
  46963. frame: beginFrame,
  46964. value: startKey.value,
  46965. inTangent: startKey.inTangent,
  46966. outTangent: startKey.outTangent,
  46967. interpolation: startKey.interpolation
  46968. };
  46969. keys.splice(0, 0, newKey);
  46970. }
  46971. if (endKey.frame < endFrame) {
  46972. var newKey = {
  46973. frame: endFrame,
  46974. value: endKey.value,
  46975. inTangent: endKey.outTangent,
  46976. outTangent: endKey.outTangent,
  46977. interpolation: endKey.interpolation
  46978. };
  46979. keys.push(newKey);
  46980. }
  46981. }
  46982. return this;
  46983. };
  46984. /**
  46985. * Start all animations on given targets
  46986. * @param loop defines if animations must loop
  46987. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46988. */
  46989. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46990. var _this = this;
  46991. if (loop === void 0) { loop = false; }
  46992. if (speedRatio === void 0) { speedRatio = 1; }
  46993. if (this._isStarted || this._targetedAnimations.length === 0) {
  46994. return this;
  46995. }
  46996. var _loop_1 = function () {
  46997. var targetedAnimation = this_1._targetedAnimations[index];
  46998. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46999. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47000. }));
  47001. };
  47002. var this_1 = this;
  47003. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47004. _loop_1();
  47005. }
  47006. this._speedRatio = speedRatio;
  47007. this._isStarted = true;
  47008. return this;
  47009. };
  47010. /**
  47011. * Pause all animations
  47012. */
  47013. AnimationGroup.prototype.pause = function () {
  47014. if (!this._isStarted) {
  47015. return this;
  47016. }
  47017. for (var index = 0; index < this._animatables.length; index++) {
  47018. var animatable = this._animatables[index];
  47019. animatable.pause();
  47020. }
  47021. return this;
  47022. };
  47023. /**
  47024. * Play all animations to initial state
  47025. * This function will start() the animations if they were not started or will restart() them if they were paused
  47026. * @param loop defines if animations must loop
  47027. */
  47028. AnimationGroup.prototype.play = function (loop) {
  47029. if (this.isStarted) {
  47030. if (loop !== undefined) {
  47031. for (var index = 0; index < this._animatables.length; index++) {
  47032. var animatable = this._animatables[index];
  47033. animatable.loopAnimation = loop;
  47034. }
  47035. }
  47036. this.restart();
  47037. }
  47038. else {
  47039. this.start(loop, this._speedRatio);
  47040. }
  47041. return this;
  47042. };
  47043. /**
  47044. * Reset all animations to initial state
  47045. */
  47046. AnimationGroup.prototype.reset = function () {
  47047. if (!this._isStarted) {
  47048. return this;
  47049. }
  47050. for (var index = 0; index < this._animatables.length; index++) {
  47051. var animatable = this._animatables[index];
  47052. animatable.reset();
  47053. }
  47054. return this;
  47055. };
  47056. /**
  47057. * Restart animations from key 0
  47058. */
  47059. AnimationGroup.prototype.restart = function () {
  47060. if (!this._isStarted) {
  47061. return this;
  47062. }
  47063. for (var index = 0; index < this._animatables.length; index++) {
  47064. var animatable = this._animatables[index];
  47065. animatable.restart();
  47066. }
  47067. return this;
  47068. };
  47069. /**
  47070. * Stop all animations
  47071. */
  47072. AnimationGroup.prototype.stop = function () {
  47073. if (!this._isStarted) {
  47074. return this;
  47075. }
  47076. for (var index = 0; index < this._animatables.length; index++) {
  47077. var animatable = this._animatables[index];
  47078. animatable.stop();
  47079. }
  47080. this._isStarted = false;
  47081. return this;
  47082. };
  47083. /**
  47084. * Goes to a specific frame in this animation group
  47085. *
  47086. * @param frame the frame number to go to
  47087. * @return the animationGroup
  47088. */
  47089. AnimationGroup.prototype.goToFrame = function (frame) {
  47090. if (!this._isStarted) {
  47091. return this;
  47092. }
  47093. for (var index = 0; index < this._animatables.length; index++) {
  47094. var animatable = this._animatables[index];
  47095. animatable.goToFrame(frame);
  47096. }
  47097. return this;
  47098. };
  47099. /**
  47100. * Dispose all associated resources
  47101. */
  47102. AnimationGroup.prototype.dispose = function () {
  47103. this._targetedAnimations = [];
  47104. this._animatables = [];
  47105. var index = this._scene.animationGroups.indexOf(this);
  47106. if (index > -1) {
  47107. this._scene.animationGroups.splice(index, 1);
  47108. }
  47109. };
  47110. return AnimationGroup;
  47111. }());
  47112. BABYLON.AnimationGroup = AnimationGroup;
  47113. })(BABYLON || (BABYLON = {}));
  47114. //# sourceMappingURL=babylon.animationGroup.js.map
  47115. var BABYLON;
  47116. (function (BABYLON) {
  47117. var RuntimeAnimation = /** @class */ (function () {
  47118. function RuntimeAnimation(target, animation) {
  47119. this._offsetsCache = {};
  47120. this._highLimitsCache = {};
  47121. this._stopped = false;
  47122. this._blendingFactor = 0;
  47123. this._ratioOffset = 0;
  47124. this._animation = animation;
  47125. this._target = target;
  47126. animation._runtimeAnimations.push(this);
  47127. }
  47128. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47129. get: function () {
  47130. return this._animation;
  47131. },
  47132. enumerable: true,
  47133. configurable: true
  47134. });
  47135. RuntimeAnimation.prototype.reset = function () {
  47136. this._offsetsCache = {};
  47137. this._highLimitsCache = {};
  47138. this.currentFrame = 0;
  47139. this._blendingFactor = 0;
  47140. this._originalBlendValue = null;
  47141. };
  47142. RuntimeAnimation.prototype.isStopped = function () {
  47143. return this._stopped;
  47144. };
  47145. RuntimeAnimation.prototype.dispose = function () {
  47146. var index = this._animation.runtimeAnimations.indexOf(this);
  47147. if (index > -1) {
  47148. this._animation.runtimeAnimations.splice(index, 1);
  47149. }
  47150. };
  47151. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47152. if (typeof value === "function") {
  47153. return value();
  47154. }
  47155. return value;
  47156. };
  47157. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47158. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47159. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47160. }
  47161. this.currentFrame = currentFrame;
  47162. var keys = this._animation.getKeys();
  47163. // Try to get a hash to find the right key
  47164. 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));
  47165. if (keys[startKeyIndex].frame >= currentFrame) {
  47166. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47167. startKeyIndex--;
  47168. }
  47169. }
  47170. for (var key = startKeyIndex; key < keys.length; key++) {
  47171. var endKey = keys[key + 1];
  47172. if (endKey.frame >= currentFrame) {
  47173. var startKey = keys[key];
  47174. var startValue = this._getKeyValue(startKey.value);
  47175. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47176. return startValue;
  47177. }
  47178. var endValue = this._getKeyValue(endKey.value);
  47179. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47180. var frameDelta = endKey.frame - startKey.frame;
  47181. // gradient : percent of currentFrame between the frame inf and the frame sup
  47182. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47183. // check for easingFunction and correction of gradient
  47184. var easingFunction = this._animation.getEasingFunction();
  47185. if (easingFunction != null) {
  47186. gradient = easingFunction.ease(gradient);
  47187. }
  47188. switch (this._animation.dataType) {
  47189. // Float
  47190. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47191. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47192. switch (loopMode) {
  47193. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47194. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47195. return floatValue;
  47196. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47197. return offsetValue * repeatCount + floatValue;
  47198. }
  47199. break;
  47200. // Quaternion
  47201. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47202. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47203. switch (loopMode) {
  47204. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47205. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47206. return quatValue;
  47207. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47208. return quatValue.add(offsetValue.scale(repeatCount));
  47209. }
  47210. return quatValue;
  47211. // Vector3
  47212. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47213. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47214. switch (loopMode) {
  47215. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47216. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47217. return vec3Value;
  47218. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47219. return vec3Value.add(offsetValue.scale(repeatCount));
  47220. }
  47221. // Vector2
  47222. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47223. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47224. switch (loopMode) {
  47225. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47226. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47227. return vec2Value;
  47228. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47229. return vec2Value.add(offsetValue.scale(repeatCount));
  47230. }
  47231. // Size
  47232. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47233. switch (loopMode) {
  47234. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47235. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47236. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47237. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47238. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47239. }
  47240. // Color3
  47241. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47242. switch (loopMode) {
  47243. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47244. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47245. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47246. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47247. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47248. }
  47249. // Matrix
  47250. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47251. switch (loopMode) {
  47252. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47253. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47254. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47255. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47256. }
  47257. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47258. return startValue;
  47259. }
  47260. default:
  47261. break;
  47262. }
  47263. break;
  47264. }
  47265. }
  47266. return this._getKeyValue(keys[keys.length - 1].value);
  47267. };
  47268. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47269. if (blend === void 0) { blend = false; }
  47270. // Set value
  47271. var path;
  47272. var destination;
  47273. var targetPropertyPath = this._animation.targetPropertyPath;
  47274. if (targetPropertyPath.length > 1) {
  47275. var property = this._target[targetPropertyPath[0]];
  47276. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47277. property = property[targetPropertyPath[index]];
  47278. }
  47279. path = targetPropertyPath[targetPropertyPath.length - 1];
  47280. destination = property;
  47281. }
  47282. else {
  47283. path = targetPropertyPath[0];
  47284. destination = this._target;
  47285. }
  47286. // Blending
  47287. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47288. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47289. if (enableBlending && this._blendingFactor <= 1.0) {
  47290. if (!this._originalBlendValue) {
  47291. if (destination[path].clone) {
  47292. this._originalBlendValue = destination[path].clone();
  47293. }
  47294. else {
  47295. this._originalBlendValue = destination[path];
  47296. }
  47297. }
  47298. if (this._originalBlendValue.prototype) {
  47299. if (this._originalBlendValue.prototype.Lerp) {
  47300. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47301. }
  47302. else {
  47303. destination[path] = currentValue;
  47304. }
  47305. }
  47306. else if (this._originalBlendValue.m) {
  47307. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47308. }
  47309. else {
  47310. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47311. }
  47312. this._blendingFactor += blendingSpeed;
  47313. }
  47314. else {
  47315. destination[path] = currentValue;
  47316. }
  47317. if (this._target.markAsDirty) {
  47318. this._target.markAsDirty(this._animation.targetProperty);
  47319. }
  47320. };
  47321. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47322. if (this._target && this._target.animationPropertiesOverride) {
  47323. return this._target.animationPropertiesOverride.loopMode;
  47324. }
  47325. return this._animation.loopMode;
  47326. };
  47327. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47328. var keys = this._animation.getKeys();
  47329. if (frame < keys[0].frame) {
  47330. frame = keys[0].frame;
  47331. }
  47332. else if (frame > keys[keys.length - 1].frame) {
  47333. frame = keys[keys.length - 1].frame;
  47334. }
  47335. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47336. this.setValue(currentValue);
  47337. };
  47338. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47339. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47340. this._ratioOffset = this._previousRatio - newRatio;
  47341. };
  47342. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47343. if (blend === void 0) { blend = false; }
  47344. var targetPropertyPath = this._animation.targetPropertyPath;
  47345. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47346. this._stopped = true;
  47347. return false;
  47348. }
  47349. var returnValue = true;
  47350. var keys = this._animation.getKeys();
  47351. // Adding a start key at frame 0 if missing
  47352. if (keys[0].frame !== 0) {
  47353. var newKey = { frame: 0, value: keys[0].value };
  47354. keys.splice(0, 0, newKey);
  47355. }
  47356. // Check limits
  47357. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47358. from = keys[0].frame;
  47359. }
  47360. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47361. to = keys[keys.length - 1].frame;
  47362. }
  47363. //to and from cannot be the same key
  47364. if (from === to) {
  47365. if (from > keys[0].frame) {
  47366. from--;
  47367. }
  47368. else if (to < keys[keys.length - 1].frame) {
  47369. to++;
  47370. }
  47371. }
  47372. // Compute ratio
  47373. var range = to - from;
  47374. var offsetValue;
  47375. // ratio represents the frame delta between from and to
  47376. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47377. var highLimitValue = 0;
  47378. this._previousDelay = delay;
  47379. this._previousRatio = ratio;
  47380. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47381. returnValue = false;
  47382. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47383. }
  47384. else {
  47385. // Get max value if required
  47386. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47387. var keyOffset = to.toString() + from.toString();
  47388. if (!this._offsetsCache[keyOffset]) {
  47389. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47390. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47391. switch (this._animation.dataType) {
  47392. // Float
  47393. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47394. this._offsetsCache[keyOffset] = toValue - fromValue;
  47395. break;
  47396. // Quaternion
  47397. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47398. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47399. break;
  47400. // Vector3
  47401. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47402. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47403. // Vector2
  47404. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47405. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47406. // Size
  47407. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47408. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47409. // Color3
  47410. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47411. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47412. default:
  47413. break;
  47414. }
  47415. this._highLimitsCache[keyOffset] = toValue;
  47416. }
  47417. highLimitValue = this._highLimitsCache[keyOffset];
  47418. offsetValue = this._offsetsCache[keyOffset];
  47419. }
  47420. }
  47421. if (offsetValue === undefined) {
  47422. switch (this._animation.dataType) {
  47423. // Float
  47424. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47425. offsetValue = 0;
  47426. break;
  47427. // Quaternion
  47428. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47429. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47430. break;
  47431. // Vector3
  47432. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47433. offsetValue = BABYLON.Vector3.Zero();
  47434. break;
  47435. // Vector2
  47436. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47437. offsetValue = BABYLON.Vector2.Zero();
  47438. break;
  47439. // Size
  47440. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47441. offsetValue = BABYLON.Size.Zero();
  47442. break;
  47443. // Color3
  47444. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47445. offsetValue = BABYLON.Color3.Black();
  47446. }
  47447. }
  47448. // Compute value
  47449. var repeatCount = (ratio / range) >> 0;
  47450. var currentFrame = returnValue ? from + ratio % range : to;
  47451. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47452. // Set value
  47453. this.setValue(currentValue);
  47454. // Check events
  47455. var events = this._animation.getEvents();
  47456. for (var index = 0; index < events.length; index++) {
  47457. // Make sure current frame has passed event frame and that event frame is within the current range
  47458. // Also, handle both forward and reverse animations
  47459. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47460. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47461. var event = events[index];
  47462. if (!event.isDone) {
  47463. // If event should be done only once, remove it.
  47464. if (event.onlyOnce) {
  47465. events.splice(index, 1);
  47466. index--;
  47467. }
  47468. event.isDone = true;
  47469. event.action();
  47470. } // Don't do anything if the event has already be done.
  47471. }
  47472. else if (events[index].isDone && !events[index].onlyOnce) {
  47473. // reset event, the animation is looping
  47474. events[index].isDone = false;
  47475. }
  47476. }
  47477. if (!returnValue) {
  47478. this._stopped = true;
  47479. }
  47480. return returnValue;
  47481. };
  47482. return RuntimeAnimation;
  47483. }());
  47484. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47485. })(BABYLON || (BABYLON = {}));
  47486. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47487. var BABYLON;
  47488. (function (BABYLON) {
  47489. var Animatable = /** @class */ (function () {
  47490. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47491. if (fromFrame === void 0) { fromFrame = 0; }
  47492. if (toFrame === void 0) { toFrame = 100; }
  47493. if (loopAnimation === void 0) { loopAnimation = false; }
  47494. if (speedRatio === void 0) { speedRatio = 1.0; }
  47495. this.target = target;
  47496. this.fromFrame = fromFrame;
  47497. this.toFrame = toFrame;
  47498. this.loopAnimation = loopAnimation;
  47499. this.onAnimationEnd = onAnimationEnd;
  47500. this._localDelayOffset = null;
  47501. this._pausedDelay = null;
  47502. this._runtimeAnimations = new Array();
  47503. this._paused = false;
  47504. this._speedRatio = 1;
  47505. this.animationStarted = false;
  47506. if (animations) {
  47507. this.appendAnimations(target, animations);
  47508. }
  47509. this._speedRatio = speedRatio;
  47510. this._scene = scene;
  47511. scene._activeAnimatables.push(this);
  47512. }
  47513. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47514. get: function () {
  47515. return this._speedRatio;
  47516. },
  47517. set: function (value) {
  47518. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47519. var animation = this._runtimeAnimations[index];
  47520. animation._prepareForSpeedRatioChange(value);
  47521. }
  47522. this._speedRatio = value;
  47523. },
  47524. enumerable: true,
  47525. configurable: true
  47526. });
  47527. // Methods
  47528. Animatable.prototype.getAnimations = function () {
  47529. return this._runtimeAnimations;
  47530. };
  47531. Animatable.prototype.appendAnimations = function (target, animations) {
  47532. for (var index = 0; index < animations.length; index++) {
  47533. var animation = animations[index];
  47534. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47535. }
  47536. };
  47537. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47538. var runtimeAnimations = this._runtimeAnimations;
  47539. for (var index = 0; index < runtimeAnimations.length; index++) {
  47540. if (runtimeAnimations[index].animation.targetProperty === property) {
  47541. return runtimeAnimations[index].animation;
  47542. }
  47543. }
  47544. return null;
  47545. };
  47546. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47547. var runtimeAnimations = this._runtimeAnimations;
  47548. for (var index = 0; index < runtimeAnimations.length; index++) {
  47549. if (runtimeAnimations[index].animation.targetProperty === property) {
  47550. return runtimeAnimations[index];
  47551. }
  47552. }
  47553. return null;
  47554. };
  47555. Animatable.prototype.reset = function () {
  47556. var runtimeAnimations = this._runtimeAnimations;
  47557. for (var index = 0; index < runtimeAnimations.length; index++) {
  47558. runtimeAnimations[index].reset();
  47559. }
  47560. // Reset to original value
  47561. for (index = 0; index < runtimeAnimations.length; index++) {
  47562. var animation = runtimeAnimations[index];
  47563. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47564. }
  47565. this._localDelayOffset = null;
  47566. this._pausedDelay = null;
  47567. };
  47568. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47569. var runtimeAnimations = this._runtimeAnimations;
  47570. for (var index = 0; index < runtimeAnimations.length; index++) {
  47571. runtimeAnimations[index].animation.enableBlending = true;
  47572. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47573. }
  47574. };
  47575. Animatable.prototype.disableBlending = function () {
  47576. var runtimeAnimations = this._runtimeAnimations;
  47577. for (var index = 0; index < runtimeAnimations.length; index++) {
  47578. runtimeAnimations[index].animation.enableBlending = false;
  47579. }
  47580. };
  47581. Animatable.prototype.goToFrame = function (frame) {
  47582. var runtimeAnimations = this._runtimeAnimations;
  47583. if (runtimeAnimations[0]) {
  47584. var fps = runtimeAnimations[0].animation.framePerSecond;
  47585. var currentFrame = runtimeAnimations[0].currentFrame;
  47586. var adjustTime = frame - currentFrame;
  47587. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47588. if (this._localDelayOffset === null) {
  47589. this._localDelayOffset = 0;
  47590. }
  47591. this._localDelayOffset -= delay;
  47592. }
  47593. for (var index = 0; index < runtimeAnimations.length; index++) {
  47594. runtimeAnimations[index].goToFrame(frame);
  47595. }
  47596. };
  47597. Animatable.prototype.pause = function () {
  47598. if (this._paused) {
  47599. return;
  47600. }
  47601. this._paused = true;
  47602. };
  47603. Animatable.prototype.restart = function () {
  47604. this._paused = false;
  47605. };
  47606. Animatable.prototype.stop = function (animationName) {
  47607. if (animationName) {
  47608. var idx = this._scene._activeAnimatables.indexOf(this);
  47609. if (idx > -1) {
  47610. var runtimeAnimations = this._runtimeAnimations;
  47611. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47612. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47613. continue;
  47614. }
  47615. runtimeAnimations[index].dispose();
  47616. runtimeAnimations.splice(index, 1);
  47617. }
  47618. if (runtimeAnimations.length == 0) {
  47619. this._scene._activeAnimatables.splice(idx, 1);
  47620. if (this.onAnimationEnd) {
  47621. this.onAnimationEnd();
  47622. }
  47623. }
  47624. }
  47625. }
  47626. else {
  47627. var index = this._scene._activeAnimatables.indexOf(this);
  47628. if (index > -1) {
  47629. this._scene._activeAnimatables.splice(index, 1);
  47630. var runtimeAnimations = this._runtimeAnimations;
  47631. for (var index = 0; index < runtimeAnimations.length; index++) {
  47632. runtimeAnimations[index].dispose();
  47633. }
  47634. if (this.onAnimationEnd) {
  47635. this.onAnimationEnd();
  47636. }
  47637. }
  47638. }
  47639. };
  47640. Animatable.prototype._animate = function (delay) {
  47641. if (this._paused) {
  47642. this.animationStarted = false;
  47643. if (this._pausedDelay === null) {
  47644. this._pausedDelay = delay;
  47645. }
  47646. return true;
  47647. }
  47648. if (this._localDelayOffset === null) {
  47649. this._localDelayOffset = delay;
  47650. this._pausedDelay = null;
  47651. }
  47652. else if (this._pausedDelay !== null) {
  47653. this._localDelayOffset += delay - this._pausedDelay;
  47654. this._pausedDelay = null;
  47655. }
  47656. // Animating
  47657. var running = false;
  47658. var runtimeAnimations = this._runtimeAnimations;
  47659. var index;
  47660. for (index = 0; index < runtimeAnimations.length; index++) {
  47661. var animation = runtimeAnimations[index];
  47662. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47663. running = running || isRunning;
  47664. }
  47665. this.animationStarted = running;
  47666. if (!running) {
  47667. // Remove from active animatables
  47668. index = this._scene._activeAnimatables.indexOf(this);
  47669. this._scene._activeAnimatables.splice(index, 1);
  47670. // Dispose all runtime animations
  47671. for (index = 0; index < runtimeAnimations.length; index++) {
  47672. runtimeAnimations[index].dispose();
  47673. }
  47674. }
  47675. if (!running && this.onAnimationEnd) {
  47676. this.onAnimationEnd();
  47677. this.onAnimationEnd = null;
  47678. }
  47679. return running;
  47680. };
  47681. return Animatable;
  47682. }());
  47683. BABYLON.Animatable = Animatable;
  47684. })(BABYLON || (BABYLON = {}));
  47685. //# sourceMappingURL=babylon.animatable.js.map
  47686. var BABYLON;
  47687. (function (BABYLON) {
  47688. var EasingFunction = /** @class */ (function () {
  47689. function EasingFunction() {
  47690. // Properties
  47691. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47692. }
  47693. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47694. get: function () {
  47695. return EasingFunction._EASINGMODE_EASEIN;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47701. get: function () {
  47702. return EasingFunction._EASINGMODE_EASEOUT;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47708. get: function () {
  47709. return EasingFunction._EASINGMODE_EASEINOUT;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47715. var n = Math.min(Math.max(easingMode, 0), 2);
  47716. this._easingMode = n;
  47717. };
  47718. EasingFunction.prototype.getEasingMode = function () {
  47719. return this._easingMode;
  47720. };
  47721. EasingFunction.prototype.easeInCore = function (gradient) {
  47722. throw new Error('You must implement this method');
  47723. };
  47724. EasingFunction.prototype.ease = function (gradient) {
  47725. switch (this._easingMode) {
  47726. case EasingFunction.EASINGMODE_EASEIN:
  47727. return this.easeInCore(gradient);
  47728. case EasingFunction.EASINGMODE_EASEOUT:
  47729. return (1 - this.easeInCore(1 - gradient));
  47730. }
  47731. if (gradient >= 0.5) {
  47732. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47733. }
  47734. return (this.easeInCore(gradient * 2) * 0.5);
  47735. };
  47736. //Statics
  47737. EasingFunction._EASINGMODE_EASEIN = 0;
  47738. EasingFunction._EASINGMODE_EASEOUT = 1;
  47739. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47740. return EasingFunction;
  47741. }());
  47742. BABYLON.EasingFunction = EasingFunction;
  47743. var CircleEase = /** @class */ (function (_super) {
  47744. __extends(CircleEase, _super);
  47745. function CircleEase() {
  47746. return _super !== null && _super.apply(this, arguments) || this;
  47747. }
  47748. CircleEase.prototype.easeInCore = function (gradient) {
  47749. gradient = Math.max(0, Math.min(1, gradient));
  47750. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47751. };
  47752. return CircleEase;
  47753. }(EasingFunction));
  47754. BABYLON.CircleEase = CircleEase;
  47755. var BackEase = /** @class */ (function (_super) {
  47756. __extends(BackEase, _super);
  47757. function BackEase(amplitude) {
  47758. if (amplitude === void 0) { amplitude = 1; }
  47759. var _this = _super.call(this) || this;
  47760. _this.amplitude = amplitude;
  47761. return _this;
  47762. }
  47763. BackEase.prototype.easeInCore = function (gradient) {
  47764. var num = Math.max(0, this.amplitude);
  47765. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47766. };
  47767. return BackEase;
  47768. }(EasingFunction));
  47769. BABYLON.BackEase = BackEase;
  47770. var BounceEase = /** @class */ (function (_super) {
  47771. __extends(BounceEase, _super);
  47772. function BounceEase(bounces, bounciness) {
  47773. if (bounces === void 0) { bounces = 3; }
  47774. if (bounciness === void 0) { bounciness = 2; }
  47775. var _this = _super.call(this) || this;
  47776. _this.bounces = bounces;
  47777. _this.bounciness = bounciness;
  47778. return _this;
  47779. }
  47780. BounceEase.prototype.easeInCore = function (gradient) {
  47781. var y = Math.max(0.0, this.bounces);
  47782. var bounciness = this.bounciness;
  47783. if (bounciness <= 1.0) {
  47784. bounciness = 1.001;
  47785. }
  47786. var num9 = Math.pow(bounciness, y);
  47787. var num5 = 1.0 - bounciness;
  47788. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47789. var num15 = gradient * num4;
  47790. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47791. var num3 = Math.floor(num65);
  47792. var num13 = num3 + 1.0;
  47793. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47794. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47795. var num7 = (num8 + num12) * 0.5;
  47796. var num6 = gradient - num7;
  47797. var num2 = num7 - num8;
  47798. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47799. };
  47800. return BounceEase;
  47801. }(EasingFunction));
  47802. BABYLON.BounceEase = BounceEase;
  47803. var CubicEase = /** @class */ (function (_super) {
  47804. __extends(CubicEase, _super);
  47805. function CubicEase() {
  47806. return _super !== null && _super.apply(this, arguments) || this;
  47807. }
  47808. CubicEase.prototype.easeInCore = function (gradient) {
  47809. return (gradient * gradient * gradient);
  47810. };
  47811. return CubicEase;
  47812. }(EasingFunction));
  47813. BABYLON.CubicEase = CubicEase;
  47814. var ElasticEase = /** @class */ (function (_super) {
  47815. __extends(ElasticEase, _super);
  47816. function ElasticEase(oscillations, springiness) {
  47817. if (oscillations === void 0) { oscillations = 3; }
  47818. if (springiness === void 0) { springiness = 3; }
  47819. var _this = _super.call(this) || this;
  47820. _this.oscillations = oscillations;
  47821. _this.springiness = springiness;
  47822. return _this;
  47823. }
  47824. ElasticEase.prototype.easeInCore = function (gradient) {
  47825. var num2;
  47826. var num3 = Math.max(0.0, this.oscillations);
  47827. var num = Math.max(0.0, this.springiness);
  47828. if (num == 0) {
  47829. num2 = gradient;
  47830. }
  47831. else {
  47832. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47833. }
  47834. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47835. };
  47836. return ElasticEase;
  47837. }(EasingFunction));
  47838. BABYLON.ElasticEase = ElasticEase;
  47839. var ExponentialEase = /** @class */ (function (_super) {
  47840. __extends(ExponentialEase, _super);
  47841. function ExponentialEase(exponent) {
  47842. if (exponent === void 0) { exponent = 2; }
  47843. var _this = _super.call(this) || this;
  47844. _this.exponent = exponent;
  47845. return _this;
  47846. }
  47847. ExponentialEase.prototype.easeInCore = function (gradient) {
  47848. if (this.exponent <= 0) {
  47849. return gradient;
  47850. }
  47851. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47852. };
  47853. return ExponentialEase;
  47854. }(EasingFunction));
  47855. BABYLON.ExponentialEase = ExponentialEase;
  47856. var PowerEase = /** @class */ (function (_super) {
  47857. __extends(PowerEase, _super);
  47858. function PowerEase(power) {
  47859. if (power === void 0) { power = 2; }
  47860. var _this = _super.call(this) || this;
  47861. _this.power = power;
  47862. return _this;
  47863. }
  47864. PowerEase.prototype.easeInCore = function (gradient) {
  47865. var y = Math.max(0.0, this.power);
  47866. return Math.pow(gradient, y);
  47867. };
  47868. return PowerEase;
  47869. }(EasingFunction));
  47870. BABYLON.PowerEase = PowerEase;
  47871. var QuadraticEase = /** @class */ (function (_super) {
  47872. __extends(QuadraticEase, _super);
  47873. function QuadraticEase() {
  47874. return _super !== null && _super.apply(this, arguments) || this;
  47875. }
  47876. QuadraticEase.prototype.easeInCore = function (gradient) {
  47877. return (gradient * gradient);
  47878. };
  47879. return QuadraticEase;
  47880. }(EasingFunction));
  47881. BABYLON.QuadraticEase = QuadraticEase;
  47882. var QuarticEase = /** @class */ (function (_super) {
  47883. __extends(QuarticEase, _super);
  47884. function QuarticEase() {
  47885. return _super !== null && _super.apply(this, arguments) || this;
  47886. }
  47887. QuarticEase.prototype.easeInCore = function (gradient) {
  47888. return (gradient * gradient * gradient * gradient);
  47889. };
  47890. return QuarticEase;
  47891. }(EasingFunction));
  47892. BABYLON.QuarticEase = QuarticEase;
  47893. var QuinticEase = /** @class */ (function (_super) {
  47894. __extends(QuinticEase, _super);
  47895. function QuinticEase() {
  47896. return _super !== null && _super.apply(this, arguments) || this;
  47897. }
  47898. QuinticEase.prototype.easeInCore = function (gradient) {
  47899. return (gradient * gradient * gradient * gradient * gradient);
  47900. };
  47901. return QuinticEase;
  47902. }(EasingFunction));
  47903. BABYLON.QuinticEase = QuinticEase;
  47904. var SineEase = /** @class */ (function (_super) {
  47905. __extends(SineEase, _super);
  47906. function SineEase() {
  47907. return _super !== null && _super.apply(this, arguments) || this;
  47908. }
  47909. SineEase.prototype.easeInCore = function (gradient) {
  47910. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47911. };
  47912. return SineEase;
  47913. }(EasingFunction));
  47914. BABYLON.SineEase = SineEase;
  47915. var BezierCurveEase = /** @class */ (function (_super) {
  47916. __extends(BezierCurveEase, _super);
  47917. function BezierCurveEase(x1, y1, x2, y2) {
  47918. if (x1 === void 0) { x1 = 0; }
  47919. if (y1 === void 0) { y1 = 0; }
  47920. if (x2 === void 0) { x2 = 1; }
  47921. if (y2 === void 0) { y2 = 1; }
  47922. var _this = _super.call(this) || this;
  47923. _this.x1 = x1;
  47924. _this.y1 = y1;
  47925. _this.x2 = x2;
  47926. _this.y2 = y2;
  47927. return _this;
  47928. }
  47929. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47930. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47931. };
  47932. return BezierCurveEase;
  47933. }(EasingFunction));
  47934. BABYLON.BezierCurveEase = BezierCurveEase;
  47935. })(BABYLON || (BABYLON = {}));
  47936. //# sourceMappingURL=babylon.easing.js.map
  47937. var BABYLON;
  47938. (function (BABYLON) {
  47939. var Condition = /** @class */ (function () {
  47940. function Condition(actionManager) {
  47941. this._actionManager = actionManager;
  47942. }
  47943. Condition.prototype.isValid = function () {
  47944. return true;
  47945. };
  47946. Condition.prototype._getProperty = function (propertyPath) {
  47947. return this._actionManager._getProperty(propertyPath);
  47948. };
  47949. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47950. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47951. };
  47952. Condition.prototype.serialize = function () {
  47953. };
  47954. Condition.prototype._serialize = function (serializedCondition) {
  47955. return {
  47956. type: 2,
  47957. children: [],
  47958. name: serializedCondition.name,
  47959. properties: serializedCondition.properties
  47960. };
  47961. };
  47962. return Condition;
  47963. }());
  47964. BABYLON.Condition = Condition;
  47965. var ValueCondition = /** @class */ (function (_super) {
  47966. __extends(ValueCondition, _super);
  47967. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47968. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47969. var _this = _super.call(this, actionManager) || this;
  47970. _this.propertyPath = propertyPath;
  47971. _this.value = value;
  47972. _this.operator = operator;
  47973. _this._target = target;
  47974. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47975. _this._property = _this._getProperty(_this.propertyPath);
  47976. return _this;
  47977. }
  47978. Object.defineProperty(ValueCondition, "IsEqual", {
  47979. get: function () {
  47980. return ValueCondition._IsEqual;
  47981. },
  47982. enumerable: true,
  47983. configurable: true
  47984. });
  47985. Object.defineProperty(ValueCondition, "IsDifferent", {
  47986. get: function () {
  47987. return ValueCondition._IsDifferent;
  47988. },
  47989. enumerable: true,
  47990. configurable: true
  47991. });
  47992. Object.defineProperty(ValueCondition, "IsGreater", {
  47993. get: function () {
  47994. return ValueCondition._IsGreater;
  47995. },
  47996. enumerable: true,
  47997. configurable: true
  47998. });
  47999. Object.defineProperty(ValueCondition, "IsLesser", {
  48000. get: function () {
  48001. return ValueCondition._IsLesser;
  48002. },
  48003. enumerable: true,
  48004. configurable: true
  48005. });
  48006. // Methods
  48007. ValueCondition.prototype.isValid = function () {
  48008. switch (this.operator) {
  48009. case ValueCondition.IsGreater:
  48010. return this._effectiveTarget[this._property] > this.value;
  48011. case ValueCondition.IsLesser:
  48012. return this._effectiveTarget[this._property] < this.value;
  48013. case ValueCondition.IsEqual:
  48014. case ValueCondition.IsDifferent:
  48015. var check;
  48016. if (this.value.equals) {
  48017. check = this.value.equals(this._effectiveTarget[this._property]);
  48018. }
  48019. else {
  48020. check = this.value === this._effectiveTarget[this._property];
  48021. }
  48022. return this.operator === ValueCondition.IsEqual ? check : !check;
  48023. }
  48024. return false;
  48025. };
  48026. ValueCondition.prototype.serialize = function () {
  48027. return this._serialize({
  48028. name: "ValueCondition",
  48029. properties: [
  48030. BABYLON.Action._GetTargetProperty(this._target),
  48031. { name: "propertyPath", value: this.propertyPath },
  48032. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48033. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48034. ]
  48035. });
  48036. };
  48037. ValueCondition.GetOperatorName = function (operator) {
  48038. switch (operator) {
  48039. case ValueCondition._IsEqual: return "IsEqual";
  48040. case ValueCondition._IsDifferent: return "IsDifferent";
  48041. case ValueCondition._IsGreater: return "IsGreater";
  48042. case ValueCondition._IsLesser: return "IsLesser";
  48043. default: return "";
  48044. }
  48045. };
  48046. // Statics
  48047. ValueCondition._IsEqual = 0;
  48048. ValueCondition._IsDifferent = 1;
  48049. ValueCondition._IsGreater = 2;
  48050. ValueCondition._IsLesser = 3;
  48051. return ValueCondition;
  48052. }(Condition));
  48053. BABYLON.ValueCondition = ValueCondition;
  48054. var PredicateCondition = /** @class */ (function (_super) {
  48055. __extends(PredicateCondition, _super);
  48056. function PredicateCondition(actionManager, predicate) {
  48057. var _this = _super.call(this, actionManager) || this;
  48058. _this.predicate = predicate;
  48059. return _this;
  48060. }
  48061. PredicateCondition.prototype.isValid = function () {
  48062. return this.predicate();
  48063. };
  48064. return PredicateCondition;
  48065. }(Condition));
  48066. BABYLON.PredicateCondition = PredicateCondition;
  48067. var StateCondition = /** @class */ (function (_super) {
  48068. __extends(StateCondition, _super);
  48069. function StateCondition(actionManager, target, value) {
  48070. var _this = _super.call(this, actionManager) || this;
  48071. _this.value = value;
  48072. _this._target = target;
  48073. return _this;
  48074. }
  48075. // Methods
  48076. StateCondition.prototype.isValid = function () {
  48077. return this._target.state === this.value;
  48078. };
  48079. StateCondition.prototype.serialize = function () {
  48080. return this._serialize({
  48081. name: "StateCondition",
  48082. properties: [
  48083. BABYLON.Action._GetTargetProperty(this._target),
  48084. { name: "value", value: this.value }
  48085. ]
  48086. });
  48087. };
  48088. return StateCondition;
  48089. }(Condition));
  48090. BABYLON.StateCondition = StateCondition;
  48091. })(BABYLON || (BABYLON = {}));
  48092. //# sourceMappingURL=babylon.condition.js.map
  48093. var BABYLON;
  48094. (function (BABYLON) {
  48095. var Action = /** @class */ (function () {
  48096. function Action(triggerOptions, condition) {
  48097. this.triggerOptions = triggerOptions;
  48098. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48099. if (triggerOptions.parameter) {
  48100. this.trigger = triggerOptions.trigger;
  48101. this._triggerParameter = triggerOptions.parameter;
  48102. }
  48103. else {
  48104. this.trigger = triggerOptions;
  48105. }
  48106. this._nextActiveAction = this;
  48107. this._condition = condition;
  48108. }
  48109. // Methods
  48110. Action.prototype._prepare = function () {
  48111. };
  48112. Action.prototype.getTriggerParameter = function () {
  48113. return this._triggerParameter;
  48114. };
  48115. Action.prototype._executeCurrent = function (evt) {
  48116. if (this._nextActiveAction._condition) {
  48117. var condition = this._nextActiveAction._condition;
  48118. var currentRenderId = this._actionManager.getScene().getRenderId();
  48119. // We cache the current evaluation for the current frame
  48120. if (condition._evaluationId === currentRenderId) {
  48121. if (!condition._currentResult) {
  48122. return;
  48123. }
  48124. }
  48125. else {
  48126. condition._evaluationId = currentRenderId;
  48127. if (!condition.isValid()) {
  48128. condition._currentResult = false;
  48129. return;
  48130. }
  48131. condition._currentResult = true;
  48132. }
  48133. }
  48134. this.onBeforeExecuteObservable.notifyObservers(this);
  48135. this._nextActiveAction.execute(evt);
  48136. this.skipToNextActiveAction();
  48137. };
  48138. Action.prototype.execute = function (evt) {
  48139. };
  48140. Action.prototype.skipToNextActiveAction = function () {
  48141. if (this._nextActiveAction._child) {
  48142. if (!this._nextActiveAction._child._actionManager) {
  48143. this._nextActiveAction._child._actionManager = this._actionManager;
  48144. }
  48145. this._nextActiveAction = this._nextActiveAction._child;
  48146. }
  48147. else {
  48148. this._nextActiveAction = this;
  48149. }
  48150. };
  48151. Action.prototype.then = function (action) {
  48152. this._child = action;
  48153. action._actionManager = this._actionManager;
  48154. action._prepare();
  48155. return action;
  48156. };
  48157. Action.prototype._getProperty = function (propertyPath) {
  48158. return this._actionManager._getProperty(propertyPath);
  48159. };
  48160. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48161. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48162. };
  48163. Action.prototype.serialize = function (parent) {
  48164. };
  48165. // Called by BABYLON.Action objects in serialize(...). Internal use
  48166. Action.prototype._serialize = function (serializedAction, parent) {
  48167. var serializationObject = {
  48168. type: 1,
  48169. children: [],
  48170. name: serializedAction.name,
  48171. properties: serializedAction.properties || []
  48172. };
  48173. // Serialize child
  48174. if (this._child) {
  48175. this._child.serialize(serializationObject);
  48176. }
  48177. // Check if "this" has a condition
  48178. if (this._condition) {
  48179. var serializedCondition = this._condition.serialize();
  48180. serializedCondition.children.push(serializationObject);
  48181. if (parent) {
  48182. parent.children.push(serializedCondition);
  48183. }
  48184. return serializedCondition;
  48185. }
  48186. if (parent) {
  48187. parent.children.push(serializationObject);
  48188. }
  48189. return serializationObject;
  48190. };
  48191. Action._SerializeValueAsString = function (value) {
  48192. if (typeof value === "number") {
  48193. return value.toString();
  48194. }
  48195. if (typeof value === "boolean") {
  48196. return value ? "true" : "false";
  48197. }
  48198. if (value instanceof BABYLON.Vector2) {
  48199. return value.x + ", " + value.y;
  48200. }
  48201. if (value instanceof BABYLON.Vector3) {
  48202. return value.x + ", " + value.y + ", " + value.z;
  48203. }
  48204. if (value instanceof BABYLON.Color3) {
  48205. return value.r + ", " + value.g + ", " + value.b;
  48206. }
  48207. if (value instanceof BABYLON.Color4) {
  48208. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48209. }
  48210. return value; // string
  48211. };
  48212. Action._GetTargetProperty = function (target) {
  48213. return {
  48214. name: "target",
  48215. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48216. : target instanceof BABYLON.Light ? "LightProperties"
  48217. : target instanceof BABYLON.Camera ? "CameraProperties"
  48218. : "SceneProperties",
  48219. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48220. };
  48221. };
  48222. return Action;
  48223. }());
  48224. BABYLON.Action = Action;
  48225. })(BABYLON || (BABYLON = {}));
  48226. //# sourceMappingURL=babylon.action.js.map
  48227. var BABYLON;
  48228. (function (BABYLON) {
  48229. /**
  48230. * ActionEvent is the event beint sent when an action is triggered.
  48231. */
  48232. var ActionEvent = /** @class */ (function () {
  48233. /**
  48234. * @param source The mesh or sprite that triggered the action.
  48235. * @param pointerX The X mouse cursor position at the time of the event
  48236. * @param pointerY The Y mouse cursor position at the time of the event
  48237. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48238. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48239. */
  48240. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48241. this.source = source;
  48242. this.pointerX = pointerX;
  48243. this.pointerY = pointerY;
  48244. this.meshUnderPointer = meshUnderPointer;
  48245. this.sourceEvent = sourceEvent;
  48246. this.additionalData = additionalData;
  48247. }
  48248. /**
  48249. * Helper function to auto-create an ActionEvent from a source mesh.
  48250. * @param source The source mesh that triggered the event
  48251. * @param evt {Event} The original (browser) event
  48252. */
  48253. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48254. var scene = source.getScene();
  48255. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48256. };
  48257. /**
  48258. * Helper function to auto-create an ActionEvent from a source mesh.
  48259. * @param source The source sprite that triggered the event
  48260. * @param scene Scene associated with the sprite
  48261. * @param evt {Event} The original (browser) event
  48262. */
  48263. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48264. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48265. };
  48266. /**
  48267. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48268. * @param scene the scene where the event occurred
  48269. * @param evt {Event} The original (browser) event
  48270. */
  48271. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48272. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48273. };
  48274. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48275. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48276. };
  48277. return ActionEvent;
  48278. }());
  48279. BABYLON.ActionEvent = ActionEvent;
  48280. /**
  48281. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48282. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48283. */
  48284. var ActionManager = /** @class */ (function () {
  48285. function ActionManager(scene) {
  48286. // Members
  48287. this.actions = new Array();
  48288. this.hoverCursor = '';
  48289. this._scene = scene;
  48290. scene._actionManagers.push(this);
  48291. }
  48292. Object.defineProperty(ActionManager, "NothingTrigger", {
  48293. get: function () {
  48294. return ActionManager._NothingTrigger;
  48295. },
  48296. enumerable: true,
  48297. configurable: true
  48298. });
  48299. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48300. get: function () {
  48301. return ActionManager._OnPickTrigger;
  48302. },
  48303. enumerable: true,
  48304. configurable: true
  48305. });
  48306. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48307. get: function () {
  48308. return ActionManager._OnLeftPickTrigger;
  48309. },
  48310. enumerable: true,
  48311. configurable: true
  48312. });
  48313. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48314. get: function () {
  48315. return ActionManager._OnRightPickTrigger;
  48316. },
  48317. enumerable: true,
  48318. configurable: true
  48319. });
  48320. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48321. get: function () {
  48322. return ActionManager._OnCenterPickTrigger;
  48323. },
  48324. enumerable: true,
  48325. configurable: true
  48326. });
  48327. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48328. get: function () {
  48329. return ActionManager._OnPickDownTrigger;
  48330. },
  48331. enumerable: true,
  48332. configurable: true
  48333. });
  48334. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48335. get: function () {
  48336. return ActionManager._OnDoublePickTrigger;
  48337. },
  48338. enumerable: true,
  48339. configurable: true
  48340. });
  48341. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48342. get: function () {
  48343. return ActionManager._OnPickUpTrigger;
  48344. },
  48345. enumerable: true,
  48346. configurable: true
  48347. });
  48348. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48349. /// This trigger will only be raised if you also declared a OnPickDown
  48350. get: function () {
  48351. return ActionManager._OnPickOutTrigger;
  48352. },
  48353. enumerable: true,
  48354. configurable: true
  48355. });
  48356. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48357. get: function () {
  48358. return ActionManager._OnLongPressTrigger;
  48359. },
  48360. enumerable: true,
  48361. configurable: true
  48362. });
  48363. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48364. get: function () {
  48365. return ActionManager._OnPointerOverTrigger;
  48366. },
  48367. enumerable: true,
  48368. configurable: true
  48369. });
  48370. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48371. get: function () {
  48372. return ActionManager._OnPointerOutTrigger;
  48373. },
  48374. enumerable: true,
  48375. configurable: true
  48376. });
  48377. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48378. get: function () {
  48379. return ActionManager._OnEveryFrameTrigger;
  48380. },
  48381. enumerable: true,
  48382. configurable: true
  48383. });
  48384. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48385. get: function () {
  48386. return ActionManager._OnIntersectionEnterTrigger;
  48387. },
  48388. enumerable: true,
  48389. configurable: true
  48390. });
  48391. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48392. get: function () {
  48393. return ActionManager._OnIntersectionExitTrigger;
  48394. },
  48395. enumerable: true,
  48396. configurable: true
  48397. });
  48398. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48399. get: function () {
  48400. return ActionManager._OnKeyDownTrigger;
  48401. },
  48402. enumerable: true,
  48403. configurable: true
  48404. });
  48405. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48406. get: function () {
  48407. return ActionManager._OnKeyUpTrigger;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. // Methods
  48413. ActionManager.prototype.dispose = function () {
  48414. var index = this._scene._actionManagers.indexOf(this);
  48415. for (var i = 0; i < this.actions.length; i++) {
  48416. var action = this.actions[i];
  48417. ActionManager.Triggers[action.trigger]--;
  48418. if (ActionManager.Triggers[action.trigger] === 0) {
  48419. delete ActionManager.Triggers[action.trigger];
  48420. }
  48421. }
  48422. if (index > -1) {
  48423. this._scene._actionManagers.splice(index, 1);
  48424. }
  48425. };
  48426. ActionManager.prototype.getScene = function () {
  48427. return this._scene;
  48428. };
  48429. /**
  48430. * Does this action manager handles actions of any of the given triggers
  48431. * @param {number[]} triggers - the triggers to be tested
  48432. * @return {boolean} whether one (or more) of the triggers is handeled
  48433. */
  48434. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48435. for (var index = 0; index < this.actions.length; index++) {
  48436. var action = this.actions[index];
  48437. if (triggers.indexOf(action.trigger) > -1) {
  48438. return true;
  48439. }
  48440. }
  48441. return false;
  48442. };
  48443. /**
  48444. * Does this action manager handles actions of a given trigger
  48445. * @param {number} trigger - the trigger to be tested
  48446. * @return {boolean} whether the trigger is handeled
  48447. */
  48448. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48449. for (var index = 0; index < this.actions.length; index++) {
  48450. var action = this.actions[index];
  48451. if (action.trigger === trigger) {
  48452. return true;
  48453. }
  48454. }
  48455. return false;
  48456. };
  48457. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48458. /**
  48459. * Does this action manager has pointer triggers
  48460. * @return {boolean} whether or not it has pointer triggers
  48461. */
  48462. get: function () {
  48463. for (var index = 0; index < this.actions.length; index++) {
  48464. var action = this.actions[index];
  48465. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48466. return true;
  48467. }
  48468. }
  48469. return false;
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48475. /**
  48476. * Does this action manager has pick triggers
  48477. * @return {boolean} whether or not it has pick triggers
  48478. */
  48479. get: function () {
  48480. for (var index = 0; index < this.actions.length; index++) {
  48481. var action = this.actions[index];
  48482. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48483. return true;
  48484. }
  48485. }
  48486. return false;
  48487. },
  48488. enumerable: true,
  48489. configurable: true
  48490. });
  48491. Object.defineProperty(ActionManager, "HasTriggers", {
  48492. /**
  48493. * Does exist one action manager with at least one trigger
  48494. * @return {boolean} whether or not it exists one action manager with one trigger
  48495. **/
  48496. get: function () {
  48497. for (var t in ActionManager.Triggers) {
  48498. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48499. return true;
  48500. }
  48501. }
  48502. return false;
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48508. /**
  48509. * Does exist one action manager with at least one pick trigger
  48510. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48511. **/
  48512. get: function () {
  48513. for (var t in ActionManager.Triggers) {
  48514. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48515. var t_int = parseInt(t);
  48516. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48517. return true;
  48518. }
  48519. }
  48520. }
  48521. return false;
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. /**
  48527. * Does exist one action manager that handles actions of a given trigger
  48528. * @param {number} trigger - the trigger to be tested
  48529. * @return {boolean} whether the trigger is handeled by at least one action manager
  48530. **/
  48531. ActionManager.HasSpecificTrigger = function (trigger) {
  48532. for (var t in ActionManager.Triggers) {
  48533. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48534. var t_int = parseInt(t);
  48535. if (t_int === trigger) {
  48536. return true;
  48537. }
  48538. }
  48539. }
  48540. return false;
  48541. };
  48542. /**
  48543. * Registers an action to this action manager
  48544. * @param {BABYLON.Action} action - the action to be registered
  48545. * @return {BABYLON.Action} the action amended (prepared) after registration
  48546. */
  48547. ActionManager.prototype.registerAction = function (action) {
  48548. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48549. if (this.getScene().actionManager !== this) {
  48550. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48551. return null;
  48552. }
  48553. }
  48554. this.actions.push(action);
  48555. if (ActionManager.Triggers[action.trigger]) {
  48556. ActionManager.Triggers[action.trigger]++;
  48557. }
  48558. else {
  48559. ActionManager.Triggers[action.trigger] = 1;
  48560. }
  48561. action._actionManager = this;
  48562. action._prepare();
  48563. return action;
  48564. };
  48565. /**
  48566. * Unregisters an action to this action manager
  48567. * @param action The action to be unregistered
  48568. * @return whether the action has been unregistered
  48569. */
  48570. ActionManager.prototype.unregisterAction = function (action) {
  48571. var index = this.actions.indexOf(action);
  48572. if (index !== -1) {
  48573. this.actions.splice(index, 1);
  48574. ActionManager.Triggers[action.trigger] -= 1;
  48575. if (ActionManager.Triggers[action.trigger] === 0) {
  48576. delete ActionManager.Triggers[action.trigger];
  48577. }
  48578. delete action._actionManager;
  48579. return true;
  48580. }
  48581. return false;
  48582. };
  48583. /**
  48584. * Process a specific trigger
  48585. * @param {number} trigger - the trigger to process
  48586. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48587. */
  48588. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48589. for (var index = 0; index < this.actions.length; index++) {
  48590. var action = this.actions[index];
  48591. if (action.trigger === trigger) {
  48592. if (evt) {
  48593. if (trigger === ActionManager.OnKeyUpTrigger
  48594. || trigger === ActionManager.OnKeyDownTrigger) {
  48595. var parameter = action.getTriggerParameter();
  48596. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48597. if (!parameter.toLowerCase) {
  48598. continue;
  48599. }
  48600. var lowerCase = parameter.toLowerCase();
  48601. if (lowerCase !== evt.sourceEvent.key) {
  48602. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48603. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48604. if (actualkey !== lowerCase) {
  48605. continue;
  48606. }
  48607. }
  48608. }
  48609. }
  48610. }
  48611. action._executeCurrent(evt);
  48612. }
  48613. }
  48614. };
  48615. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48616. var properties = propertyPath.split(".");
  48617. for (var index = 0; index < properties.length - 1; index++) {
  48618. target = target[properties[index]];
  48619. }
  48620. return target;
  48621. };
  48622. ActionManager.prototype._getProperty = function (propertyPath) {
  48623. var properties = propertyPath.split(".");
  48624. return properties[properties.length - 1];
  48625. };
  48626. ActionManager.prototype.serialize = function (name) {
  48627. var root = {
  48628. children: new Array(),
  48629. name: name,
  48630. type: 3,
  48631. properties: new Array() // Empty for root but required
  48632. };
  48633. for (var i = 0; i < this.actions.length; i++) {
  48634. var triggerObject = {
  48635. type: 0,
  48636. children: new Array(),
  48637. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48638. properties: new Array()
  48639. };
  48640. var triggerOptions = this.actions[i].triggerOptions;
  48641. if (triggerOptions && typeof triggerOptions !== "number") {
  48642. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48643. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48644. }
  48645. else {
  48646. var parameter = {};
  48647. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48648. if (triggerOptions.parameter.mesh) {
  48649. parameter._meshId = triggerOptions.parameter.mesh.id;
  48650. }
  48651. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48652. }
  48653. }
  48654. // Serialize child action, recursively
  48655. this.actions[i].serialize(triggerObject);
  48656. // Add serialized trigger
  48657. root.children.push(triggerObject);
  48658. }
  48659. return root;
  48660. };
  48661. ActionManager.Parse = function (parsedActions, object, scene) {
  48662. var actionManager = new ActionManager(scene);
  48663. if (object === null)
  48664. scene.actionManager = actionManager;
  48665. else
  48666. object.actionManager = actionManager;
  48667. // instanciate a new object
  48668. var instanciate = function (name, params) {
  48669. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48670. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48671. newInstance.constructor.apply(newInstance, params);
  48672. return newInstance;
  48673. };
  48674. var parseParameter = function (name, value, target, propertyPath) {
  48675. if (propertyPath === null) {
  48676. // String, boolean or float
  48677. var floatValue = parseFloat(value);
  48678. if (value === "true" || value === "false")
  48679. return value === "true";
  48680. else
  48681. return isNaN(floatValue) ? value : floatValue;
  48682. }
  48683. var effectiveTarget = propertyPath.split(".");
  48684. var values = value.split(",");
  48685. // Get effective Target
  48686. for (var i = 0; i < effectiveTarget.length; i++) {
  48687. target = target[effectiveTarget[i]];
  48688. }
  48689. // Return appropriate value with its type
  48690. if (typeof (target) === "boolean")
  48691. return values[0] === "true";
  48692. if (typeof (target) === "string")
  48693. return values[0];
  48694. // Parameters with multiple values such as Vector3 etc.
  48695. var split = new Array();
  48696. for (var i = 0; i < values.length; i++)
  48697. split.push(parseFloat(values[i]));
  48698. if (target instanceof BABYLON.Vector3)
  48699. return BABYLON.Vector3.FromArray(split);
  48700. if (target instanceof BABYLON.Vector4)
  48701. return BABYLON.Vector4.FromArray(split);
  48702. if (target instanceof BABYLON.Color3)
  48703. return BABYLON.Color3.FromArray(split);
  48704. if (target instanceof BABYLON.Color4)
  48705. return BABYLON.Color4.FromArray(split);
  48706. return parseFloat(values[0]);
  48707. };
  48708. // traverse graph per trigger
  48709. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48710. if (combineArray === void 0) { combineArray = null; }
  48711. if (parsedAction.detached)
  48712. return;
  48713. var parameters = new Array();
  48714. var target = null;
  48715. var propertyPath = null;
  48716. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48717. // Parameters
  48718. if (parsedAction.type === 2)
  48719. parameters.push(actionManager);
  48720. else
  48721. parameters.push(trigger);
  48722. if (combine) {
  48723. var actions = new Array();
  48724. for (var j = 0; j < parsedAction.combine.length; j++) {
  48725. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48726. }
  48727. parameters.push(actions);
  48728. }
  48729. else {
  48730. for (var i = 0; i < parsedAction.properties.length; i++) {
  48731. var value = parsedAction.properties[i].value;
  48732. var name = parsedAction.properties[i].name;
  48733. var targetType = parsedAction.properties[i].targetType;
  48734. if (name === "target")
  48735. if (targetType !== null && targetType === "SceneProperties")
  48736. value = target = scene;
  48737. else
  48738. value = target = scene.getNodeByName(value);
  48739. else if (name === "parent")
  48740. value = scene.getNodeByName(value);
  48741. else if (name === "sound")
  48742. value = scene.getSoundByName(value);
  48743. else if (name !== "propertyPath") {
  48744. if (parsedAction.type === 2 && name === "operator")
  48745. value = BABYLON.ValueCondition[value];
  48746. else
  48747. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48748. }
  48749. else {
  48750. propertyPath = value;
  48751. }
  48752. parameters.push(value);
  48753. }
  48754. }
  48755. if (combineArray === null) {
  48756. parameters.push(condition);
  48757. }
  48758. else {
  48759. parameters.push(null);
  48760. }
  48761. // If interpolate value action
  48762. if (parsedAction.name === "InterpolateValueAction") {
  48763. var param = parameters[parameters.length - 2];
  48764. parameters[parameters.length - 1] = param;
  48765. parameters[parameters.length - 2] = condition;
  48766. }
  48767. // Action or condition(s) and not CombineAction
  48768. var newAction = instanciate(parsedAction.name, parameters);
  48769. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48770. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48771. if (action)
  48772. action.then(nothing);
  48773. else
  48774. actionManager.registerAction(nothing);
  48775. action = nothing;
  48776. }
  48777. if (combineArray === null) {
  48778. if (newAction instanceof BABYLON.Condition) {
  48779. condition = newAction;
  48780. newAction = action;
  48781. }
  48782. else {
  48783. condition = null;
  48784. if (action)
  48785. action.then(newAction);
  48786. else
  48787. actionManager.registerAction(newAction);
  48788. }
  48789. }
  48790. else {
  48791. combineArray.push(newAction);
  48792. }
  48793. for (var i = 0; i < parsedAction.children.length; i++)
  48794. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48795. };
  48796. // triggers
  48797. for (var i = 0; i < parsedActions.children.length; i++) {
  48798. var triggerParams;
  48799. var trigger = parsedActions.children[i];
  48800. if (trigger.properties.length > 0) {
  48801. var param = trigger.properties[0].value;
  48802. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48803. if (value._meshId) {
  48804. value.mesh = scene.getMeshByID(value._meshId);
  48805. }
  48806. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48807. }
  48808. else
  48809. triggerParams = ActionManager[trigger.name];
  48810. for (var j = 0; j < trigger.children.length; j++) {
  48811. if (!trigger.detached)
  48812. traverse(trigger.children[j], triggerParams, null, null);
  48813. }
  48814. }
  48815. };
  48816. ActionManager.GetTriggerName = function (trigger) {
  48817. switch (trigger) {
  48818. case 0: return "NothingTrigger";
  48819. case 1: return "OnPickTrigger";
  48820. case 2: return "OnLeftPickTrigger";
  48821. case 3: return "OnRightPickTrigger";
  48822. case 4: return "OnCenterPickTrigger";
  48823. case 5: return "OnPickDownTrigger";
  48824. case 6: return "OnPickUpTrigger";
  48825. case 7: return "OnLongPressTrigger";
  48826. case 8: return "OnPointerOverTrigger";
  48827. case 9: return "OnPointerOutTrigger";
  48828. case 10: return "OnEveryFrameTrigger";
  48829. case 11: return "OnIntersectionEnterTrigger";
  48830. case 12: return "OnIntersectionExitTrigger";
  48831. case 13: return "OnKeyDownTrigger";
  48832. case 14: return "OnKeyUpTrigger";
  48833. case 15: return "OnPickOutTrigger";
  48834. default: return "";
  48835. }
  48836. };
  48837. // Statics
  48838. ActionManager._NothingTrigger = 0;
  48839. ActionManager._OnPickTrigger = 1;
  48840. ActionManager._OnLeftPickTrigger = 2;
  48841. ActionManager._OnRightPickTrigger = 3;
  48842. ActionManager._OnCenterPickTrigger = 4;
  48843. ActionManager._OnPickDownTrigger = 5;
  48844. ActionManager._OnDoublePickTrigger = 6;
  48845. ActionManager._OnPickUpTrigger = 7;
  48846. ActionManager._OnLongPressTrigger = 8;
  48847. ActionManager._OnPointerOverTrigger = 9;
  48848. ActionManager._OnPointerOutTrigger = 10;
  48849. ActionManager._OnEveryFrameTrigger = 11;
  48850. ActionManager._OnIntersectionEnterTrigger = 12;
  48851. ActionManager._OnIntersectionExitTrigger = 13;
  48852. ActionManager._OnKeyDownTrigger = 14;
  48853. ActionManager._OnKeyUpTrigger = 15;
  48854. ActionManager._OnPickOutTrigger = 16;
  48855. ActionManager.Triggers = {};
  48856. return ActionManager;
  48857. }());
  48858. BABYLON.ActionManager = ActionManager;
  48859. })(BABYLON || (BABYLON = {}));
  48860. //# sourceMappingURL=babylon.actionManager.js.map
  48861. var BABYLON;
  48862. (function (BABYLON) {
  48863. var InterpolateValueAction = /** @class */ (function (_super) {
  48864. __extends(InterpolateValueAction, _super);
  48865. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48866. if (duration === void 0) { duration = 1000; }
  48867. var _this = _super.call(this, triggerOptions, condition) || this;
  48868. _this.propertyPath = propertyPath;
  48869. _this.value = value;
  48870. _this.duration = duration;
  48871. _this.stopOtherAnimations = stopOtherAnimations;
  48872. _this.onInterpolationDone = onInterpolationDone;
  48873. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48874. _this._target = _this._effectiveTarget = target;
  48875. return _this;
  48876. }
  48877. InterpolateValueAction.prototype._prepare = function () {
  48878. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48879. this._property = this._getProperty(this.propertyPath);
  48880. };
  48881. InterpolateValueAction.prototype.execute = function () {
  48882. var _this = this;
  48883. var scene = this._actionManager.getScene();
  48884. var keys = [
  48885. {
  48886. frame: 0,
  48887. value: this._effectiveTarget[this._property]
  48888. }, {
  48889. frame: 100,
  48890. value: this.value
  48891. }
  48892. ];
  48893. var dataType;
  48894. if (typeof this.value === "number") {
  48895. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48896. }
  48897. else if (this.value instanceof BABYLON.Color3) {
  48898. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48899. }
  48900. else if (this.value instanceof BABYLON.Vector3) {
  48901. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48902. }
  48903. else if (this.value instanceof BABYLON.Matrix) {
  48904. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48905. }
  48906. else if (this.value instanceof BABYLON.Quaternion) {
  48907. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48908. }
  48909. else {
  48910. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48911. return;
  48912. }
  48913. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48914. animation.setKeys(keys);
  48915. if (this.stopOtherAnimations) {
  48916. scene.stopAnimation(this._effectiveTarget);
  48917. }
  48918. var wrapper = function () {
  48919. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48920. if (_this.onInterpolationDone) {
  48921. _this.onInterpolationDone();
  48922. }
  48923. };
  48924. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48925. };
  48926. InterpolateValueAction.prototype.serialize = function (parent) {
  48927. return _super.prototype._serialize.call(this, {
  48928. name: "InterpolateValueAction",
  48929. properties: [
  48930. BABYLON.Action._GetTargetProperty(this._target),
  48931. { name: "propertyPath", value: this.propertyPath },
  48932. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48933. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48934. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48935. ]
  48936. }, parent);
  48937. };
  48938. return InterpolateValueAction;
  48939. }(BABYLON.Action));
  48940. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48941. })(BABYLON || (BABYLON = {}));
  48942. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48943. var BABYLON;
  48944. (function (BABYLON) {
  48945. var SwitchBooleanAction = /** @class */ (function (_super) {
  48946. __extends(SwitchBooleanAction, _super);
  48947. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48948. var _this = _super.call(this, triggerOptions, condition) || this;
  48949. _this.propertyPath = propertyPath;
  48950. _this._target = _this._effectiveTarget = target;
  48951. return _this;
  48952. }
  48953. SwitchBooleanAction.prototype._prepare = function () {
  48954. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48955. this._property = this._getProperty(this.propertyPath);
  48956. };
  48957. SwitchBooleanAction.prototype.execute = function () {
  48958. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48959. };
  48960. SwitchBooleanAction.prototype.serialize = function (parent) {
  48961. return _super.prototype._serialize.call(this, {
  48962. name: "SwitchBooleanAction",
  48963. properties: [
  48964. BABYLON.Action._GetTargetProperty(this._target),
  48965. { name: "propertyPath", value: this.propertyPath }
  48966. ]
  48967. }, parent);
  48968. };
  48969. return SwitchBooleanAction;
  48970. }(BABYLON.Action));
  48971. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48972. var SetStateAction = /** @class */ (function (_super) {
  48973. __extends(SetStateAction, _super);
  48974. function SetStateAction(triggerOptions, target, value, condition) {
  48975. var _this = _super.call(this, triggerOptions, condition) || this;
  48976. _this.value = value;
  48977. _this._target = target;
  48978. return _this;
  48979. }
  48980. SetStateAction.prototype.execute = function () {
  48981. this._target.state = this.value;
  48982. };
  48983. SetStateAction.prototype.serialize = function (parent) {
  48984. return _super.prototype._serialize.call(this, {
  48985. name: "SetStateAction",
  48986. properties: [
  48987. BABYLON.Action._GetTargetProperty(this._target),
  48988. { name: "value", value: this.value }
  48989. ]
  48990. }, parent);
  48991. };
  48992. return SetStateAction;
  48993. }(BABYLON.Action));
  48994. BABYLON.SetStateAction = SetStateAction;
  48995. var SetValueAction = /** @class */ (function (_super) {
  48996. __extends(SetValueAction, _super);
  48997. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48998. var _this = _super.call(this, triggerOptions, condition) || this;
  48999. _this.propertyPath = propertyPath;
  49000. _this.value = value;
  49001. _this._target = _this._effectiveTarget = target;
  49002. return _this;
  49003. }
  49004. SetValueAction.prototype._prepare = function () {
  49005. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49006. this._property = this._getProperty(this.propertyPath);
  49007. };
  49008. SetValueAction.prototype.execute = function () {
  49009. this._effectiveTarget[this._property] = this.value;
  49010. if (this._target.markAsDirty) {
  49011. this._target.markAsDirty(this._property);
  49012. }
  49013. };
  49014. SetValueAction.prototype.serialize = function (parent) {
  49015. return _super.prototype._serialize.call(this, {
  49016. name: "SetValueAction",
  49017. properties: [
  49018. BABYLON.Action._GetTargetProperty(this._target),
  49019. { name: "propertyPath", value: this.propertyPath },
  49020. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49021. ]
  49022. }, parent);
  49023. };
  49024. return SetValueAction;
  49025. }(BABYLON.Action));
  49026. BABYLON.SetValueAction = SetValueAction;
  49027. var IncrementValueAction = /** @class */ (function (_super) {
  49028. __extends(IncrementValueAction, _super);
  49029. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49030. var _this = _super.call(this, triggerOptions, condition) || this;
  49031. _this.propertyPath = propertyPath;
  49032. _this.value = value;
  49033. _this._target = _this._effectiveTarget = target;
  49034. return _this;
  49035. }
  49036. IncrementValueAction.prototype._prepare = function () {
  49037. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49038. this._property = this._getProperty(this.propertyPath);
  49039. if (typeof this._effectiveTarget[this._property] !== "number") {
  49040. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49041. }
  49042. };
  49043. IncrementValueAction.prototype.execute = function () {
  49044. this._effectiveTarget[this._property] += this.value;
  49045. if (this._target.markAsDirty) {
  49046. this._target.markAsDirty(this._property);
  49047. }
  49048. };
  49049. IncrementValueAction.prototype.serialize = function (parent) {
  49050. return _super.prototype._serialize.call(this, {
  49051. name: "IncrementValueAction",
  49052. properties: [
  49053. BABYLON.Action._GetTargetProperty(this._target),
  49054. { name: "propertyPath", value: this.propertyPath },
  49055. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49056. ]
  49057. }, parent);
  49058. };
  49059. return IncrementValueAction;
  49060. }(BABYLON.Action));
  49061. BABYLON.IncrementValueAction = IncrementValueAction;
  49062. var PlayAnimationAction = /** @class */ (function (_super) {
  49063. __extends(PlayAnimationAction, _super);
  49064. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49065. var _this = _super.call(this, triggerOptions, condition) || this;
  49066. _this.from = from;
  49067. _this.to = to;
  49068. _this.loop = loop;
  49069. _this._target = target;
  49070. return _this;
  49071. }
  49072. PlayAnimationAction.prototype._prepare = function () {
  49073. };
  49074. PlayAnimationAction.prototype.execute = function () {
  49075. var scene = this._actionManager.getScene();
  49076. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49077. };
  49078. PlayAnimationAction.prototype.serialize = function (parent) {
  49079. return _super.prototype._serialize.call(this, {
  49080. name: "PlayAnimationAction",
  49081. properties: [
  49082. BABYLON.Action._GetTargetProperty(this._target),
  49083. { name: "from", value: String(this.from) },
  49084. { name: "to", value: String(this.to) },
  49085. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49086. ]
  49087. }, parent);
  49088. };
  49089. return PlayAnimationAction;
  49090. }(BABYLON.Action));
  49091. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49092. var StopAnimationAction = /** @class */ (function (_super) {
  49093. __extends(StopAnimationAction, _super);
  49094. function StopAnimationAction(triggerOptions, target, condition) {
  49095. var _this = _super.call(this, triggerOptions, condition) || this;
  49096. _this._target = target;
  49097. return _this;
  49098. }
  49099. StopAnimationAction.prototype._prepare = function () {
  49100. };
  49101. StopAnimationAction.prototype.execute = function () {
  49102. var scene = this._actionManager.getScene();
  49103. scene.stopAnimation(this._target);
  49104. };
  49105. StopAnimationAction.prototype.serialize = function (parent) {
  49106. return _super.prototype._serialize.call(this, {
  49107. name: "StopAnimationAction",
  49108. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49109. }, parent);
  49110. };
  49111. return StopAnimationAction;
  49112. }(BABYLON.Action));
  49113. BABYLON.StopAnimationAction = StopAnimationAction;
  49114. var DoNothingAction = /** @class */ (function (_super) {
  49115. __extends(DoNothingAction, _super);
  49116. function DoNothingAction(triggerOptions, condition) {
  49117. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49118. return _super.call(this, triggerOptions, condition) || this;
  49119. }
  49120. DoNothingAction.prototype.execute = function () {
  49121. };
  49122. DoNothingAction.prototype.serialize = function (parent) {
  49123. return _super.prototype._serialize.call(this, {
  49124. name: "DoNothingAction",
  49125. properties: []
  49126. }, parent);
  49127. };
  49128. return DoNothingAction;
  49129. }(BABYLON.Action));
  49130. BABYLON.DoNothingAction = DoNothingAction;
  49131. var CombineAction = /** @class */ (function (_super) {
  49132. __extends(CombineAction, _super);
  49133. function CombineAction(triggerOptions, children, condition) {
  49134. var _this = _super.call(this, triggerOptions, condition) || this;
  49135. _this.children = children;
  49136. return _this;
  49137. }
  49138. CombineAction.prototype._prepare = function () {
  49139. for (var index = 0; index < this.children.length; index++) {
  49140. this.children[index]._actionManager = this._actionManager;
  49141. this.children[index]._prepare();
  49142. }
  49143. };
  49144. CombineAction.prototype.execute = function (evt) {
  49145. for (var index = 0; index < this.children.length; index++) {
  49146. this.children[index].execute(evt);
  49147. }
  49148. };
  49149. CombineAction.prototype.serialize = function (parent) {
  49150. var serializationObject = _super.prototype._serialize.call(this, {
  49151. name: "CombineAction",
  49152. properties: [],
  49153. combine: []
  49154. }, parent);
  49155. for (var i = 0; i < this.children.length; i++) {
  49156. serializationObject.combine.push(this.children[i].serialize(null));
  49157. }
  49158. return serializationObject;
  49159. };
  49160. return CombineAction;
  49161. }(BABYLON.Action));
  49162. BABYLON.CombineAction = CombineAction;
  49163. var ExecuteCodeAction = /** @class */ (function (_super) {
  49164. __extends(ExecuteCodeAction, _super);
  49165. function ExecuteCodeAction(triggerOptions, func, condition) {
  49166. var _this = _super.call(this, triggerOptions, condition) || this;
  49167. _this.func = func;
  49168. return _this;
  49169. }
  49170. ExecuteCodeAction.prototype.execute = function (evt) {
  49171. this.func(evt);
  49172. };
  49173. return ExecuteCodeAction;
  49174. }(BABYLON.Action));
  49175. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49176. var SetParentAction = /** @class */ (function (_super) {
  49177. __extends(SetParentAction, _super);
  49178. function SetParentAction(triggerOptions, target, parent, condition) {
  49179. var _this = _super.call(this, triggerOptions, condition) || this;
  49180. _this._target = target;
  49181. _this._parent = parent;
  49182. return _this;
  49183. }
  49184. SetParentAction.prototype._prepare = function () {
  49185. };
  49186. SetParentAction.prototype.execute = function () {
  49187. if (this._target.parent === this._parent) {
  49188. return;
  49189. }
  49190. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49191. invertParentWorldMatrix.invert();
  49192. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49193. this._target.parent = this._parent;
  49194. };
  49195. SetParentAction.prototype.serialize = function (parent) {
  49196. return _super.prototype._serialize.call(this, {
  49197. name: "SetParentAction",
  49198. properties: [
  49199. BABYLON.Action._GetTargetProperty(this._target),
  49200. BABYLON.Action._GetTargetProperty(this._parent),
  49201. ]
  49202. }, parent);
  49203. };
  49204. return SetParentAction;
  49205. }(BABYLON.Action));
  49206. BABYLON.SetParentAction = SetParentAction;
  49207. var PlaySoundAction = /** @class */ (function (_super) {
  49208. __extends(PlaySoundAction, _super);
  49209. function PlaySoundAction(triggerOptions, sound, condition) {
  49210. var _this = _super.call(this, triggerOptions, condition) || this;
  49211. _this._sound = sound;
  49212. return _this;
  49213. }
  49214. PlaySoundAction.prototype._prepare = function () {
  49215. };
  49216. PlaySoundAction.prototype.execute = function () {
  49217. if (this._sound !== undefined)
  49218. this._sound.play();
  49219. };
  49220. PlaySoundAction.prototype.serialize = function (parent) {
  49221. return _super.prototype._serialize.call(this, {
  49222. name: "PlaySoundAction",
  49223. properties: [{ name: "sound", value: this._sound.name }]
  49224. }, parent);
  49225. };
  49226. return PlaySoundAction;
  49227. }(BABYLON.Action));
  49228. BABYLON.PlaySoundAction = PlaySoundAction;
  49229. var StopSoundAction = /** @class */ (function (_super) {
  49230. __extends(StopSoundAction, _super);
  49231. function StopSoundAction(triggerOptions, sound, condition) {
  49232. var _this = _super.call(this, triggerOptions, condition) || this;
  49233. _this._sound = sound;
  49234. return _this;
  49235. }
  49236. StopSoundAction.prototype._prepare = function () {
  49237. };
  49238. StopSoundAction.prototype.execute = function () {
  49239. if (this._sound !== undefined)
  49240. this._sound.stop();
  49241. };
  49242. StopSoundAction.prototype.serialize = function (parent) {
  49243. return _super.prototype._serialize.call(this, {
  49244. name: "StopSoundAction",
  49245. properties: [{ name: "sound", value: this._sound.name }]
  49246. }, parent);
  49247. };
  49248. return StopSoundAction;
  49249. }(BABYLON.Action));
  49250. BABYLON.StopSoundAction = StopSoundAction;
  49251. })(BABYLON || (BABYLON = {}));
  49252. //# sourceMappingURL=babylon.directActions.js.map
  49253. var BABYLON;
  49254. (function (BABYLON) {
  49255. var SpriteManager = /** @class */ (function () {
  49256. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49257. if (epsilon === void 0) { epsilon = 0.01; }
  49258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49259. this.name = name;
  49260. this.sprites = new Array();
  49261. this.renderingGroupId = 0;
  49262. this.layerMask = 0x0FFFFFFF;
  49263. this.fogEnabled = true;
  49264. this.isPickable = false;
  49265. /**
  49266. * An event triggered when the manager is disposed.
  49267. * @type {BABYLON.Observable}
  49268. */
  49269. this.onDisposeObservable = new BABYLON.Observable();
  49270. this._vertexBuffers = {};
  49271. this._capacity = capacity;
  49272. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49273. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49274. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49275. if (cellSize.width && cellSize.height) {
  49276. this.cellWidth = cellSize.width;
  49277. this.cellHeight = cellSize.height;
  49278. }
  49279. else if (cellSize !== undefined) {
  49280. this.cellWidth = cellSize;
  49281. this.cellHeight = cellSize;
  49282. }
  49283. else {
  49284. return;
  49285. }
  49286. this._epsilon = epsilon;
  49287. this._scene = scene;
  49288. this._scene.spriteManagers.push(this);
  49289. var indices = [];
  49290. var index = 0;
  49291. for (var count = 0; count < capacity; count++) {
  49292. indices.push(index);
  49293. indices.push(index + 1);
  49294. indices.push(index + 2);
  49295. indices.push(index);
  49296. indices.push(index + 2);
  49297. indices.push(index + 3);
  49298. index += 4;
  49299. }
  49300. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49301. // VBO
  49302. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49303. this._vertexData = new Float32Array(capacity * 16 * 4);
  49304. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49305. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49306. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49307. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49308. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49309. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49310. this._vertexBuffers["options"] = options;
  49311. this._vertexBuffers["cellInfo"] = cellInfo;
  49312. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49313. // Effects
  49314. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49315. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49316. }
  49317. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49318. set: function (callback) {
  49319. if (this._onDisposeObserver) {
  49320. this.onDisposeObservable.remove(this._onDisposeObserver);
  49321. }
  49322. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(SpriteManager.prototype, "texture", {
  49328. get: function () {
  49329. return this._spriteTexture;
  49330. },
  49331. set: function (value) {
  49332. this._spriteTexture = value;
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49338. var arrayOffset = index * 16;
  49339. if (offsetX === 0)
  49340. offsetX = this._epsilon;
  49341. else if (offsetX === 1)
  49342. offsetX = 1 - this._epsilon;
  49343. if (offsetY === 0)
  49344. offsetY = this._epsilon;
  49345. else if (offsetY === 1)
  49346. offsetY = 1 - this._epsilon;
  49347. this._vertexData[arrayOffset] = sprite.position.x;
  49348. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49349. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49350. this._vertexData[arrayOffset + 3] = sprite.angle;
  49351. this._vertexData[arrayOffset + 4] = sprite.width;
  49352. this._vertexData[arrayOffset + 5] = sprite.height;
  49353. this._vertexData[arrayOffset + 6] = offsetX;
  49354. this._vertexData[arrayOffset + 7] = offsetY;
  49355. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49356. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49357. var offset = (sprite.cellIndex / rowSize) >> 0;
  49358. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49359. this._vertexData[arrayOffset + 11] = offset;
  49360. // Color
  49361. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49362. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49363. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49364. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49365. };
  49366. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49367. var count = Math.min(this._capacity, this.sprites.length);
  49368. var min = BABYLON.Vector3.Zero();
  49369. var max = BABYLON.Vector3.Zero();
  49370. var distance = Number.MAX_VALUE;
  49371. var currentSprite = null;
  49372. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49373. var cameraView = camera.getViewMatrix();
  49374. for (var index = 0; index < count; index++) {
  49375. var sprite = this.sprites[index];
  49376. if (!sprite) {
  49377. continue;
  49378. }
  49379. if (predicate) {
  49380. if (!predicate(sprite)) {
  49381. continue;
  49382. }
  49383. }
  49384. else if (!sprite.isPickable) {
  49385. continue;
  49386. }
  49387. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49388. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49389. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49390. if (ray.intersectsBoxMinMax(min, max)) {
  49391. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49392. if (distance > currentDistance) {
  49393. distance = currentDistance;
  49394. currentSprite = sprite;
  49395. if (fastCheck) {
  49396. break;
  49397. }
  49398. }
  49399. }
  49400. }
  49401. if (currentSprite) {
  49402. var result = new BABYLON.PickingInfo();
  49403. result.hit = true;
  49404. result.pickedSprite = currentSprite;
  49405. result.distance = distance;
  49406. return result;
  49407. }
  49408. return null;
  49409. };
  49410. SpriteManager.prototype.render = function () {
  49411. // Check
  49412. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49413. return;
  49414. var engine = this._scene.getEngine();
  49415. var baseSize = this._spriteTexture.getBaseSize();
  49416. // Sprites
  49417. var deltaTime = engine.getDeltaTime();
  49418. var max = Math.min(this._capacity, this.sprites.length);
  49419. var rowSize = baseSize.width / this.cellWidth;
  49420. var offset = 0;
  49421. for (var index = 0; index < max; index++) {
  49422. var sprite = this.sprites[index];
  49423. if (!sprite) {
  49424. continue;
  49425. }
  49426. sprite._animate(deltaTime);
  49427. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49428. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49429. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49430. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49431. }
  49432. this._buffer.update(this._vertexData);
  49433. // Render
  49434. var effect = this._effectBase;
  49435. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49436. effect = this._effectFog;
  49437. }
  49438. engine.enableEffect(effect);
  49439. var viewMatrix = this._scene.getViewMatrix();
  49440. effect.setTexture("diffuseSampler", this._spriteTexture);
  49441. effect.setMatrix("view", viewMatrix);
  49442. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49443. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49444. // Fog
  49445. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49446. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49447. effect.setColor3("vFogColor", this._scene.fogColor);
  49448. }
  49449. // VBOs
  49450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49451. // Draw order
  49452. engine.setDepthFunctionToLessOrEqual();
  49453. effect.setBool("alphaTest", true);
  49454. engine.setColorWrite(false);
  49455. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49456. engine.setColorWrite(true);
  49457. effect.setBool("alphaTest", false);
  49458. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49460. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49461. };
  49462. SpriteManager.prototype.dispose = function () {
  49463. if (this._buffer) {
  49464. this._buffer.dispose();
  49465. this._buffer = null;
  49466. }
  49467. if (this._indexBuffer) {
  49468. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49469. this._indexBuffer = null;
  49470. }
  49471. if (this._spriteTexture) {
  49472. this._spriteTexture.dispose();
  49473. this._spriteTexture = null;
  49474. }
  49475. // Remove from scene
  49476. var index = this._scene.spriteManagers.indexOf(this);
  49477. this._scene.spriteManagers.splice(index, 1);
  49478. // Callback
  49479. this.onDisposeObservable.notifyObservers(this);
  49480. this.onDisposeObservable.clear();
  49481. };
  49482. return SpriteManager;
  49483. }());
  49484. BABYLON.SpriteManager = SpriteManager;
  49485. })(BABYLON || (BABYLON = {}));
  49486. //# sourceMappingURL=babylon.spriteManager.js.map
  49487. var BABYLON;
  49488. (function (BABYLON) {
  49489. var Sprite = /** @class */ (function () {
  49490. function Sprite(name, manager) {
  49491. this.name = name;
  49492. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49493. this.width = 1.0;
  49494. this.height = 1.0;
  49495. this.angle = 0;
  49496. this.cellIndex = 0;
  49497. this.invertU = 0;
  49498. this.invertV = 0;
  49499. this.animations = new Array();
  49500. this.isPickable = false;
  49501. this._animationStarted = false;
  49502. this._loopAnimation = false;
  49503. this._fromIndex = 0;
  49504. this._toIndex = 0;
  49505. this._delay = 0;
  49506. this._direction = 1;
  49507. this._time = 0;
  49508. this._manager = manager;
  49509. this._manager.sprites.push(this);
  49510. this.position = BABYLON.Vector3.Zero();
  49511. }
  49512. Object.defineProperty(Sprite.prototype, "size", {
  49513. get: function () {
  49514. return this.width;
  49515. },
  49516. set: function (value) {
  49517. this.width = value;
  49518. this.height = value;
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49524. this._fromIndex = from;
  49525. this._toIndex = to;
  49526. this._loopAnimation = loop;
  49527. this._delay = delay;
  49528. this._animationStarted = true;
  49529. this._direction = from < to ? 1 : -1;
  49530. this.cellIndex = from;
  49531. this._time = 0;
  49532. this._onAnimationEnd = onAnimationEnd;
  49533. };
  49534. Sprite.prototype.stopAnimation = function () {
  49535. this._animationStarted = false;
  49536. };
  49537. Sprite.prototype._animate = function (deltaTime) {
  49538. if (!this._animationStarted)
  49539. return;
  49540. this._time += deltaTime;
  49541. if (this._time > this._delay) {
  49542. this._time = this._time % this._delay;
  49543. this.cellIndex += this._direction;
  49544. if (this.cellIndex > this._toIndex) {
  49545. if (this._loopAnimation) {
  49546. this.cellIndex = this._fromIndex;
  49547. }
  49548. else {
  49549. this.cellIndex = this._toIndex;
  49550. this._animationStarted = false;
  49551. if (this._onAnimationEnd) {
  49552. this._onAnimationEnd();
  49553. }
  49554. if (this.disposeWhenFinishedAnimating) {
  49555. this.dispose();
  49556. }
  49557. }
  49558. }
  49559. }
  49560. };
  49561. Sprite.prototype.dispose = function () {
  49562. for (var i = 0; i < this._manager.sprites.length; i++) {
  49563. if (this._manager.sprites[i] == this) {
  49564. this._manager.sprites.splice(i, 1);
  49565. }
  49566. }
  49567. };
  49568. return Sprite;
  49569. }());
  49570. BABYLON.Sprite = Sprite;
  49571. })(BABYLON || (BABYLON = {}));
  49572. //# sourceMappingURL=babylon.sprite.js.map
  49573. var BABYLON;
  49574. (function (BABYLON) {
  49575. var IntersectionInfo = /** @class */ (function () {
  49576. function IntersectionInfo(bu, bv, distance) {
  49577. this.bu = bu;
  49578. this.bv = bv;
  49579. this.distance = distance;
  49580. this.faceId = 0;
  49581. this.subMeshId = 0;
  49582. }
  49583. return IntersectionInfo;
  49584. }());
  49585. BABYLON.IntersectionInfo = IntersectionInfo;
  49586. var PickingInfo = /** @class */ (function () {
  49587. function PickingInfo() {
  49588. this.hit = false;
  49589. this.distance = 0;
  49590. this.pickedPoint = null;
  49591. this.pickedMesh = null;
  49592. this.bu = 0;
  49593. this.bv = 0;
  49594. this.faceId = -1;
  49595. this.subMeshId = 0;
  49596. this.pickedSprite = null;
  49597. }
  49598. // Methods
  49599. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49600. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49601. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49602. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49603. return null;
  49604. }
  49605. var indices = this.pickedMesh.getIndices();
  49606. if (!indices) {
  49607. return null;
  49608. }
  49609. var result;
  49610. if (useVerticesNormals) {
  49611. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49612. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49613. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49614. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49615. normal0 = normal0.scale(this.bu);
  49616. normal1 = normal1.scale(this.bv);
  49617. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49618. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49619. }
  49620. else {
  49621. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49622. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49623. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49624. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49625. var p1p2 = vertex1.subtract(vertex2);
  49626. var p3p2 = vertex3.subtract(vertex2);
  49627. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49628. }
  49629. if (useWorldCoordinates) {
  49630. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49631. }
  49632. return BABYLON.Vector3.Normalize(result);
  49633. };
  49634. PickingInfo.prototype.getTextureCoordinates = function () {
  49635. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49636. return null;
  49637. }
  49638. var indices = this.pickedMesh.getIndices();
  49639. if (!indices) {
  49640. return null;
  49641. }
  49642. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49643. if (!uvs) {
  49644. return null;
  49645. }
  49646. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49647. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49648. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49649. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49650. uv1 = uv1.scale(this.bu);
  49651. uv2 = uv2.scale(this.bv);
  49652. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49653. };
  49654. return PickingInfo;
  49655. }());
  49656. BABYLON.PickingInfo = PickingInfo;
  49657. })(BABYLON || (BABYLON = {}));
  49658. //# sourceMappingURL=babylon.pickingInfo.js.map
  49659. var BABYLON;
  49660. (function (BABYLON) {
  49661. var Ray = /** @class */ (function () {
  49662. function Ray(origin, direction, length) {
  49663. if (length === void 0) { length = Number.MAX_VALUE; }
  49664. this.origin = origin;
  49665. this.direction = direction;
  49666. this.length = length;
  49667. }
  49668. // Methods
  49669. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49670. var d = 0.0;
  49671. var maxValue = Number.MAX_VALUE;
  49672. var inv;
  49673. var min;
  49674. var max;
  49675. var temp;
  49676. if (Math.abs(this.direction.x) < 0.0000001) {
  49677. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49678. return false;
  49679. }
  49680. }
  49681. else {
  49682. inv = 1.0 / this.direction.x;
  49683. min = (minimum.x - this.origin.x) * inv;
  49684. max = (maximum.x - this.origin.x) * inv;
  49685. if (max === -Infinity) {
  49686. max = Infinity;
  49687. }
  49688. if (min > max) {
  49689. temp = min;
  49690. min = max;
  49691. max = temp;
  49692. }
  49693. d = Math.max(min, d);
  49694. maxValue = Math.min(max, maxValue);
  49695. if (d > maxValue) {
  49696. return false;
  49697. }
  49698. }
  49699. if (Math.abs(this.direction.y) < 0.0000001) {
  49700. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49701. return false;
  49702. }
  49703. }
  49704. else {
  49705. inv = 1.0 / this.direction.y;
  49706. min = (minimum.y - this.origin.y) * inv;
  49707. max = (maximum.y - this.origin.y) * inv;
  49708. if (max === -Infinity) {
  49709. max = Infinity;
  49710. }
  49711. if (min > max) {
  49712. temp = min;
  49713. min = max;
  49714. max = temp;
  49715. }
  49716. d = Math.max(min, d);
  49717. maxValue = Math.min(max, maxValue);
  49718. if (d > maxValue) {
  49719. return false;
  49720. }
  49721. }
  49722. if (Math.abs(this.direction.z) < 0.0000001) {
  49723. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49724. return false;
  49725. }
  49726. }
  49727. else {
  49728. inv = 1.0 / this.direction.z;
  49729. min = (minimum.z - this.origin.z) * inv;
  49730. max = (maximum.z - this.origin.z) * inv;
  49731. if (max === -Infinity) {
  49732. max = Infinity;
  49733. }
  49734. if (min > max) {
  49735. temp = min;
  49736. min = max;
  49737. max = temp;
  49738. }
  49739. d = Math.max(min, d);
  49740. maxValue = Math.min(max, maxValue);
  49741. if (d > maxValue) {
  49742. return false;
  49743. }
  49744. }
  49745. return true;
  49746. };
  49747. Ray.prototype.intersectsBox = function (box) {
  49748. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49749. };
  49750. Ray.prototype.intersectsSphere = function (sphere) {
  49751. var x = sphere.center.x - this.origin.x;
  49752. var y = sphere.center.y - this.origin.y;
  49753. var z = sphere.center.z - this.origin.z;
  49754. var pyth = (x * x) + (y * y) + (z * z);
  49755. var rr = sphere.radius * sphere.radius;
  49756. if (pyth <= rr) {
  49757. return true;
  49758. }
  49759. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49760. if (dot < 0.0) {
  49761. return false;
  49762. }
  49763. var temp = pyth - (dot * dot);
  49764. return temp <= rr;
  49765. };
  49766. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49767. if (!this._edge1) {
  49768. this._edge1 = BABYLON.Vector3.Zero();
  49769. this._edge2 = BABYLON.Vector3.Zero();
  49770. this._pvec = BABYLON.Vector3.Zero();
  49771. this._tvec = BABYLON.Vector3.Zero();
  49772. this._qvec = BABYLON.Vector3.Zero();
  49773. }
  49774. vertex1.subtractToRef(vertex0, this._edge1);
  49775. vertex2.subtractToRef(vertex0, this._edge2);
  49776. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49777. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49778. if (det === 0) {
  49779. return null;
  49780. }
  49781. var invdet = 1 / det;
  49782. this.origin.subtractToRef(vertex0, this._tvec);
  49783. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49784. if (bu < 0 || bu > 1.0) {
  49785. return null;
  49786. }
  49787. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49788. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49789. if (bv < 0 || bu + bv > 1.0) {
  49790. return null;
  49791. }
  49792. //check if the distance is longer than the predefined length.
  49793. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49794. if (distance > this.length) {
  49795. return null;
  49796. }
  49797. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49798. };
  49799. Ray.prototype.intersectsPlane = function (plane) {
  49800. var distance;
  49801. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49802. if (Math.abs(result1) < 9.99999997475243E-07) {
  49803. return null;
  49804. }
  49805. else {
  49806. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49807. distance = (-plane.d - result2) / result1;
  49808. if (distance < 0.0) {
  49809. if (distance < -9.99999997475243E-07) {
  49810. return null;
  49811. }
  49812. else {
  49813. return 0;
  49814. }
  49815. }
  49816. return distance;
  49817. }
  49818. };
  49819. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49820. var tm = BABYLON.Tmp.Matrix[0];
  49821. mesh.getWorldMatrix().invertToRef(tm);
  49822. if (this._tmpRay) {
  49823. Ray.TransformToRef(this, tm, this._tmpRay);
  49824. }
  49825. else {
  49826. this._tmpRay = Ray.Transform(this, tm);
  49827. }
  49828. return mesh.intersects(this._tmpRay, fastCheck);
  49829. };
  49830. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49831. if (results) {
  49832. results.length = 0;
  49833. }
  49834. else {
  49835. results = [];
  49836. }
  49837. for (var i = 0; i < meshes.length; i++) {
  49838. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49839. if (pickInfo.hit) {
  49840. results.push(pickInfo);
  49841. }
  49842. }
  49843. results.sort(this._comparePickingInfo);
  49844. return results;
  49845. };
  49846. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49847. if (pickingInfoA.distance < pickingInfoB.distance) {
  49848. return -1;
  49849. }
  49850. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49851. return 1;
  49852. }
  49853. else {
  49854. return 0;
  49855. }
  49856. };
  49857. /**
  49858. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49859. * @param sega the first point of the segment to test the intersection against
  49860. * @param segb the second point of the segment to test the intersection against
  49861. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49862. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49863. */
  49864. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49865. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49866. var u = segb.subtract(sega);
  49867. var v = rsegb.subtract(this.origin);
  49868. var w = sega.subtract(this.origin);
  49869. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49870. var b = BABYLON.Vector3.Dot(u, v);
  49871. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49872. var d = BABYLON.Vector3.Dot(u, w);
  49873. var e = BABYLON.Vector3.Dot(v, w);
  49874. var D = a * c - b * b; // always >= 0
  49875. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49876. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49877. // compute the line parameters of the two closest points
  49878. if (D < Ray.smallnum) {
  49879. sN = 0.0; // force using point P0 on segment S1
  49880. sD = 1.0; // to prevent possible division by 0.0 later
  49881. tN = e;
  49882. tD = c;
  49883. }
  49884. else {
  49885. sN = (b * e - c * d);
  49886. tN = (a * e - b * d);
  49887. if (sN < 0.0) {
  49888. sN = 0.0;
  49889. tN = e;
  49890. tD = c;
  49891. }
  49892. else if (sN > sD) {
  49893. sN = sD;
  49894. tN = e + b;
  49895. tD = c;
  49896. }
  49897. }
  49898. if (tN < 0.0) {
  49899. tN = 0.0;
  49900. // recompute sc for this edge
  49901. if (-d < 0.0) {
  49902. sN = 0.0;
  49903. }
  49904. else if (-d > a)
  49905. sN = sD;
  49906. else {
  49907. sN = -d;
  49908. sD = a;
  49909. }
  49910. }
  49911. else if (tN > tD) {
  49912. tN = tD;
  49913. // recompute sc for this edge
  49914. if ((-d + b) < 0.0) {
  49915. sN = 0;
  49916. }
  49917. else if ((-d + b) > a) {
  49918. sN = sD;
  49919. }
  49920. else {
  49921. sN = (-d + b);
  49922. sD = a;
  49923. }
  49924. }
  49925. // finally do the division to get sc and tc
  49926. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49927. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49928. // get the difference of the two closest points
  49929. var qtc = v.multiplyByFloats(tc, tc, tc);
  49930. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49931. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49932. if (isIntersected) {
  49933. return qtc.length();
  49934. }
  49935. return -1;
  49936. };
  49937. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49938. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49939. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49940. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49941. this.direction.normalize();
  49942. return this;
  49943. };
  49944. // Statics
  49945. Ray.Zero = function () {
  49946. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49947. };
  49948. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49949. var result = Ray.Zero();
  49950. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49951. };
  49952. /**
  49953. * 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
  49954. * transformed to the given world matrix.
  49955. * @param origin The origin point
  49956. * @param end The end point
  49957. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49958. */
  49959. Ray.CreateNewFromTo = function (origin, end, world) {
  49960. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49961. var direction = end.subtract(origin);
  49962. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49963. direction.normalize();
  49964. return Ray.Transform(new Ray(origin, direction, length), world);
  49965. };
  49966. Ray.Transform = function (ray, matrix) {
  49967. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49968. Ray.TransformToRef(ray, matrix, result);
  49969. return result;
  49970. };
  49971. Ray.TransformToRef = function (ray, matrix, result) {
  49972. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49973. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49974. result.length = ray.length;
  49975. var dir = result.direction;
  49976. var len = dir.length();
  49977. if (!(len === 0 || len === 1)) {
  49978. var num = 1.0 / len;
  49979. dir.x *= num;
  49980. dir.y *= num;
  49981. dir.z *= num;
  49982. result.length *= len;
  49983. }
  49984. };
  49985. Ray.smallnum = 0.00000001;
  49986. Ray.rayl = 10e8;
  49987. return Ray;
  49988. }());
  49989. BABYLON.Ray = Ray;
  49990. })(BABYLON || (BABYLON = {}));
  49991. //# sourceMappingURL=babylon.ray.js.map
  49992. var BABYLON;
  49993. (function (BABYLON) {
  49994. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49995. if (boxMin.x > sphereCenter.x + sphereRadius)
  49996. return false;
  49997. if (sphereCenter.x - sphereRadius > boxMax.x)
  49998. return false;
  49999. if (boxMin.y > sphereCenter.y + sphereRadius)
  50000. return false;
  50001. if (sphereCenter.y - sphereRadius > boxMax.y)
  50002. return false;
  50003. if (boxMin.z > sphereCenter.z + sphereRadius)
  50004. return false;
  50005. if (sphereCenter.z - sphereRadius > boxMax.z)
  50006. return false;
  50007. return true;
  50008. };
  50009. var getLowestRoot = (function () {
  50010. var result = { root: 0, found: false };
  50011. return function (a, b, c, maxR) {
  50012. result.root = 0;
  50013. result.found = false;
  50014. var determinant = b * b - 4.0 * a * c;
  50015. if (determinant < 0)
  50016. return result;
  50017. var sqrtD = Math.sqrt(determinant);
  50018. var r1 = (-b - sqrtD) / (2.0 * a);
  50019. var r2 = (-b + sqrtD) / (2.0 * a);
  50020. if (r1 > r2) {
  50021. var temp = r2;
  50022. r2 = r1;
  50023. r1 = temp;
  50024. }
  50025. if (r1 > 0 && r1 < maxR) {
  50026. result.root = r1;
  50027. result.found = true;
  50028. return result;
  50029. }
  50030. if (r2 > 0 && r2 < maxR) {
  50031. result.root = r2;
  50032. result.found = true;
  50033. return result;
  50034. }
  50035. return result;
  50036. };
  50037. })();
  50038. var Collider = /** @class */ (function () {
  50039. function Collider() {
  50040. this._collisionPoint = BABYLON.Vector3.Zero();
  50041. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50042. this._tempVector = BABYLON.Vector3.Zero();
  50043. this._tempVector2 = BABYLON.Vector3.Zero();
  50044. this._tempVector3 = BABYLON.Vector3.Zero();
  50045. this._tempVector4 = BABYLON.Vector3.Zero();
  50046. this._edge = BABYLON.Vector3.Zero();
  50047. this._baseToVertex = BABYLON.Vector3.Zero();
  50048. this._destinationPoint = BABYLON.Vector3.Zero();
  50049. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50050. this._displacementVector = BABYLON.Vector3.Zero();
  50051. this._radius = BABYLON.Vector3.One();
  50052. this._retry = 0;
  50053. this._basePointWorld = BABYLON.Vector3.Zero();
  50054. this._velocityWorld = BABYLON.Vector3.Zero();
  50055. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50056. this._collisionMask = -1;
  50057. }
  50058. Object.defineProperty(Collider.prototype, "collisionMask", {
  50059. get: function () {
  50060. return this._collisionMask;
  50061. },
  50062. set: function (mask) {
  50063. this._collisionMask = !isNaN(mask) ? mask : -1;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50069. /**
  50070. * Gets the plane normal used to compute the sliding response (in local space)
  50071. */
  50072. get: function () {
  50073. return this._slidePlaneNormal;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. // Methods
  50079. Collider.prototype._initialize = function (source, dir, e) {
  50080. this._velocity = dir;
  50081. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50082. this._basePoint = source;
  50083. source.multiplyToRef(this._radius, this._basePointWorld);
  50084. dir.multiplyToRef(this._radius, this._velocityWorld);
  50085. this._velocityWorldLength = this._velocityWorld.length();
  50086. this._epsilon = e;
  50087. this.collisionFound = false;
  50088. };
  50089. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50090. pa.subtractToRef(point, this._tempVector);
  50091. pb.subtractToRef(point, this._tempVector2);
  50092. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50093. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50094. if (d < 0)
  50095. return false;
  50096. pc.subtractToRef(point, this._tempVector3);
  50097. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50098. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50099. if (d < 0)
  50100. return false;
  50101. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50102. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50103. return d >= 0;
  50104. };
  50105. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50106. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50107. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50108. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50109. return false;
  50110. }
  50111. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50112. return false;
  50113. return true;
  50114. };
  50115. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50116. var t0;
  50117. var embeddedInPlane = false;
  50118. //defensive programming, actually not needed.
  50119. if (!trianglePlaneArray) {
  50120. trianglePlaneArray = [];
  50121. }
  50122. if (!trianglePlaneArray[faceIndex]) {
  50123. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50124. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50125. }
  50126. var trianglePlane = trianglePlaneArray[faceIndex];
  50127. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50128. return;
  50129. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50130. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50131. if (normalDotVelocity == 0) {
  50132. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50133. return;
  50134. embeddedInPlane = true;
  50135. t0 = 0;
  50136. }
  50137. else {
  50138. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50139. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50140. if (t0 > t1) {
  50141. var temp = t1;
  50142. t1 = t0;
  50143. t0 = temp;
  50144. }
  50145. if (t0 > 1.0 || t1 < 0.0)
  50146. return;
  50147. if (t0 < 0)
  50148. t0 = 0;
  50149. if (t0 > 1.0)
  50150. t0 = 1.0;
  50151. }
  50152. this._collisionPoint.copyFromFloats(0, 0, 0);
  50153. var found = false;
  50154. var t = 1.0;
  50155. if (!embeddedInPlane) {
  50156. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50157. this._velocity.scaleToRef(t0, this._tempVector);
  50158. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50159. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50160. found = true;
  50161. t = t0;
  50162. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50163. }
  50164. }
  50165. if (!found) {
  50166. var velocitySquaredLength = this._velocity.lengthSquared();
  50167. var a = velocitySquaredLength;
  50168. this._basePoint.subtractToRef(p1, this._tempVector);
  50169. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50170. var c = this._tempVector.lengthSquared() - 1.0;
  50171. var lowestRoot = getLowestRoot(a, b, c, t);
  50172. if (lowestRoot.found) {
  50173. t = lowestRoot.root;
  50174. found = true;
  50175. this._collisionPoint.copyFrom(p1);
  50176. }
  50177. this._basePoint.subtractToRef(p2, this._tempVector);
  50178. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50179. c = this._tempVector.lengthSquared() - 1.0;
  50180. lowestRoot = getLowestRoot(a, b, c, t);
  50181. if (lowestRoot.found) {
  50182. t = lowestRoot.root;
  50183. found = true;
  50184. this._collisionPoint.copyFrom(p2);
  50185. }
  50186. this._basePoint.subtractToRef(p3, this._tempVector);
  50187. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50188. c = this._tempVector.lengthSquared() - 1.0;
  50189. lowestRoot = getLowestRoot(a, b, c, t);
  50190. if (lowestRoot.found) {
  50191. t = lowestRoot.root;
  50192. found = true;
  50193. this._collisionPoint.copyFrom(p3);
  50194. }
  50195. p2.subtractToRef(p1, this._edge);
  50196. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50197. var edgeSquaredLength = this._edge.lengthSquared();
  50198. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50199. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50200. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50201. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50202. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50203. lowestRoot = getLowestRoot(a, b, c, t);
  50204. if (lowestRoot.found) {
  50205. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50206. if (f >= 0.0 && f <= 1.0) {
  50207. t = lowestRoot.root;
  50208. found = true;
  50209. this._edge.scaleInPlace(f);
  50210. p1.addToRef(this._edge, this._collisionPoint);
  50211. }
  50212. }
  50213. p3.subtractToRef(p2, this._edge);
  50214. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50215. edgeSquaredLength = this._edge.lengthSquared();
  50216. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50217. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50218. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50219. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50220. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50221. lowestRoot = getLowestRoot(a, b, c, t);
  50222. if (lowestRoot.found) {
  50223. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50224. if (f >= 0.0 && f <= 1.0) {
  50225. t = lowestRoot.root;
  50226. found = true;
  50227. this._edge.scaleInPlace(f);
  50228. p2.addToRef(this._edge, this._collisionPoint);
  50229. }
  50230. }
  50231. p1.subtractToRef(p3, this._edge);
  50232. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50233. edgeSquaredLength = this._edge.lengthSquared();
  50234. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50235. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50236. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50237. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50238. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50239. lowestRoot = getLowestRoot(a, b, c, t);
  50240. if (lowestRoot.found) {
  50241. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50242. if (f >= 0.0 && f <= 1.0) {
  50243. t = lowestRoot.root;
  50244. found = true;
  50245. this._edge.scaleInPlace(f);
  50246. p3.addToRef(this._edge, this._collisionPoint);
  50247. }
  50248. }
  50249. }
  50250. if (found) {
  50251. var distToCollision = t * this._velocity.length();
  50252. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50253. if (!this.intersectionPoint) {
  50254. this.intersectionPoint = this._collisionPoint.clone();
  50255. }
  50256. else {
  50257. this.intersectionPoint.copyFrom(this._collisionPoint);
  50258. }
  50259. this._nearestDistance = distToCollision;
  50260. this.collisionFound = true;
  50261. }
  50262. }
  50263. };
  50264. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50265. for (var i = indexStart; i < indexEnd; i += 3) {
  50266. var p1 = pts[indices[i] - decal];
  50267. var p2 = pts[indices[i + 1] - decal];
  50268. var p3 = pts[indices[i + 2] - decal];
  50269. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50270. }
  50271. };
  50272. Collider.prototype._getResponse = function (pos, vel) {
  50273. pos.addToRef(vel, this._destinationPoint);
  50274. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50275. this._basePoint.addToRef(vel, pos);
  50276. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50277. this._slidePlaneNormal.normalize();
  50278. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50279. pos.addInPlace(this._displacementVector);
  50280. this.intersectionPoint.addInPlace(this._displacementVector);
  50281. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50282. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50283. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50284. };
  50285. return Collider;
  50286. }());
  50287. BABYLON.Collider = Collider;
  50288. })(BABYLON || (BABYLON = {}));
  50289. //# sourceMappingURL=babylon.collider.js.map
  50290. var BABYLON;
  50291. (function (BABYLON) {
  50292. //WebWorker code will be inserted to this variable.
  50293. BABYLON.CollisionWorker = "";
  50294. var WorkerTaskType;
  50295. (function (WorkerTaskType) {
  50296. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50297. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50298. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50299. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50300. var WorkerReplyType;
  50301. (function (WorkerReplyType) {
  50302. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50303. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50304. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50305. var CollisionCoordinatorWorker = /** @class */ (function () {
  50306. function CollisionCoordinatorWorker() {
  50307. var _this = this;
  50308. this._scaledPosition = BABYLON.Vector3.Zero();
  50309. this._scaledVelocity = BABYLON.Vector3.Zero();
  50310. this.onMeshUpdated = function (transformNode) {
  50311. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50312. };
  50313. this.onGeometryUpdated = function (geometry) {
  50314. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50315. };
  50316. this._afterRender = function () {
  50317. if (!_this._init)
  50318. return;
  50319. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50320. return;
  50321. }
  50322. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50323. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50324. if (_this._runningUpdated > 4) {
  50325. return;
  50326. }
  50327. ++_this._runningUpdated;
  50328. var payload = {
  50329. updatedMeshes: _this._addUpdateMeshesList,
  50330. updatedGeometries: _this._addUpdateGeometriesList,
  50331. removedGeometries: _this._toRemoveGeometryArray,
  50332. removedMeshes: _this._toRemoveMeshesArray
  50333. };
  50334. var message = {
  50335. payload: payload,
  50336. taskType: WorkerTaskType.UPDATE
  50337. };
  50338. var serializable = [];
  50339. for (var id in payload.updatedGeometries) {
  50340. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50341. //prepare transferables
  50342. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50343. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50344. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50345. }
  50346. }
  50347. _this._worker.postMessage(message, serializable);
  50348. _this._addUpdateMeshesList = {};
  50349. _this._addUpdateGeometriesList = {};
  50350. _this._toRemoveGeometryArray = [];
  50351. _this._toRemoveMeshesArray = [];
  50352. };
  50353. this._onMessageFromWorker = function (e) {
  50354. var returnData = e.data;
  50355. if (returnData.error != WorkerReplyType.SUCCESS) {
  50356. //TODO what errors can be returned from the worker?
  50357. BABYLON.Tools.Warn("error returned from worker!");
  50358. return;
  50359. }
  50360. switch (returnData.taskType) {
  50361. case WorkerTaskType.INIT:
  50362. _this._init = true;
  50363. //Update the worked with ALL of the scene's current state
  50364. _this._scene.meshes.forEach(function (mesh) {
  50365. _this.onMeshAdded(mesh);
  50366. });
  50367. _this._scene.getGeometries().forEach(function (geometry) {
  50368. _this.onGeometryAdded(geometry);
  50369. });
  50370. break;
  50371. case WorkerTaskType.UPDATE:
  50372. _this._runningUpdated--;
  50373. break;
  50374. case WorkerTaskType.COLLIDE:
  50375. var returnPayload = returnData.payload;
  50376. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50377. return;
  50378. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50379. if (callback) {
  50380. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50381. if (mesh) {
  50382. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50383. }
  50384. }
  50385. //cleanup
  50386. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50387. break;
  50388. }
  50389. };
  50390. this._collisionsCallbackArray = [];
  50391. this._init = false;
  50392. this._runningUpdated = 0;
  50393. this._addUpdateMeshesList = {};
  50394. this._addUpdateGeometriesList = {};
  50395. this._toRemoveGeometryArray = [];
  50396. this._toRemoveMeshesArray = [];
  50397. }
  50398. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50399. if (!this._init)
  50400. return;
  50401. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50402. return;
  50403. position.divideToRef(collider._radius, this._scaledPosition);
  50404. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50405. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50406. var payload = {
  50407. collider: {
  50408. position: this._scaledPosition.asArray(),
  50409. velocity: this._scaledVelocity.asArray(),
  50410. radius: collider._radius.asArray()
  50411. },
  50412. collisionId: collisionIndex,
  50413. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50414. maximumRetry: maximumRetry
  50415. };
  50416. var message = {
  50417. payload: payload,
  50418. taskType: WorkerTaskType.COLLIDE
  50419. };
  50420. this._worker.postMessage(message);
  50421. };
  50422. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50423. this._scene = scene;
  50424. this._scene.registerAfterRender(this._afterRender);
  50425. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50426. this._worker = new Worker(workerUrl);
  50427. this._worker.onmessage = this._onMessageFromWorker;
  50428. var message = {
  50429. payload: {},
  50430. taskType: WorkerTaskType.INIT
  50431. };
  50432. this._worker.postMessage(message);
  50433. };
  50434. CollisionCoordinatorWorker.prototype.destroy = function () {
  50435. this._scene.unregisterAfterRender(this._afterRender);
  50436. this._worker.terminate();
  50437. };
  50438. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50439. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50440. this.onMeshUpdated(mesh);
  50441. };
  50442. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50443. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50444. };
  50445. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50446. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50447. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50448. this.onGeometryUpdated(geometry);
  50449. };
  50450. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50451. this._toRemoveGeometryArray.push(geometry.id);
  50452. };
  50453. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50454. var submeshes = [];
  50455. if (mesh.subMeshes) {
  50456. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50457. var boundingInfo = sm.getBoundingInfo();
  50458. return {
  50459. position: idx,
  50460. verticesStart: sm.verticesStart,
  50461. verticesCount: sm.verticesCount,
  50462. indexStart: sm.indexStart,
  50463. indexCount: sm.indexCount,
  50464. hasMaterial: !!sm.getMaterial(),
  50465. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50466. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50467. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50468. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50469. };
  50470. });
  50471. }
  50472. var geometryId = null;
  50473. if (mesh instanceof BABYLON.Mesh) {
  50474. var geometry = mesh.geometry;
  50475. geometryId = geometry ? geometry.id : null;
  50476. }
  50477. else if (mesh instanceof BABYLON.InstancedMesh) {
  50478. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50479. geometryId = geometry ? geometry.id : null;
  50480. }
  50481. var boundingInfo = mesh.getBoundingInfo();
  50482. return {
  50483. uniqueId: mesh.uniqueId,
  50484. id: mesh.id,
  50485. name: mesh.name,
  50486. geometryId: geometryId,
  50487. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50488. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50489. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50490. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50491. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50492. subMeshes: submeshes,
  50493. checkCollisions: mesh.checkCollisions
  50494. };
  50495. };
  50496. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50497. return {
  50498. id: geometry.id,
  50499. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50500. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50501. indices: new Uint32Array(geometry.getIndices() || []),
  50502. };
  50503. };
  50504. return CollisionCoordinatorWorker;
  50505. }());
  50506. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50507. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50508. function CollisionCoordinatorLegacy() {
  50509. this._scaledPosition = BABYLON.Vector3.Zero();
  50510. this._scaledVelocity = BABYLON.Vector3.Zero();
  50511. this._finalPosition = BABYLON.Vector3.Zero();
  50512. }
  50513. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50514. position.divideToRef(collider._radius, this._scaledPosition);
  50515. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50516. collider.collidedMesh = null;
  50517. collider._retry = 0;
  50518. collider._initialVelocity = this._scaledVelocity;
  50519. collider._initialPosition = this._scaledPosition;
  50520. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50521. this._finalPosition.multiplyInPlace(collider._radius);
  50522. //run the callback
  50523. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50524. };
  50525. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50526. this._scene = scene;
  50527. };
  50528. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50529. //Legacy need no destruction method.
  50530. };
  50531. //No update in legacy mode
  50532. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50533. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50534. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50535. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50536. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50537. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50538. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50539. if (excludedMesh === void 0) { excludedMesh = null; }
  50540. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50541. if (collider._retry >= maximumRetry) {
  50542. finalPosition.copyFrom(position);
  50543. return;
  50544. }
  50545. // Check if this is a mesh else camera or -1
  50546. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50547. collider._initialize(position, velocity, closeDistance);
  50548. // Check all meshes
  50549. for (var index = 0; index < this._scene.meshes.length; index++) {
  50550. var mesh = this._scene.meshes[index];
  50551. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50552. mesh._checkCollision(collider);
  50553. }
  50554. }
  50555. if (!collider.collisionFound) {
  50556. position.addToRef(velocity, finalPosition);
  50557. return;
  50558. }
  50559. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50560. collider._getResponse(position, velocity);
  50561. }
  50562. if (velocity.length() <= closeDistance) {
  50563. finalPosition.copyFrom(position);
  50564. return;
  50565. }
  50566. collider._retry++;
  50567. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50568. };
  50569. return CollisionCoordinatorLegacy;
  50570. }());
  50571. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50572. })(BABYLON || (BABYLON = {}));
  50573. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50574. var BABYLON;
  50575. (function (BABYLON) {
  50576. /**
  50577. * A particle represents one of the element emitted by a particle system.
  50578. * This is mainly define by its coordinates, direction, velocity and age.
  50579. */
  50580. var Particle = /** @class */ (function () {
  50581. /**
  50582. * Creates a new instance of @see Particle
  50583. * @param particleSystem the particle system the particle belongs to
  50584. */
  50585. function Particle(particleSystem) {
  50586. this.particleSystem = particleSystem;
  50587. /**
  50588. * The world position of the particle in the scene.
  50589. */
  50590. this.position = BABYLON.Vector3.Zero();
  50591. /**
  50592. * The world direction of the particle in the scene.
  50593. */
  50594. this.direction = BABYLON.Vector3.Zero();
  50595. /**
  50596. * The color of the particle.
  50597. */
  50598. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50599. /**
  50600. * The color change of the particle per step.
  50601. */
  50602. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50603. /**
  50604. * Defines how long will the life of the particle be.
  50605. */
  50606. this.lifeTime = 1.0;
  50607. /**
  50608. * The current age of the particle.
  50609. */
  50610. this.age = 0;
  50611. /**
  50612. * The current size of the particle.
  50613. */
  50614. this.size = 0;
  50615. /**
  50616. * The current angle of the particle.
  50617. */
  50618. this.angle = 0;
  50619. /**
  50620. * Defines how fast is the angle changing.
  50621. */
  50622. this.angularSpeed = 0;
  50623. /**
  50624. * Defines the cell index used by the particle to be rendered from a sprite.
  50625. */
  50626. this.cellIndex = 0;
  50627. this._currentFrameCounter = 0;
  50628. if (!this.particleSystem.isAnimationSheetEnabled) {
  50629. return;
  50630. }
  50631. this.cellIndex = this.particleSystem.startSpriteCellID;
  50632. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50633. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50634. }
  50635. else {
  50636. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50637. }
  50638. }
  50639. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50640. // (ageOffset / scaledUpdateSpeed) / available cells
  50641. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50642. this._currentFrameCounter += scaledUpdateSpeed;
  50643. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50644. this._currentFrameCounter = 0;
  50645. this.cellIndex++;
  50646. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50647. this.cellIndex = this.particleSystem.endSpriteCellID;
  50648. }
  50649. }
  50650. };
  50651. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50652. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50653. this.cellIndex++;
  50654. this._currentFrameCounter = 0;
  50655. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50656. if (this.particleSystem.spriteCellLoop) {
  50657. this.cellIndex = this.particleSystem.startSpriteCellID;
  50658. }
  50659. else {
  50660. this.cellIndex = this.particleSystem.endSpriteCellID;
  50661. }
  50662. }
  50663. }
  50664. else {
  50665. this._currentFrameCounter++;
  50666. }
  50667. };
  50668. /**
  50669. * Copy the properties of particle to another one.
  50670. * @param other the particle to copy the information to.
  50671. */
  50672. Particle.prototype.copyTo = function (other) {
  50673. other.position.copyFrom(this.position);
  50674. other.direction.copyFrom(this.direction);
  50675. other.color.copyFrom(this.color);
  50676. other.colorStep.copyFrom(this.colorStep);
  50677. other.lifeTime = this.lifeTime;
  50678. other.age = this.age;
  50679. other.size = this.size;
  50680. other.angle = this.angle;
  50681. other.angularSpeed = this.angularSpeed;
  50682. other.particleSystem = this.particleSystem;
  50683. other.cellIndex = this.cellIndex;
  50684. };
  50685. return Particle;
  50686. }());
  50687. BABYLON.Particle = Particle;
  50688. })(BABYLON || (BABYLON = {}));
  50689. //# sourceMappingURL=babylon.particle.js.map
  50690. var BABYLON;
  50691. (function (BABYLON) {
  50692. /**
  50693. * This represents a particle system in Babylon.
  50694. * 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.
  50695. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50696. * @example https://doc.babylonjs.com/babylon101/particles
  50697. */
  50698. var ParticleSystem = /** @class */ (function () {
  50699. /**
  50700. * Instantiates a particle system.
  50701. * 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.
  50702. * @param name The name of the particle system
  50703. * @param capacity The max number of particles alive at the same time
  50704. * @param scene The scene the particle system belongs to
  50705. * @param customEffect a custom effect used to change the way particles are rendered by default
  50706. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50707. * @param epsilon Offset used to render the particles
  50708. */
  50709. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50710. if (customEffect === void 0) { customEffect = null; }
  50711. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50712. if (epsilon === void 0) { epsilon = 0.01; }
  50713. var _this = this;
  50714. /**
  50715. * List of animations used by the particle system.
  50716. */
  50717. this.animations = [];
  50718. /**
  50719. * The rendering group used by the Particle system to chose when to render.
  50720. */
  50721. this.renderingGroupId = 0;
  50722. /**
  50723. * The emitter represents the Mesh or position we are attaching the particle system to.
  50724. */
  50725. this.emitter = null;
  50726. /**
  50727. * The maximum number of particles to emit per frame
  50728. */
  50729. this.emitRate = 10;
  50730. /**
  50731. * If you want to launch only a few particles at once, that can be done, as well.
  50732. */
  50733. this.manualEmitCount = -1;
  50734. /**
  50735. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50736. */
  50737. this.updateSpeed = 0.01;
  50738. /**
  50739. * The amount of time the particle system is running (depends of the overall update speed).
  50740. */
  50741. this.targetStopDuration = 0;
  50742. /**
  50743. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50744. */
  50745. this.disposeOnStop = false;
  50746. /**
  50747. * Minimum power of emitting particles.
  50748. */
  50749. this.minEmitPower = 1;
  50750. /**
  50751. * Maximum power of emitting particles.
  50752. */
  50753. this.maxEmitPower = 1;
  50754. /**
  50755. * Minimum life time of emitting particles.
  50756. */
  50757. this.minLifeTime = 1;
  50758. /**
  50759. * Maximum life time of emitting particles.
  50760. */
  50761. this.maxLifeTime = 1;
  50762. /**
  50763. * Minimum Size of emitting particles.
  50764. */
  50765. this.minSize = 1;
  50766. /**
  50767. * Maximum Size of emitting particles.
  50768. */
  50769. this.maxSize = 1;
  50770. /**
  50771. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50772. */
  50773. this.minAngularSpeed = 0;
  50774. /**
  50775. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50776. */
  50777. this.maxAngularSpeed = 0;
  50778. /**
  50779. * The layer mask we are rendering the particles through.
  50780. */
  50781. this.layerMask = 0x0FFFFFFF;
  50782. /**
  50783. * This can help using your own shader to render the particle system.
  50784. * The according effect will be created
  50785. */
  50786. this.customShader = null;
  50787. /**
  50788. * By default particle system starts as soon as they are created. This prevents the
  50789. * automatic start to happen and let you decide when to start emitting particles.
  50790. */
  50791. this.preventAutoStart = false;
  50792. /**
  50793. * Callback triggered when the particle animation is ending.
  50794. */
  50795. this.onAnimationEnd = null;
  50796. /**
  50797. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50798. */
  50799. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50800. /**
  50801. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50802. * to override the particles.
  50803. */
  50804. this.forceDepthWrite = false;
  50805. /**
  50806. * You can use gravity if you want to give an orientation to your particles.
  50807. */
  50808. this.gravity = BABYLON.Vector3.Zero();
  50809. /**
  50810. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50811. */
  50812. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50813. /**
  50814. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50815. */
  50816. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50817. /**
  50818. * Color the particle will have at the end of its lifetime.
  50819. */
  50820. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50821. /**
  50822. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50823. */
  50824. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50825. /**
  50826. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50827. */
  50828. this.spriteCellLoop = true;
  50829. /**
  50830. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50831. */
  50832. this.spriteCellChangeSpeed = 0;
  50833. /**
  50834. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50835. */
  50836. this.startSpriteCellID = 0;
  50837. /**
  50838. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50839. */
  50840. this.endSpriteCellID = 0;
  50841. /**
  50842. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50843. */
  50844. this.spriteCellWidth = 0;
  50845. /**
  50846. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50847. */
  50848. this.spriteCellHeight = 0;
  50849. /**
  50850. * An event triggered when the system is disposed.
  50851. */
  50852. this.onDisposeObservable = new BABYLON.Observable();
  50853. this._particles = new Array();
  50854. this._stockParticles = new Array();
  50855. this._newPartsExcess = 0;
  50856. this._vertexBuffers = {};
  50857. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50858. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50859. this._scaledDirection = BABYLON.Vector3.Zero();
  50860. this._scaledGravity = BABYLON.Vector3.Zero();
  50861. this._currentRenderId = -1;
  50862. this._started = false;
  50863. this._stopped = false;
  50864. this._actualFrame = 0;
  50865. this._vertexBufferSize = 11;
  50866. this._appendParticleVertexes = null;
  50867. this.id = name;
  50868. this.name = name;
  50869. this._capacity = capacity;
  50870. this._epsilon = epsilon;
  50871. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50872. if (isAnimationSheetEnabled) {
  50873. this._vertexBufferSize = 12;
  50874. }
  50875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50876. this._customEffect = customEffect;
  50877. scene.particleSystems.push(this);
  50878. this._createIndexBuffer();
  50879. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50880. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50881. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50882. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50883. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50884. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50885. if (this._isAnimationSheetEnabled) {
  50886. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50887. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50888. }
  50889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50890. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50891. this._vertexBuffers["options"] = options;
  50892. // Default emitter type
  50893. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50894. this.updateFunction = function (particles) {
  50895. for (var index = 0; index < particles.length; index++) {
  50896. var particle = particles[index];
  50897. particle.age += _this._scaledUpdateSpeed;
  50898. if (particle.age >= particle.lifeTime) {
  50899. _this.recycleParticle(particle);
  50900. index--;
  50901. continue;
  50902. }
  50903. else {
  50904. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50905. particle.color.addInPlace(_this._scaledColorStep);
  50906. if (particle.color.a < 0)
  50907. particle.color.a = 0;
  50908. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50909. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50910. particle.position.addInPlace(_this._scaledDirection);
  50911. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50912. particle.direction.addInPlace(_this._scaledGravity);
  50913. if (_this._isAnimationSheetEnabled) {
  50914. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50915. }
  50916. }
  50917. }
  50918. };
  50919. }
  50920. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50921. /**
  50922. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50924. */
  50925. get: function () {
  50926. if (this.particleEmitterType.direction1) {
  50927. return this.particleEmitterType.direction1;
  50928. }
  50929. return BABYLON.Vector3.Zero();
  50930. },
  50931. set: function (value) {
  50932. if (this.particleEmitterType.direction1) {
  50933. this.particleEmitterType.direction1 = value;
  50934. }
  50935. },
  50936. enumerable: true,
  50937. configurable: true
  50938. });
  50939. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50940. /**
  50941. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50943. */
  50944. get: function () {
  50945. if (this.particleEmitterType.direction2) {
  50946. return this.particleEmitterType.direction2;
  50947. }
  50948. return BABYLON.Vector3.Zero();
  50949. },
  50950. set: function (value) {
  50951. if (this.particleEmitterType.direction2) {
  50952. this.particleEmitterType.direction2 = value;
  50953. }
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50959. /**
  50960. * 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.
  50961. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50962. */
  50963. get: function () {
  50964. if (this.particleEmitterType.minEmitBox) {
  50965. return this.particleEmitterType.minEmitBox;
  50966. }
  50967. return BABYLON.Vector3.Zero();
  50968. },
  50969. set: function (value) {
  50970. if (this.particleEmitterType.minEmitBox) {
  50971. this.particleEmitterType.minEmitBox = value;
  50972. }
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50978. /**
  50979. * 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.
  50980. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50981. */
  50982. get: function () {
  50983. if (this.particleEmitterType.maxEmitBox) {
  50984. return this.particleEmitterType.maxEmitBox;
  50985. }
  50986. return BABYLON.Vector3.Zero();
  50987. },
  50988. set: function (value) {
  50989. if (this.particleEmitterType.maxEmitBox) {
  50990. this.particleEmitterType.maxEmitBox = value;
  50991. }
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50997. /**
  50998. * Sets a callback that will be triggered when the system is disposed.
  50999. */
  51000. set: function (callback) {
  51001. if (this._onDisposeObserver) {
  51002. this.onDisposeObservable.remove(this._onDisposeObserver);
  51003. }
  51004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51005. },
  51006. enumerable: true,
  51007. configurable: true
  51008. });
  51009. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51010. /**
  51011. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51012. */
  51013. get: function () {
  51014. return this._isAnimationSheetEnabled;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51020. /**
  51021. * Gets the current list of active particles
  51022. */
  51023. get: function () {
  51024. return this._particles;
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. /**
  51030. * Returns the string "ParticleSystem"
  51031. * @returns a string containing the class name
  51032. */
  51033. ParticleSystem.prototype.getClassName = function () {
  51034. return "ParticleSystem";
  51035. };
  51036. ParticleSystem.prototype._createIndexBuffer = function () {
  51037. var indices = [];
  51038. var index = 0;
  51039. for (var count = 0; count < this._capacity; count++) {
  51040. indices.push(index);
  51041. indices.push(index + 1);
  51042. indices.push(index + 2);
  51043. indices.push(index);
  51044. indices.push(index + 2);
  51045. indices.push(index + 3);
  51046. index += 4;
  51047. }
  51048. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51049. };
  51050. /**
  51051. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51052. * Its lifetime will start back at 0.
  51053. * @param particle The particle to recycle
  51054. */
  51055. ParticleSystem.prototype.recycleParticle = function (particle) {
  51056. var lastParticle = this._particles.pop();
  51057. if (lastParticle !== particle) {
  51058. lastParticle.copyTo(particle);
  51059. this._stockParticles.push(lastParticle);
  51060. }
  51061. };
  51062. /**
  51063. * Gets the maximum number of particles active at the same time.
  51064. * @returns The max number of active particles.
  51065. */
  51066. ParticleSystem.prototype.getCapacity = function () {
  51067. return this._capacity;
  51068. };
  51069. /**
  51070. * Gets Wether there are still active particles in the system.
  51071. * @returns True if it is alive, otherwise false.
  51072. */
  51073. ParticleSystem.prototype.isAlive = function () {
  51074. return this._alive;
  51075. };
  51076. /**
  51077. * Gets Wether the system has been started.
  51078. * @returns True if it has been started, otherwise false.
  51079. */
  51080. ParticleSystem.prototype.isStarted = function () {
  51081. return this._started;
  51082. };
  51083. /**
  51084. * Starts the particle system and begins to emit.
  51085. */
  51086. ParticleSystem.prototype.start = function () {
  51087. this._started = true;
  51088. this._stopped = false;
  51089. this._actualFrame = 0;
  51090. };
  51091. /**
  51092. * Stops the particle system.
  51093. */
  51094. ParticleSystem.prototype.stop = function () {
  51095. this._stopped = true;
  51096. };
  51097. /**
  51098. * Remove all active particles
  51099. */
  51100. ParticleSystem.prototype.reset = function () {
  51101. this._stockParticles = [];
  51102. this._particles = [];
  51103. };
  51104. /**
  51105. * @ignore (for internal use only)
  51106. */
  51107. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51108. var offset = index * this._vertexBufferSize;
  51109. this._vertexData[offset] = particle.position.x;
  51110. this._vertexData[offset + 1] = particle.position.y;
  51111. this._vertexData[offset + 2] = particle.position.z;
  51112. this._vertexData[offset + 3] = particle.color.r;
  51113. this._vertexData[offset + 4] = particle.color.g;
  51114. this._vertexData[offset + 5] = particle.color.b;
  51115. this._vertexData[offset + 6] = particle.color.a;
  51116. this._vertexData[offset + 7] = particle.angle;
  51117. this._vertexData[offset + 8] = particle.size;
  51118. this._vertexData[offset + 9] = offsetX;
  51119. this._vertexData[offset + 10] = offsetY;
  51120. };
  51121. /**
  51122. * @ignore (for internal use only)
  51123. */
  51124. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51125. if (offsetX === 0)
  51126. offsetX = this._epsilon;
  51127. else if (offsetX === 1)
  51128. offsetX = 1 - this._epsilon;
  51129. if (offsetY === 0)
  51130. offsetY = this._epsilon;
  51131. else if (offsetY === 1)
  51132. offsetY = 1 - this._epsilon;
  51133. var offset = index * this._vertexBufferSize;
  51134. this._vertexData[offset] = particle.position.x;
  51135. this._vertexData[offset + 1] = particle.position.y;
  51136. this._vertexData[offset + 2] = particle.position.z;
  51137. this._vertexData[offset + 3] = particle.color.r;
  51138. this._vertexData[offset + 4] = particle.color.g;
  51139. this._vertexData[offset + 5] = particle.color.b;
  51140. this._vertexData[offset + 6] = particle.color.a;
  51141. this._vertexData[offset + 7] = particle.angle;
  51142. this._vertexData[offset + 8] = particle.size;
  51143. this._vertexData[offset + 9] = offsetX;
  51144. this._vertexData[offset + 10] = offsetY;
  51145. this._vertexData[offset + 11] = particle.cellIndex;
  51146. };
  51147. ParticleSystem.prototype._update = function (newParticles) {
  51148. // Update current
  51149. this._alive = this._particles.length > 0;
  51150. this.updateFunction(this._particles);
  51151. // Add new ones
  51152. var worldMatrix;
  51153. if (this.emitter.position) {
  51154. var emitterMesh = this.emitter;
  51155. worldMatrix = emitterMesh.getWorldMatrix();
  51156. }
  51157. else {
  51158. var emitterPosition = this.emitter;
  51159. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51160. }
  51161. var particle;
  51162. for (var index = 0; index < newParticles; index++) {
  51163. if (this._particles.length === this._capacity) {
  51164. break;
  51165. }
  51166. if (this._stockParticles.length !== 0) {
  51167. particle = this._stockParticles.pop();
  51168. particle.age = 0;
  51169. particle.cellIndex = this.startSpriteCellID;
  51170. }
  51171. else {
  51172. particle = new BABYLON.Particle(this);
  51173. }
  51174. this._particles.push(particle);
  51175. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51176. if (this.startPositionFunction) {
  51177. this.startPositionFunction(worldMatrix, particle.position, particle);
  51178. }
  51179. else {
  51180. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51181. }
  51182. if (this.startDirectionFunction) {
  51183. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51184. }
  51185. else {
  51186. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51187. }
  51188. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51189. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51190. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51191. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51192. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51193. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51194. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51195. }
  51196. };
  51197. ParticleSystem.prototype._getEffect = function () {
  51198. if (this._customEffect) {
  51199. return this._customEffect;
  51200. }
  51201. ;
  51202. var defines = [];
  51203. if (this._scene.clipPlane) {
  51204. defines.push("#define CLIPPLANE");
  51205. }
  51206. if (this._isAnimationSheetEnabled) {
  51207. defines.push("#define ANIMATESHEET");
  51208. }
  51209. // Effect
  51210. var join = defines.join("\n");
  51211. if (this._cachedDefines !== join) {
  51212. this._cachedDefines = join;
  51213. var attributesNamesOrOptions;
  51214. var effectCreationOption;
  51215. if (this._isAnimationSheetEnabled) {
  51216. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51217. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51218. }
  51219. else {
  51220. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51221. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51222. }
  51223. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51224. }
  51225. return this._effect;
  51226. };
  51227. /**
  51228. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51229. */
  51230. ParticleSystem.prototype.animate = function () {
  51231. if (!this._started)
  51232. return;
  51233. var effect = this._getEffect();
  51234. // Check
  51235. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51236. return;
  51237. if (this._currentRenderId === this._scene.getRenderId()) {
  51238. return;
  51239. }
  51240. this._currentRenderId = this._scene.getRenderId();
  51241. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51242. // determine the number of particles we need to create
  51243. var newParticles;
  51244. if (this.manualEmitCount > -1) {
  51245. newParticles = this.manualEmitCount;
  51246. this._newPartsExcess = 0;
  51247. this.manualEmitCount = 0;
  51248. }
  51249. else {
  51250. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51251. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51252. }
  51253. if (this._newPartsExcess > 1.0) {
  51254. newParticles += this._newPartsExcess >> 0;
  51255. this._newPartsExcess -= this._newPartsExcess >> 0;
  51256. }
  51257. this._alive = false;
  51258. if (!this._stopped) {
  51259. this._actualFrame += this._scaledUpdateSpeed;
  51260. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51261. this.stop();
  51262. }
  51263. else {
  51264. newParticles = 0;
  51265. }
  51266. this._update(newParticles);
  51267. // Stopped?
  51268. if (this._stopped) {
  51269. if (!this._alive) {
  51270. this._started = false;
  51271. if (this.onAnimationEnd) {
  51272. this.onAnimationEnd();
  51273. }
  51274. if (this.disposeOnStop) {
  51275. this._scene._toBeDisposed.push(this);
  51276. }
  51277. }
  51278. }
  51279. // Animation sheet
  51280. if (this._isAnimationSheetEnabled) {
  51281. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51282. }
  51283. else {
  51284. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51285. }
  51286. // Update VBO
  51287. var offset = 0;
  51288. for (var index = 0; index < this._particles.length; index++) {
  51289. var particle = this._particles[index];
  51290. this._appendParticleVertexes(offset, particle);
  51291. offset += 4;
  51292. }
  51293. if (this._vertexBuffer) {
  51294. this._vertexBuffer.update(this._vertexData);
  51295. }
  51296. };
  51297. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51298. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51299. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51300. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51301. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51302. };
  51303. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51304. this._appendParticleVertex(offset++, particle, 0, 0);
  51305. this._appendParticleVertex(offset++, particle, 1, 0);
  51306. this._appendParticleVertex(offset++, particle, 1, 1);
  51307. this._appendParticleVertex(offset++, particle, 0, 1);
  51308. };
  51309. /**
  51310. * Rebuilds the particle system.
  51311. */
  51312. ParticleSystem.prototype.rebuild = function () {
  51313. this._createIndexBuffer();
  51314. if (this._vertexBuffer) {
  51315. this._vertexBuffer._rebuild();
  51316. }
  51317. };
  51318. /**
  51319. * Renders the particle system in its current state.
  51320. * @returns the current number of particles
  51321. */
  51322. ParticleSystem.prototype.render = function () {
  51323. var effect = this._getEffect();
  51324. // Check
  51325. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51326. return 0;
  51327. }
  51328. var engine = this._scene.getEngine();
  51329. // Render
  51330. engine.enableEffect(effect);
  51331. engine.setState(false);
  51332. var viewMatrix = this._scene.getViewMatrix();
  51333. effect.setTexture("diffuseSampler", this.particleTexture);
  51334. effect.setMatrix("view", viewMatrix);
  51335. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51336. if (this._isAnimationSheetEnabled) {
  51337. var baseSize = this.particleTexture.getBaseSize();
  51338. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51339. }
  51340. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51341. if (this._scene.clipPlane) {
  51342. var clipPlane = this._scene.clipPlane;
  51343. var invView = viewMatrix.clone();
  51344. invView.invert();
  51345. effect.setMatrix("invView", invView);
  51346. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51347. }
  51348. // VBOs
  51349. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51350. // Draw order
  51351. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51352. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51353. }
  51354. else {
  51355. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51356. }
  51357. if (this.forceDepthWrite) {
  51358. engine.setDepthWrite(true);
  51359. }
  51360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51362. return this._particles.length;
  51363. };
  51364. /**
  51365. * Disposes the particle system and free the associated resources
  51366. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51367. */
  51368. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51369. if (disposeTexture === void 0) { disposeTexture = true; }
  51370. if (this._vertexBuffer) {
  51371. this._vertexBuffer.dispose();
  51372. this._vertexBuffer = null;
  51373. }
  51374. if (this._indexBuffer) {
  51375. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51376. this._indexBuffer = null;
  51377. }
  51378. if (disposeTexture && this.particleTexture) {
  51379. this.particleTexture.dispose();
  51380. this.particleTexture = null;
  51381. }
  51382. // Remove from scene
  51383. var index = this._scene.particleSystems.indexOf(this);
  51384. if (index > -1) {
  51385. this._scene.particleSystems.splice(index, 1);
  51386. }
  51387. // Callback
  51388. this.onDisposeObservable.notifyObservers(this);
  51389. this.onDisposeObservable.clear();
  51390. };
  51391. /**
  51392. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51393. * @param radius The radius of the sphere to emit from
  51394. * @returns the emitter
  51395. */
  51396. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51397. if (radius === void 0) { radius = 1; }
  51398. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51399. this.particleEmitterType = particleEmitter;
  51400. return particleEmitter;
  51401. };
  51402. /**
  51403. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51404. * @param radius The radius of the sphere to emit from
  51405. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51406. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51407. * @returns the emitter
  51408. */
  51409. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51410. if (radius === void 0) { radius = 1; }
  51411. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51412. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51413. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51414. this.particleEmitterType = particleEmitter;
  51415. return particleEmitter;
  51416. };
  51417. /**
  51418. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51419. * @param radius The radius of the cone to emit from
  51420. * @param angle The base angle of the cone
  51421. * @returns the emitter
  51422. */
  51423. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51424. if (radius === void 0) { radius = 1; }
  51425. if (angle === void 0) { angle = Math.PI / 4; }
  51426. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51427. this.particleEmitterType = particleEmitter;
  51428. return particleEmitter;
  51429. };
  51430. // 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.
  51431. /**
  51432. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51433. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51434. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51435. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51436. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51437. * @returns the emitter
  51438. */
  51439. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51440. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51441. this.direction1 = direction1;
  51442. this.direction2 = direction2;
  51443. this.minEmitBox = minEmitBox;
  51444. this.maxEmitBox = maxEmitBox;
  51445. this.particleEmitterType = particleEmitter;
  51446. return particleEmitter;
  51447. };
  51448. /**
  51449. * Clones the particle system.
  51450. * @param name The name of the cloned object
  51451. * @param newEmitter The new emitter to use
  51452. * @returns the cloned particle system
  51453. */
  51454. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51455. var custom = null;
  51456. var program = null;
  51457. if (this.customShader != null) {
  51458. program = this.customShader;
  51459. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51460. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51461. }
  51462. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51463. result.customShader = program;
  51464. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51465. if (newEmitter === undefined) {
  51466. newEmitter = this.emitter;
  51467. }
  51468. result.emitter = newEmitter;
  51469. if (this.particleTexture) {
  51470. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51471. }
  51472. if (!this.preventAutoStart) {
  51473. result.start();
  51474. }
  51475. return result;
  51476. };
  51477. /**
  51478. * Serializes the particle system to a JSON object.
  51479. * @returns the JSON object
  51480. */
  51481. ParticleSystem.prototype.serialize = function () {
  51482. var serializationObject = {};
  51483. serializationObject.name = this.name;
  51484. serializationObject.id = this.id;
  51485. // Emitter
  51486. if (this.emitter.position) {
  51487. var emitterMesh = this.emitter;
  51488. serializationObject.emitterId = emitterMesh.id;
  51489. }
  51490. else {
  51491. var emitterPosition = this.emitter;
  51492. serializationObject.emitter = emitterPosition.asArray();
  51493. }
  51494. serializationObject.capacity = this.getCapacity();
  51495. if (this.particleTexture) {
  51496. serializationObject.textureName = this.particleTexture.name;
  51497. }
  51498. // Animations
  51499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51500. // Particle system
  51501. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51502. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51503. serializationObject.minSize = this.minSize;
  51504. serializationObject.maxSize = this.maxSize;
  51505. serializationObject.minEmitPower = this.minEmitPower;
  51506. serializationObject.maxEmitPower = this.maxEmitPower;
  51507. serializationObject.minLifeTime = this.minLifeTime;
  51508. serializationObject.maxLifeTime = this.maxLifeTime;
  51509. serializationObject.emitRate = this.emitRate;
  51510. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51511. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51512. serializationObject.gravity = this.gravity.asArray();
  51513. serializationObject.direction1 = this.direction1.asArray();
  51514. serializationObject.direction2 = this.direction2.asArray();
  51515. serializationObject.color1 = this.color1.asArray();
  51516. serializationObject.color2 = this.color2.asArray();
  51517. serializationObject.colorDead = this.colorDead.asArray();
  51518. serializationObject.updateSpeed = this.updateSpeed;
  51519. serializationObject.targetStopDuration = this.targetStopDuration;
  51520. serializationObject.textureMask = this.textureMask.asArray();
  51521. serializationObject.blendMode = this.blendMode;
  51522. serializationObject.customShader = this.customShader;
  51523. serializationObject.preventAutoStart = this.preventAutoStart;
  51524. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51525. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51526. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51527. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51528. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51529. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51530. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51531. // Emitter
  51532. if (this.particleEmitterType) {
  51533. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51534. }
  51535. return serializationObject;
  51536. };
  51537. /**
  51538. * Parses a JSON object to create a particle system.
  51539. * @param parsedParticleSystem The JSON object to parse
  51540. * @param scene The scene to create the particle system in
  51541. * @param rootUrl The root url to use to load external dependencies like texture
  51542. * @returns the Parsed particle system
  51543. */
  51544. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51545. var name = parsedParticleSystem.name;
  51546. var custom = null;
  51547. var program = null;
  51548. if (parsedParticleSystem.customShader) {
  51549. program = parsedParticleSystem.customShader;
  51550. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51551. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51552. }
  51553. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51554. particleSystem.customShader = program;
  51555. if (parsedParticleSystem.id) {
  51556. particleSystem.id = parsedParticleSystem.id;
  51557. }
  51558. // Auto start
  51559. if (parsedParticleSystem.preventAutoStart) {
  51560. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51561. }
  51562. // Texture
  51563. if (parsedParticleSystem.textureName) {
  51564. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51565. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51566. }
  51567. // Emitter
  51568. if (parsedParticleSystem.emitterId) {
  51569. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51570. }
  51571. else {
  51572. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51573. }
  51574. // Animations
  51575. if (parsedParticleSystem.animations) {
  51576. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51577. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51578. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51579. }
  51580. }
  51581. if (parsedParticleSystem.autoAnimate) {
  51582. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51583. }
  51584. // Particle system
  51585. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51586. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51587. particleSystem.minSize = parsedParticleSystem.minSize;
  51588. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51589. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51590. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51591. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51592. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51593. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51594. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51595. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51596. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51597. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51598. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51599. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51600. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51601. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51602. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51603. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51604. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51605. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51606. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51607. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51608. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51609. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51610. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51611. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51612. if (!particleSystem.preventAutoStart) {
  51613. particleSystem.start();
  51614. }
  51615. return particleSystem;
  51616. };
  51617. /**
  51618. * Source color is added to the destination color without alpha affecting the result.
  51619. */
  51620. ParticleSystem.BLENDMODE_ONEONE = 0;
  51621. /**
  51622. * Blend current color and particle color using particle’s alpha.
  51623. */
  51624. ParticleSystem.BLENDMODE_STANDARD = 1;
  51625. return ParticleSystem;
  51626. }());
  51627. BABYLON.ParticleSystem = ParticleSystem;
  51628. })(BABYLON || (BABYLON = {}));
  51629. //# sourceMappingURL=babylon.particleSystem.js.map
  51630. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51631. var BABYLON;
  51632. (function (BABYLON) {
  51633. /**
  51634. * Particle emitter emitting particles from the inside of a box.
  51635. * It emits the particles randomly between 2 given directions.
  51636. */
  51637. var BoxParticleEmitter = /** @class */ (function () {
  51638. /**
  51639. * Creates a new instance of @see BoxParticleEmitter
  51640. */
  51641. function BoxParticleEmitter() {
  51642. /**
  51643. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51644. */
  51645. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51646. /**
  51647. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51648. */
  51649. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51650. /**
  51651. * 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.
  51652. */
  51653. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51654. /**
  51655. * 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.
  51656. */
  51657. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51658. }
  51659. /**
  51660. * Called by the particle System when the direction is computed for the created particle.
  51661. * @param emitPower is the power of the particle (speed)
  51662. * @param worldMatrix is the world matrix of the particle system
  51663. * @param directionToUpdate is the direction vector to update with the result
  51664. * @param particle is the particle we are computed the direction for
  51665. */
  51666. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51667. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51668. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51669. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51670. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51671. };
  51672. /**
  51673. * Called by the particle System when the position is computed for the created particle.
  51674. * @param worldMatrix is the world matrix of the particle system
  51675. * @param positionToUpdate is the position vector to update with the result
  51676. * @param particle is the particle we are computed the position for
  51677. */
  51678. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51679. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51680. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51681. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51683. };
  51684. /**
  51685. * Clones the current emitter and returns a copy of it
  51686. * @returns the new emitter
  51687. */
  51688. BoxParticleEmitter.prototype.clone = function () {
  51689. var newOne = new BoxParticleEmitter();
  51690. BABYLON.Tools.DeepCopy(this, newOne);
  51691. return newOne;
  51692. };
  51693. /**
  51694. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51695. * @param effect defines the update shader
  51696. */
  51697. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51698. effect.setVector3("direction1", this.direction1);
  51699. effect.setVector3("direction2", this.direction2);
  51700. effect.setVector3("minEmitBox", this.minEmitBox);
  51701. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51702. };
  51703. /**
  51704. * Returns a string to use to update the GPU particles update shader
  51705. * @returns a string containng the defines string
  51706. */
  51707. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51708. return "#define BOXEMITTER";
  51709. };
  51710. /**
  51711. * Returns the string "BoxEmitter"
  51712. * @returns a string containing the class name
  51713. */
  51714. BoxParticleEmitter.prototype.getClassName = function () {
  51715. return "BoxEmitter";
  51716. };
  51717. /**
  51718. * Serializes the particle system to a JSON object.
  51719. * @returns the JSON object
  51720. */
  51721. BoxParticleEmitter.prototype.serialize = function () {
  51722. var serializationObject = {};
  51723. serializationObject.type = this.getClassName();
  51724. serializationObject.direction1 = this.direction1.asArray();
  51725. ;
  51726. serializationObject.direction2 = this.direction2.asArray();
  51727. ;
  51728. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51729. ;
  51730. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51731. ;
  51732. return serializationObject;
  51733. };
  51734. /**
  51735. * Parse properties from a JSON object
  51736. * @param serializationObject defines the JSON object
  51737. */
  51738. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51739. this.direction1.copyFrom(serializationObject.direction1);
  51740. this.direction2.copyFrom(serializationObject.direction2);
  51741. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51742. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51743. };
  51744. return BoxParticleEmitter;
  51745. }());
  51746. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51747. })(BABYLON || (BABYLON = {}));
  51748. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51749. var BABYLON;
  51750. (function (BABYLON) {
  51751. /**
  51752. * Particle emitter emitting particles from the inside of a cone.
  51753. * It emits the particles alongside the cone volume from the base to the particle.
  51754. * The emission direction might be randomized.
  51755. */
  51756. var ConeParticleEmitter = /** @class */ (function () {
  51757. /**
  51758. * Creates a new instance of @see ConeParticleEmitter
  51759. * @param radius the radius of the emission cone (1 by default)
  51760. * @param angles the cone base angle (PI by default)
  51761. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51762. */
  51763. function ConeParticleEmitter(radius,
  51764. /**
  51765. * The radius of the emission cone.
  51766. */
  51767. angle,
  51768. /**
  51769. * The cone base angle.
  51770. */
  51771. directionRandomizer) {
  51772. if (radius === void 0) { radius = 1; }
  51773. if (angle === void 0) { angle = Math.PI; }
  51774. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51775. this.angle = angle;
  51776. this.directionRandomizer = directionRandomizer;
  51777. this.radius = radius;
  51778. }
  51779. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51780. /**
  51781. * Gets the radius of the emission cone.
  51782. */
  51783. get: function () {
  51784. return this._radius;
  51785. },
  51786. /**
  51787. * Sets the radius of the emission cone.
  51788. */
  51789. set: function (value) {
  51790. this._radius = value;
  51791. if (this.angle !== 0) {
  51792. this._height = value / Math.tan(this.angle / 2);
  51793. }
  51794. else {
  51795. this._height = 1;
  51796. }
  51797. },
  51798. enumerable: true,
  51799. configurable: true
  51800. });
  51801. /**
  51802. * Called by the particle System when the direction is computed for the created particle.
  51803. * @param emitPower is the power of the particle (speed)
  51804. * @param worldMatrix is the world matrix of the particle system
  51805. * @param directionToUpdate is the direction vector to update with the result
  51806. * @param particle is the particle we are computed the direction for
  51807. */
  51808. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51809. if (this.angle === 0) {
  51810. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51811. }
  51812. else {
  51813. // measure the direction Vector from the emitter to the particle.
  51814. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51815. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51816. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51817. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51818. direction.x += randX;
  51819. direction.y += randY;
  51820. direction.z += randZ;
  51821. direction.normalize();
  51822. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51823. }
  51824. };
  51825. /**
  51826. * Called by the particle System when the position is computed for the created particle.
  51827. * @param worldMatrix is the world matrix of the particle system
  51828. * @param positionToUpdate is the position vector to update with the result
  51829. * @param particle is the particle we are computed the position for
  51830. */
  51831. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51832. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51833. var h = BABYLON.Scalar.RandomRange(0, 1);
  51834. // Better distribution in a cone at normal angles.
  51835. h = 1 - h * h;
  51836. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51837. radius = radius * h / this._height;
  51838. var randX = radius * Math.sin(s);
  51839. var randZ = radius * Math.cos(s);
  51840. var randY = h * this._height;
  51841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51842. };
  51843. /**
  51844. * Clones the current emitter and returns a copy of it
  51845. * @returns the new emitter
  51846. */
  51847. ConeParticleEmitter.prototype.clone = function () {
  51848. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51849. BABYLON.Tools.DeepCopy(this, newOne);
  51850. return newOne;
  51851. };
  51852. /**
  51853. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51854. * @param effect defines the update shader
  51855. */
  51856. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51857. effect.setFloat("radius", this.radius);
  51858. effect.setFloat("angle", this.angle);
  51859. effect.setFloat("height", this._height);
  51860. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51861. };
  51862. /**
  51863. * Returns a string to use to update the GPU particles update shader
  51864. * @returns a string containng the defines string
  51865. */
  51866. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51867. return "#define CONEEMITTER";
  51868. };
  51869. /**
  51870. * Returns the string "BoxEmitter"
  51871. * @returns a string containing the class name
  51872. */
  51873. ConeParticleEmitter.prototype.getClassName = function () {
  51874. return "ConeEmitter";
  51875. };
  51876. /**
  51877. * Serializes the particle system to a JSON object.
  51878. * @returns the JSON object
  51879. */
  51880. ConeParticleEmitter.prototype.serialize = function () {
  51881. var serializationObject = {};
  51882. serializationObject.type = this.getClassName();
  51883. serializationObject.radius = this.radius;
  51884. serializationObject.angle = this.angle;
  51885. serializationObject.directionRandomizer = this.directionRandomizer;
  51886. return serializationObject;
  51887. };
  51888. /**
  51889. * Parse properties from a JSON object
  51890. * @param serializationObject defines the JSON object
  51891. */
  51892. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51893. this.radius = serializationObject.radius;
  51894. this.angle = serializationObject.angle;
  51895. this.directionRandomizer = serializationObject.directionRandomizer;
  51896. };
  51897. return ConeParticleEmitter;
  51898. }());
  51899. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51900. })(BABYLON || (BABYLON = {}));
  51901. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51902. var BABYLON;
  51903. (function (BABYLON) {
  51904. /**
  51905. * Particle emitter emitting particles from the inside of a sphere.
  51906. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51907. */
  51908. var SphereParticleEmitter = /** @class */ (function () {
  51909. /**
  51910. * Creates a new instance of @see SphereParticleEmitter
  51911. * @param radius the radius of the emission sphere (1 by default)
  51912. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51913. */
  51914. function SphereParticleEmitter(
  51915. /**
  51916. * The radius of the emission sphere.
  51917. */
  51918. radius,
  51919. /**
  51920. * How much to randomize the particle direction [0-1].
  51921. */
  51922. directionRandomizer) {
  51923. if (radius === void 0) { radius = 1; }
  51924. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51925. this.radius = radius;
  51926. this.directionRandomizer = directionRandomizer;
  51927. }
  51928. /**
  51929. * Called by the particle System when the direction is computed for the created particle.
  51930. * @param emitPower is the power of the particle (speed)
  51931. * @param worldMatrix is the world matrix of the particle system
  51932. * @param directionToUpdate is the direction vector to update with the result
  51933. * @param particle is the particle we are computed the direction for
  51934. */
  51935. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51936. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51937. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51938. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51939. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51940. direction.x += randX;
  51941. direction.y += randY;
  51942. direction.z += randZ;
  51943. direction.normalize();
  51944. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51945. };
  51946. /**
  51947. * Called by the particle System when the position is computed for the created particle.
  51948. * @param worldMatrix is the world matrix of the particle system
  51949. * @param positionToUpdate is the position vector to update with the result
  51950. * @param particle is the particle we are computed the position for
  51951. */
  51952. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51953. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51954. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51955. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51956. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51957. var randY = randRadius * Math.cos(theta);
  51958. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51960. };
  51961. /**
  51962. * Clones the current emitter and returns a copy of it
  51963. * @returns the new emitter
  51964. */
  51965. SphereParticleEmitter.prototype.clone = function () {
  51966. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51967. BABYLON.Tools.DeepCopy(this, newOne);
  51968. return newOne;
  51969. };
  51970. /**
  51971. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51972. * @param effect defines the update shader
  51973. */
  51974. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51975. effect.setFloat("radius", this.radius);
  51976. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51977. };
  51978. /**
  51979. * Returns a string to use to update the GPU particles update shader
  51980. * @returns a string containng the defines string
  51981. */
  51982. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51983. return "#define SPHEREEMITTER";
  51984. };
  51985. /**
  51986. * Returns the string "SphereParticleEmitter"
  51987. * @returns a string containing the class name
  51988. */
  51989. SphereParticleEmitter.prototype.getClassName = function () {
  51990. return "SphereParticleEmitter";
  51991. };
  51992. /**
  51993. * Serializes the particle system to a JSON object.
  51994. * @returns the JSON object
  51995. */
  51996. SphereParticleEmitter.prototype.serialize = function () {
  51997. var serializationObject = {};
  51998. serializationObject.type = this.getClassName();
  51999. serializationObject.radius = this.radius;
  52000. serializationObject.directionRandomizer = this.directionRandomizer;
  52001. return serializationObject;
  52002. };
  52003. /**
  52004. * Parse properties from a JSON object
  52005. * @param serializationObject defines the JSON object
  52006. */
  52007. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52008. this.radius = serializationObject.radius;
  52009. this.directionRandomizer = serializationObject.directionRandomizer;
  52010. };
  52011. return SphereParticleEmitter;
  52012. }());
  52013. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52014. /**
  52015. * Particle emitter emitting particles from the inside of a sphere.
  52016. * It emits the particles randomly between two vectors.
  52017. */
  52018. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52019. __extends(SphereDirectedParticleEmitter, _super);
  52020. /**
  52021. * Creates a new instance of @see SphereDirectedParticleEmitter
  52022. * @param radius the radius of the emission sphere (1 by default)
  52023. * @param direction1 the min limit of the emission direction (up vector by default)
  52024. * @param direction2 the max limit of the emission direction (up vector by default)
  52025. */
  52026. function SphereDirectedParticleEmitter(radius,
  52027. /**
  52028. * The min limit of the emission direction.
  52029. */
  52030. direction1,
  52031. /**
  52032. * The max limit of the emission direction.
  52033. */
  52034. direction2) {
  52035. if (radius === void 0) { radius = 1; }
  52036. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52037. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52038. var _this = _super.call(this, radius) || this;
  52039. _this.direction1 = direction1;
  52040. _this.direction2 = direction2;
  52041. return _this;
  52042. }
  52043. /**
  52044. * Called by the particle System when the direction is computed for the created particle.
  52045. * @param emitPower is the power of the particle (speed)
  52046. * @param worldMatrix is the world matrix of the particle system
  52047. * @param directionToUpdate is the direction vector to update with the result
  52048. * @param particle is the particle we are computed the direction for
  52049. */
  52050. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52051. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52052. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52053. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52054. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52055. };
  52056. /**
  52057. * Clones the current emitter and returns a copy of it
  52058. * @returns the new emitter
  52059. */
  52060. SphereDirectedParticleEmitter.prototype.clone = function () {
  52061. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52062. BABYLON.Tools.DeepCopy(this, newOne);
  52063. return newOne;
  52064. };
  52065. /**
  52066. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52067. * @param effect defines the update shader
  52068. */
  52069. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52070. effect.setFloat("radius", this.radius);
  52071. effect.setVector3("direction1", this.direction1);
  52072. effect.setVector3("direction2", this.direction2);
  52073. };
  52074. /**
  52075. * Returns a string to use to update the GPU particles update shader
  52076. * @returns a string containng the defines string
  52077. */
  52078. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52079. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52080. };
  52081. /**
  52082. * Returns the string "SphereDirectedParticleEmitter"
  52083. * @returns a string containing the class name
  52084. */
  52085. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52086. return "SphereDirectedParticleEmitter";
  52087. };
  52088. /**
  52089. * Serializes the particle system to a JSON object.
  52090. * @returns the JSON object
  52091. */
  52092. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52093. var serializationObject = _super.prototype.serialize.call(this);
  52094. ;
  52095. serializationObject.direction1 = this.direction1.asArray();
  52096. ;
  52097. serializationObject.direction2 = this.direction2.asArray();
  52098. ;
  52099. return serializationObject;
  52100. };
  52101. /**
  52102. * Parse properties from a JSON object
  52103. * @param serializationObject defines the JSON object
  52104. */
  52105. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52106. _super.prototype.parse.call(this, serializationObject);
  52107. this.direction1.copyFrom(serializationObject.direction1);
  52108. this.direction2.copyFrom(serializationObject.direction2);
  52109. };
  52110. return SphereDirectedParticleEmitter;
  52111. }(SphereParticleEmitter));
  52112. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52113. })(BABYLON || (BABYLON = {}));
  52114. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52115. var BABYLON;
  52116. (function (BABYLON) {
  52117. /**
  52118. * Represents one particle of a solid particle system.
  52119. * @see SolidParticleSystem
  52120. */
  52121. var SolidParticle = /** @class */ (function () {
  52122. /**
  52123. * Creates a Solid Particle object.
  52124. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52125. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52126. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52127. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52128. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52129. * @param shapeId (integer) is the model shape identifier in the SPS.
  52130. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52131. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52132. */
  52133. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52134. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52135. /**
  52136. * particle global index
  52137. */
  52138. this.idx = 0;
  52139. /**
  52140. * The color of the particle
  52141. */
  52142. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52143. /**
  52144. * The world space position of the particle.
  52145. */
  52146. this.position = BABYLON.Vector3.Zero();
  52147. /**
  52148. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52149. */
  52150. this.rotation = BABYLON.Vector3.Zero();
  52151. /**
  52152. * The scaling of the particle.
  52153. */
  52154. this.scaling = BABYLON.Vector3.One();
  52155. /**
  52156. * The uvs of the particle.
  52157. */
  52158. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52159. /**
  52160. * The current speed of the particle.
  52161. */
  52162. this.velocity = BABYLON.Vector3.Zero();
  52163. /**
  52164. * The pivot point in the particle local space.
  52165. */
  52166. this.pivot = BABYLON.Vector3.Zero();
  52167. /**
  52168. * Must the particle be translated from its pivot point in its local space ?
  52169. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52170. * Default : false
  52171. */
  52172. this.translateFromPivot = false;
  52173. /**
  52174. * Is the particle active or not ?
  52175. */
  52176. this.alive = true;
  52177. /**
  52178. * Is the particle visible or not ?
  52179. */
  52180. this.isVisible = true;
  52181. /**
  52182. * Index of this particle in the global "positions" array (Internal use)
  52183. */
  52184. this._pos = 0;
  52185. /**
  52186. * Index of this particle in the global "indices" array (Internal use)
  52187. */
  52188. this._ind = 0;
  52189. /**
  52190. * ModelShape id of this particle
  52191. */
  52192. this.shapeId = 0;
  52193. /**
  52194. * Index of the particle in its shape id (Internal use)
  52195. */
  52196. this.idxInShape = 0;
  52197. /**
  52198. * Still set as invisible in order to skip useless computations (Internal use)
  52199. */
  52200. this._stillInvisible = false;
  52201. /**
  52202. * Last computed particle rotation matrix
  52203. */
  52204. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52205. /**
  52206. * Parent particle Id, if any.
  52207. * Default null.
  52208. */
  52209. this.parentId = null;
  52210. /**
  52211. * Internal global position in the SPS.
  52212. */
  52213. this._globalPosition = BABYLON.Vector3.Zero();
  52214. this.idx = particleIndex;
  52215. this._pos = positionIndex;
  52216. this._ind = indiceIndex;
  52217. this._model = model;
  52218. this.shapeId = shapeId;
  52219. this.idxInShape = idxInShape;
  52220. this._sps = sps;
  52221. if (modelBoundingInfo) {
  52222. this._modelBoundingInfo = modelBoundingInfo;
  52223. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52224. }
  52225. }
  52226. Object.defineProperty(SolidParticle.prototype, "scale", {
  52227. /**
  52228. * Legacy support, changed scale to scaling
  52229. */
  52230. get: function () {
  52231. return this.scaling;
  52232. },
  52233. /**
  52234. * Legacy support, changed scale to scaling
  52235. */
  52236. set: function (scale) {
  52237. this.scaling = scale;
  52238. },
  52239. enumerable: true,
  52240. configurable: true
  52241. });
  52242. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52243. /**
  52244. * Legacy support, changed quaternion to rotationQuaternion
  52245. */
  52246. get: function () {
  52247. return this.rotationQuaternion;
  52248. },
  52249. /**
  52250. * Legacy support, changed quaternion to rotationQuaternion
  52251. */
  52252. set: function (q) {
  52253. this.rotationQuaternion = q;
  52254. },
  52255. enumerable: true,
  52256. configurable: true
  52257. });
  52258. /**
  52259. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52260. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52261. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52262. * @returns true if it intersects
  52263. */
  52264. SolidParticle.prototype.intersectsMesh = function (target) {
  52265. if (!this._boundingInfo || !target._boundingInfo) {
  52266. return false;
  52267. }
  52268. if (this._sps._bSphereOnly) {
  52269. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52270. }
  52271. return this._boundingInfo.intersects(target._boundingInfo, false);
  52272. };
  52273. return SolidParticle;
  52274. }());
  52275. BABYLON.SolidParticle = SolidParticle;
  52276. /**
  52277. * Represents the shape of the model used by one particle of a solid particle system.
  52278. * SPS internal tool, don't use it manually.
  52279. * @see SolidParticleSystem
  52280. */
  52281. var ModelShape = /** @class */ (function () {
  52282. /**
  52283. * 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.
  52284. * SPS internal tool, don't use it manually.
  52285. * @ignore
  52286. */
  52287. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52288. /**
  52289. * length of the shape in the model indices array (internal use)
  52290. */
  52291. this._indicesLength = 0;
  52292. this.shapeID = id;
  52293. this._shape = shape;
  52294. this._indicesLength = indicesLength;
  52295. this._shapeUV = shapeUV;
  52296. this._positionFunction = posFunction;
  52297. this._vertexFunction = vtxFunction;
  52298. }
  52299. return ModelShape;
  52300. }());
  52301. BABYLON.ModelShape = ModelShape;
  52302. /**
  52303. * Represents a Depth Sorted Particle in the solid particle system.
  52304. * @see SolidParticleSystem
  52305. */
  52306. var DepthSortedParticle = /** @class */ (function () {
  52307. function DepthSortedParticle() {
  52308. /**
  52309. * Index of the particle in the "indices" array
  52310. */
  52311. this.ind = 0;
  52312. /**
  52313. * Length of the particle shape in the "indices" array
  52314. */
  52315. this.indicesLength = 0;
  52316. /**
  52317. * Squared distance from the particle to the camera
  52318. */
  52319. this.sqDistance = 0.0;
  52320. }
  52321. return DepthSortedParticle;
  52322. }());
  52323. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52324. })(BABYLON || (BABYLON = {}));
  52325. //# sourceMappingURL=babylon.solidParticle.js.map
  52326. var BABYLON;
  52327. (function (BABYLON) {
  52328. /**
  52329. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52330. *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.
  52331. * The SPS is also a particle system. It provides some methods to manage the particles.
  52332. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52333. *
  52334. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52335. */
  52336. var SolidParticleSystem = /** @class */ (function () {
  52337. /**
  52338. * Creates a SPS (Solid Particle System) object.
  52339. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52340. * @param scene (Scene) is the scene in which the SPS is added.
  52341. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52342. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52343. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52344. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52345. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52346. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52347. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52348. */
  52349. function SolidParticleSystem(name, scene, options) {
  52350. /**
  52351. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52352. * Example : var p = SPS.particles[i];
  52353. */
  52354. this.particles = new Array();
  52355. /**
  52356. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52357. */
  52358. this.nbParticles = 0;
  52359. /**
  52360. * If the particles must ever face the camera (default false). Useful for planar particles.
  52361. */
  52362. this.billboard = false;
  52363. /**
  52364. * Recompute normals when adding a shape
  52365. */
  52366. this.recomputeNormals = true;
  52367. /**
  52368. * This a counter ofr your own usage. It's not set by any SPS functions.
  52369. */
  52370. this.counter = 0;
  52371. /**
  52372. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52373. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52374. */
  52375. this.vars = {};
  52376. /**
  52377. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52378. */
  52379. this._bSphereOnly = false;
  52380. /**
  52381. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52382. */
  52383. this._bSphereRadiusFactor = 1.0;
  52384. this._positions = new Array();
  52385. this._indices = new Array();
  52386. this._normals = new Array();
  52387. this._colors = new Array();
  52388. this._uvs = new Array();
  52389. this._index = 0; // indices index
  52390. this._updatable = true;
  52391. this._pickable = false;
  52392. this._isVisibilityBoxLocked = false;
  52393. this._alwaysVisible = false;
  52394. this._depthSort = false;
  52395. this._shapeCounter = 0;
  52396. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52397. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52398. this._computeParticleColor = true;
  52399. this._computeParticleTexture = true;
  52400. this._computeParticleRotation = true;
  52401. this._computeParticleVertex = false;
  52402. this._computeBoundingBox = false;
  52403. this._depthSortParticles = true;
  52404. this._cam_axisZ = BABYLON.Vector3.Zero();
  52405. this._cam_axisY = BABYLON.Vector3.Zero();
  52406. this._cam_axisX = BABYLON.Vector3.Zero();
  52407. this._axisZ = BABYLON.Axis.Z;
  52408. this._camDir = BABYLON.Vector3.Zero();
  52409. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52410. this._rotMatrix = new BABYLON.Matrix();
  52411. this._invertMatrix = new BABYLON.Matrix();
  52412. this._rotated = BABYLON.Vector3.Zero();
  52413. this._quaternion = new BABYLON.Quaternion();
  52414. this._vertex = BABYLON.Vector3.Zero();
  52415. this._normal = BABYLON.Vector3.Zero();
  52416. this._yaw = 0.0;
  52417. this._pitch = 0.0;
  52418. this._roll = 0.0;
  52419. this._halfroll = 0.0;
  52420. this._halfpitch = 0.0;
  52421. this._halfyaw = 0.0;
  52422. this._sinRoll = 0.0;
  52423. this._cosRoll = 0.0;
  52424. this._sinPitch = 0.0;
  52425. this._cosPitch = 0.0;
  52426. this._sinYaw = 0.0;
  52427. this._cosYaw = 0.0;
  52428. this._mustUnrotateFixedNormals = false;
  52429. this._minimum = BABYLON.Vector3.Zero();
  52430. this._maximum = BABYLON.Vector3.Zero();
  52431. this._minBbox = BABYLON.Vector3.Zero();
  52432. this._maxBbox = BABYLON.Vector3.Zero();
  52433. this._particlesIntersect = false;
  52434. this._depthSortFunction = function (p1, p2) {
  52435. return (p2.sqDistance - p1.sqDistance);
  52436. };
  52437. this._needs32Bits = false;
  52438. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52439. this._scaledPivot = BABYLON.Vector3.Zero();
  52440. this._particleHasParent = false;
  52441. this.name = name;
  52442. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52443. this._camera = scene.activeCamera;
  52444. this._pickable = options ? options.isPickable : false;
  52445. this._depthSort = options ? options.enableDepthSort : false;
  52446. this._particlesIntersect = options ? options.particleIntersection : false;
  52447. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52448. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52449. if (options && options.updatable) {
  52450. this._updatable = options.updatable;
  52451. }
  52452. else {
  52453. this._updatable = true;
  52454. }
  52455. if (this._pickable) {
  52456. this.pickedParticles = [];
  52457. }
  52458. if (this._depthSort) {
  52459. this.depthSortedParticles = [];
  52460. }
  52461. }
  52462. /**
  52463. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52464. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52465. * @returns the created mesh
  52466. */
  52467. SolidParticleSystem.prototype.buildMesh = function () {
  52468. if (this.nbParticles === 0) {
  52469. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52470. this.addShape(triangle, 1);
  52471. triangle.dispose();
  52472. }
  52473. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52474. this._positions32 = new Float32Array(this._positions);
  52475. this._uvs32 = new Float32Array(this._uvs);
  52476. this._colors32 = new Float32Array(this._colors);
  52477. if (this.recomputeNormals) {
  52478. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52479. }
  52480. this._normals32 = new Float32Array(this._normals);
  52481. this._fixedNormal32 = new Float32Array(this._normals);
  52482. if (this._mustUnrotateFixedNormals) {
  52483. this._unrotateFixedNormals();
  52484. }
  52485. var vertexData = new BABYLON.VertexData();
  52486. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52487. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52488. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52489. if (this._uvs32) {
  52490. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52491. ;
  52492. }
  52493. if (this._colors32) {
  52494. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52495. }
  52496. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52497. vertexData.applyToMesh(mesh, this._updatable);
  52498. this.mesh = mesh;
  52499. this.mesh.isPickable = this._pickable;
  52500. // free memory
  52501. if (!this._depthSort) {
  52502. this._indices = null;
  52503. }
  52504. this._positions = null;
  52505. this._normals = null;
  52506. this._uvs = null;
  52507. this._colors = null;
  52508. if (!this._updatable) {
  52509. this.particles.length = 0;
  52510. }
  52511. return mesh;
  52512. };
  52513. /**
  52514. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52515. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52516. * Thus the particles generated from `digest()` have their property `position` set yet.
  52517. * @param mesh ( Mesh ) is the mesh to be digested
  52518. * @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
  52519. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52520. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52521. * @returns the current SPS
  52522. */
  52523. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52524. var size = (options && options.facetNb) || 1;
  52525. var number = (options && options.number) || 0;
  52526. var delta = (options && options.delta) || 0;
  52527. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52528. var meshInd = mesh.getIndices();
  52529. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52530. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52531. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52532. var f = 0; // facet counter
  52533. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52534. // compute size from number
  52535. if (number) {
  52536. number = (number > totalFacets) ? totalFacets : number;
  52537. size = Math.round(totalFacets / number);
  52538. delta = 0;
  52539. }
  52540. else {
  52541. size = (size > totalFacets) ? totalFacets : size;
  52542. }
  52543. var facetPos = []; // submesh positions
  52544. var facetInd = []; // submesh indices
  52545. var facetUV = []; // submesh UV
  52546. var facetCol = []; // submesh colors
  52547. var barycenter = BABYLON.Vector3.Zero();
  52548. var sizeO = size;
  52549. while (f < totalFacets) {
  52550. size = sizeO + Math.floor((1 + delta) * Math.random());
  52551. if (f > totalFacets - size) {
  52552. size = totalFacets - f;
  52553. }
  52554. // reset temp arrays
  52555. facetPos.length = 0;
  52556. facetInd.length = 0;
  52557. facetUV.length = 0;
  52558. facetCol.length = 0;
  52559. // iterate over "size" facets
  52560. var fi = 0;
  52561. for (var j = f * 3; j < (f + size) * 3; j++) {
  52562. facetInd.push(fi);
  52563. var i = meshInd[j];
  52564. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52565. if (meshUV) {
  52566. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52567. }
  52568. if (meshCol) {
  52569. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52570. }
  52571. fi++;
  52572. }
  52573. // create a model shape for each single particle
  52574. var idx = this.nbParticles;
  52575. var shape = this._posToShape(facetPos);
  52576. var shapeUV = this._uvsToShapeUV(facetUV);
  52577. // compute the barycenter of the shape
  52578. var v;
  52579. for (v = 0; v < shape.length; v++) {
  52580. barycenter.addInPlace(shape[v]);
  52581. }
  52582. barycenter.scaleInPlace(1 / shape.length);
  52583. // shift the shape from its barycenter to the origin
  52584. for (v = 0; v < shape.length; v++) {
  52585. shape[v].subtractInPlace(barycenter);
  52586. }
  52587. var bInfo;
  52588. if (this._particlesIntersect) {
  52589. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52590. }
  52591. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52592. // add the particle in the SPS
  52593. var currentPos = this._positions.length;
  52594. var currentInd = this._indices.length;
  52595. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52596. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52597. // initialize the particle position
  52598. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52599. this._index += shape.length;
  52600. idx++;
  52601. this.nbParticles++;
  52602. this._shapeCounter++;
  52603. f += size;
  52604. }
  52605. return this;
  52606. };
  52607. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52608. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52609. var index = 0;
  52610. var idx = 0;
  52611. for (var p = 0; p < this.particles.length; p++) {
  52612. this._particle = this.particles[p];
  52613. this._shape = this._particle._model._shape;
  52614. if (this._particle.rotationQuaternion) {
  52615. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52616. }
  52617. else {
  52618. this._yaw = this._particle.rotation.y;
  52619. this._pitch = this._particle.rotation.x;
  52620. this._roll = this._particle.rotation.z;
  52621. this._quaternionRotationYPR();
  52622. }
  52623. this._quaternionToRotationMatrix();
  52624. this._rotMatrix.invertToRef(this._invertMatrix);
  52625. for (var pt = 0; pt < this._shape.length; pt++) {
  52626. idx = index + pt * 3;
  52627. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52628. this._fixedNormal32[idx] = this._normal.x;
  52629. this._fixedNormal32[idx + 1] = this._normal.y;
  52630. this._fixedNormal32[idx + 2] = this._normal.z;
  52631. }
  52632. index = idx + 3;
  52633. }
  52634. };
  52635. //reset copy
  52636. SolidParticleSystem.prototype._resetCopy = function () {
  52637. this._copy.position.x = 0;
  52638. this._copy.position.y = 0;
  52639. this._copy.position.z = 0;
  52640. this._copy.rotation.x = 0;
  52641. this._copy.rotation.y = 0;
  52642. this._copy.rotation.z = 0;
  52643. this._copy.rotationQuaternion = null;
  52644. this._copy.scaling.x = 1.0;
  52645. this._copy.scaling.y = 1.0;
  52646. this._copy.scaling.z = 1.0;
  52647. this._copy.uvs.x = 0;
  52648. this._copy.uvs.y = 0;
  52649. this._copy.uvs.z = 1.0;
  52650. this._copy.uvs.w = 1.0;
  52651. this._copy.color = null;
  52652. this._copy.translateFromPivot = false;
  52653. };
  52654. // _meshBuilder : inserts the shape model in the global SPS mesh
  52655. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52656. var i;
  52657. var u = 0;
  52658. var c = 0;
  52659. var n = 0;
  52660. this._resetCopy();
  52661. if (options && options.positionFunction) {
  52662. options.positionFunction(this._copy, idx, idxInShape);
  52663. this._mustUnrotateFixedNormals = true;
  52664. }
  52665. if (this._copy.rotationQuaternion) {
  52666. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52667. }
  52668. else {
  52669. this._yaw = this._copy.rotation.y;
  52670. this._pitch = this._copy.rotation.x;
  52671. this._roll = this._copy.rotation.z;
  52672. this._quaternionRotationYPR();
  52673. }
  52674. this._quaternionToRotationMatrix();
  52675. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52676. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52677. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52678. if (this._copy.translateFromPivot) {
  52679. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52680. }
  52681. else {
  52682. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52683. }
  52684. for (i = 0; i < shape.length; i++) {
  52685. this._vertex.x = shape[i].x;
  52686. this._vertex.y = shape[i].y;
  52687. this._vertex.z = shape[i].z;
  52688. if (options && options.vertexFunction) {
  52689. options.vertexFunction(this._copy, this._vertex, i);
  52690. }
  52691. this._vertex.x *= this._copy.scaling.x;
  52692. this._vertex.y *= this._copy.scaling.y;
  52693. this._vertex.z *= this._copy.scaling.z;
  52694. this._vertex.x -= this._scaledPivot.x;
  52695. this._vertex.y -= this._scaledPivot.y;
  52696. this._vertex.z -= this._scaledPivot.z;
  52697. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52698. this._rotated.addInPlace(this._pivotBackTranslation);
  52699. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52700. if (meshUV) {
  52701. 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);
  52702. u += 2;
  52703. }
  52704. if (this._copy.color) {
  52705. this._color = this._copy.color;
  52706. }
  52707. else if (meshCol && meshCol[c] !== undefined) {
  52708. this._color.r = meshCol[c];
  52709. this._color.g = meshCol[c + 1];
  52710. this._color.b = meshCol[c + 2];
  52711. this._color.a = meshCol[c + 3];
  52712. }
  52713. else {
  52714. this._color.r = 1.0;
  52715. this._color.g = 1.0;
  52716. this._color.b = 1.0;
  52717. this._color.a = 1.0;
  52718. }
  52719. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52720. c += 4;
  52721. if (!this.recomputeNormals && meshNor) {
  52722. this._normal.x = meshNor[n];
  52723. this._normal.y = meshNor[n + 1];
  52724. this._normal.z = meshNor[n + 2];
  52725. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52726. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52727. n += 3;
  52728. }
  52729. }
  52730. for (i = 0; i < meshInd.length; i++) {
  52731. var current_ind = p + meshInd[i];
  52732. indices.push(current_ind);
  52733. if (current_ind > 65535) {
  52734. this._needs32Bits = true;
  52735. }
  52736. }
  52737. if (this._pickable) {
  52738. var nbfaces = meshInd.length / 3;
  52739. for (i = 0; i < nbfaces; i++) {
  52740. this.pickedParticles.push({ idx: idx, faceId: i });
  52741. }
  52742. }
  52743. if (this._depthSort) {
  52744. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52745. }
  52746. return this._copy;
  52747. };
  52748. // returns a shape array from positions array
  52749. SolidParticleSystem.prototype._posToShape = function (positions) {
  52750. var shape = [];
  52751. for (var i = 0; i < positions.length; i += 3) {
  52752. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52753. }
  52754. return shape;
  52755. };
  52756. // returns a shapeUV array from a Vector4 uvs
  52757. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52758. var shapeUV = [];
  52759. if (uvs) {
  52760. for (var i = 0; i < uvs.length; i++)
  52761. shapeUV.push(uvs[i]);
  52762. }
  52763. return shapeUV;
  52764. };
  52765. // adds a new particle object in the particles array
  52766. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52767. if (bInfo === void 0) { bInfo = null; }
  52768. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52769. this.particles.push(sp);
  52770. return sp;
  52771. };
  52772. /**
  52773. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52774. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52775. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52776. * @param nb (positive integer) the number of particles to be created from this model
  52777. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52778. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52779. * @returns the number of shapes in the system
  52780. */
  52781. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52782. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52783. var meshInd = mesh.getIndices();
  52784. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52785. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52786. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52787. var bbInfo;
  52788. if (this._particlesIntersect) {
  52789. bbInfo = mesh.getBoundingInfo();
  52790. }
  52791. var shape = this._posToShape(meshPos);
  52792. var shapeUV = this._uvsToShapeUV(meshUV);
  52793. var posfunc = options ? options.positionFunction : null;
  52794. var vtxfunc = options ? options.vertexFunction : null;
  52795. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52796. // particles
  52797. var sp;
  52798. var currentCopy;
  52799. var idx = this.nbParticles;
  52800. for (var i = 0; i < nb; i++) {
  52801. var currentPos = this._positions.length;
  52802. var currentInd = this._indices.length;
  52803. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52804. if (this._updatable) {
  52805. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52806. sp.position.copyFrom(currentCopy.position);
  52807. sp.rotation.copyFrom(currentCopy.rotation);
  52808. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52809. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52810. }
  52811. if (currentCopy.color && sp.color) {
  52812. sp.color.copyFrom(currentCopy.color);
  52813. }
  52814. sp.scaling.copyFrom(currentCopy.scaling);
  52815. sp.uvs.copyFrom(currentCopy.uvs);
  52816. }
  52817. this._index += shape.length;
  52818. idx++;
  52819. }
  52820. this.nbParticles += nb;
  52821. this._shapeCounter++;
  52822. return this._shapeCounter - 1;
  52823. };
  52824. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52825. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52826. this._resetCopy();
  52827. if (particle._model._positionFunction) {
  52828. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52829. }
  52830. if (this._copy.rotationQuaternion) {
  52831. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52832. }
  52833. else {
  52834. this._yaw = this._copy.rotation.y;
  52835. this._pitch = this._copy.rotation.x;
  52836. this._roll = this._copy.rotation.z;
  52837. this._quaternionRotationYPR();
  52838. }
  52839. this._quaternionToRotationMatrix();
  52840. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52841. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52842. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52843. if (this._copy.translateFromPivot) {
  52844. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52845. }
  52846. else {
  52847. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52848. }
  52849. this._shape = particle._model._shape;
  52850. for (var pt = 0; pt < this._shape.length; pt++) {
  52851. this._vertex.x = this._shape[pt].x;
  52852. this._vertex.y = this._shape[pt].y;
  52853. this._vertex.z = this._shape[pt].z;
  52854. if (particle._model._vertexFunction) {
  52855. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52856. }
  52857. this._vertex.x *= this._copy.scaling.x;
  52858. this._vertex.y *= this._copy.scaling.y;
  52859. this._vertex.z *= this._copy.scaling.z;
  52860. this._vertex.x -= this._scaledPivot.x;
  52861. this._vertex.y -= this._scaledPivot.y;
  52862. this._vertex.z -= this._scaledPivot.z;
  52863. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52864. this._rotated.addInPlace(this._pivotBackTranslation);
  52865. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52866. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52867. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52868. }
  52869. particle.position.x = 0.0;
  52870. particle.position.y = 0.0;
  52871. particle.position.z = 0.0;
  52872. particle.rotation.x = 0.0;
  52873. particle.rotation.y = 0.0;
  52874. particle.rotation.z = 0.0;
  52875. particle.rotationQuaternion = null;
  52876. particle.scaling.x = 1.0;
  52877. particle.scaling.y = 1.0;
  52878. particle.scaling.z = 1.0;
  52879. particle.uvs.x = 0.0;
  52880. particle.uvs.y = 0.0;
  52881. particle.uvs.z = 1.0;
  52882. particle.uvs.w = 1.0;
  52883. particle.pivot.x = 0.0;
  52884. particle.pivot.y = 0.0;
  52885. particle.pivot.z = 0.0;
  52886. particle.translateFromPivot = false;
  52887. particle.parentId = null;
  52888. };
  52889. /**
  52890. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52891. * @returns the SPS.
  52892. */
  52893. SolidParticleSystem.prototype.rebuildMesh = function () {
  52894. for (var p = 0; p < this.particles.length; p++) {
  52895. this._rebuildParticle(this.particles[p]);
  52896. }
  52897. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52898. return this;
  52899. };
  52900. /**
  52901. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52902. * This method calls `updateParticle()` for each particle of the SPS.
  52903. * For an animated SPS, it is usually called within the render loop.
  52904. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52905. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52906. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52907. * @returns the SPS.
  52908. */
  52909. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52910. if (start === void 0) { start = 0; }
  52911. if (end === void 0) { end = this.nbParticles - 1; }
  52912. if (update === void 0) { update = true; }
  52913. if (!this._updatable) {
  52914. return this;
  52915. }
  52916. // custom beforeUpdate
  52917. this.beforeUpdateParticles(start, end, update);
  52918. this._cam_axisX.x = 1.0;
  52919. this._cam_axisX.y = 0.0;
  52920. this._cam_axisX.z = 0.0;
  52921. this._cam_axisY.x = 0.0;
  52922. this._cam_axisY.y = 1.0;
  52923. this._cam_axisY.z = 0.0;
  52924. this._cam_axisZ.x = 0.0;
  52925. this._cam_axisZ.y = 0.0;
  52926. this._cam_axisZ.z = 1.0;
  52927. // cases when the World Matrix is to be computed first
  52928. if (this.billboard || this._depthSort) {
  52929. this.mesh.computeWorldMatrix(true);
  52930. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52931. }
  52932. // if the particles will always face the camera
  52933. if (this.billboard) {
  52934. // compute the camera position and un-rotate it by the current mesh rotation
  52935. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52936. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52937. this._cam_axisZ.normalize();
  52938. // same for camera up vector extracted from the cam view matrix
  52939. var view = this._camera.getViewMatrix(true);
  52940. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52941. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52942. this._cam_axisY.normalize();
  52943. this._cam_axisX.normalize();
  52944. }
  52945. // if depthSort, compute the camera global position in the mesh local system
  52946. if (this._depthSort) {
  52947. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52948. }
  52949. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52950. var idx = 0; // current position index in the global array positions32
  52951. var index = 0; // position start index in the global array positions32 of the current particle
  52952. var colidx = 0; // current color index in the global array colors32
  52953. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52954. var uvidx = 0; // current uv index in the global array uvs32
  52955. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52956. var pt = 0; // current index in the particle model shape
  52957. if (this.mesh.isFacetDataEnabled) {
  52958. this._computeBoundingBox = true;
  52959. }
  52960. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52961. if (this._computeBoundingBox) {
  52962. if (start == 0 && end == this.nbParticles - 1) {
  52963. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52964. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52965. }
  52966. else {
  52967. if (this.mesh._boundingInfo) {
  52968. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52969. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52970. }
  52971. }
  52972. }
  52973. // particle loop
  52974. index = this.particles[start]._pos;
  52975. var vpos = (index / 3) | 0;
  52976. colorIndex = vpos * 4;
  52977. uvIndex = vpos * 2;
  52978. for (var p = start; p <= end; p++) {
  52979. this._particle = this.particles[p];
  52980. this._shape = this._particle._model._shape;
  52981. this._shapeUV = this._particle._model._shapeUV;
  52982. // call to custom user function to update the particle properties
  52983. this.updateParticle(this._particle);
  52984. // camera-particle distance for depth sorting
  52985. if (this._depthSort && this._depthSortParticles) {
  52986. var dsp = this.depthSortedParticles[p];
  52987. dsp.ind = this._particle._ind;
  52988. dsp.indicesLength = this._particle._model._indicesLength;
  52989. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52990. }
  52991. // skip the computations for inactive or already invisible particles
  52992. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52993. // increment indexes for the next particle
  52994. pt = this._shape.length;
  52995. index += pt * 3;
  52996. colorIndex += pt * 4;
  52997. uvIndex += pt * 2;
  52998. continue;
  52999. }
  53000. if (this._particle.isVisible) {
  53001. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53002. this._particleHasParent = (this._particle.parentId !== null);
  53003. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53004. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53005. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53006. // particle rotation matrix
  53007. if (this.billboard) {
  53008. this._particle.rotation.x = 0.0;
  53009. this._particle.rotation.y = 0.0;
  53010. }
  53011. if (this._computeParticleRotation || this.billboard) {
  53012. if (this._particle.rotationQuaternion) {
  53013. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53014. }
  53015. else {
  53016. this._yaw = this._particle.rotation.y;
  53017. this._pitch = this._particle.rotation.x;
  53018. this._roll = this._particle.rotation.z;
  53019. this._quaternionRotationYPR();
  53020. }
  53021. this._quaternionToRotationMatrix();
  53022. }
  53023. if (this._particleHasParent) {
  53024. this._parent = this.particles[this._particle.parentId];
  53025. 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];
  53026. 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];
  53027. 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];
  53028. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53029. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53030. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53031. if (this._computeParticleRotation || this.billboard) {
  53032. 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];
  53033. 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];
  53034. 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];
  53035. 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];
  53036. 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];
  53037. 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];
  53038. 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];
  53039. 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];
  53040. 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];
  53041. }
  53042. }
  53043. else {
  53044. this._particle._globalPosition.x = this._particle.position.x;
  53045. this._particle._globalPosition.y = this._particle.position.y;
  53046. this._particle._globalPosition.z = this._particle.position.z;
  53047. if (this._computeParticleRotation || this.billboard) {
  53048. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53049. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53050. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53051. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53052. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53053. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53054. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53055. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53056. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53057. }
  53058. }
  53059. if (this._particle.translateFromPivot) {
  53060. this._pivotBackTranslation.x = 0.0;
  53061. this._pivotBackTranslation.y = 0.0;
  53062. this._pivotBackTranslation.z = 0.0;
  53063. }
  53064. else {
  53065. this._pivotBackTranslation.x = this._scaledPivot.x;
  53066. this._pivotBackTranslation.y = this._scaledPivot.y;
  53067. this._pivotBackTranslation.z = this._scaledPivot.z;
  53068. }
  53069. // particle vertex loop
  53070. for (pt = 0; pt < this._shape.length; pt++) {
  53071. idx = index + pt * 3;
  53072. colidx = colorIndex + pt * 4;
  53073. uvidx = uvIndex + pt * 2;
  53074. this._vertex.x = this._shape[pt].x;
  53075. this._vertex.y = this._shape[pt].y;
  53076. this._vertex.z = this._shape[pt].z;
  53077. if (this._computeParticleVertex) {
  53078. this.updateParticleVertex(this._particle, this._vertex, pt);
  53079. }
  53080. // positions
  53081. this._vertex.x *= this._particle.scaling.x;
  53082. this._vertex.y *= this._particle.scaling.y;
  53083. this._vertex.z *= this._particle.scaling.z;
  53084. this._vertex.x -= this._scaledPivot.x;
  53085. this._vertex.y -= this._scaledPivot.y;
  53086. this._vertex.z -= this._scaledPivot.z;
  53087. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53088. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53089. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53090. this._rotated.x += this._pivotBackTranslation.x;
  53091. this._rotated.y += this._pivotBackTranslation.y;
  53092. this._rotated.z += this._pivotBackTranslation.z;
  53093. 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;
  53094. 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;
  53095. 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;
  53096. if (this._computeBoundingBox) {
  53097. if (this._positions32[idx] < this._minimum.x) {
  53098. this._minimum.x = this._positions32[idx];
  53099. }
  53100. if (this._positions32[idx] > this._maximum.x) {
  53101. this._maximum.x = this._positions32[idx];
  53102. }
  53103. if (this._positions32[idx + 1] < this._minimum.y) {
  53104. this._minimum.y = this._positions32[idx + 1];
  53105. }
  53106. if (this._positions32[idx + 1] > this._maximum.y) {
  53107. this._maximum.y = this._positions32[idx + 1];
  53108. }
  53109. if (this._positions32[idx + 2] < this._minimum.z) {
  53110. this._minimum.z = this._positions32[idx + 2];
  53111. }
  53112. if (this._positions32[idx + 2] > this._maximum.z) {
  53113. this._maximum.z = this._positions32[idx + 2];
  53114. }
  53115. }
  53116. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53117. if (!this._computeParticleVertex) {
  53118. this._normal.x = this._fixedNormal32[idx];
  53119. this._normal.y = this._fixedNormal32[idx + 1];
  53120. this._normal.z = this._fixedNormal32[idx + 2];
  53121. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53122. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53123. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53124. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53125. 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;
  53126. 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;
  53127. }
  53128. if (this._computeParticleColor && this._particle.color) {
  53129. this._colors32[colidx] = this._particle.color.r;
  53130. this._colors32[colidx + 1] = this._particle.color.g;
  53131. this._colors32[colidx + 2] = this._particle.color.b;
  53132. this._colors32[colidx + 3] = this._particle.color.a;
  53133. }
  53134. if (this._computeParticleTexture) {
  53135. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53136. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53137. }
  53138. }
  53139. }
  53140. else {
  53141. this._particle._stillInvisible = true; // mark the particle as invisible
  53142. for (pt = 0; pt < this._shape.length; pt++) {
  53143. idx = index + pt * 3;
  53144. colidx = colorIndex + pt * 4;
  53145. uvidx = uvIndex + pt * 2;
  53146. this._positions32[idx] = 0.0;
  53147. this._positions32[idx + 1] = 0.0;
  53148. this._positions32[idx + 2] = 0.0;
  53149. this._normals32[idx] = 0.0;
  53150. this._normals32[idx + 1] = 0.0;
  53151. this._normals32[idx + 2] = 0.0;
  53152. if (this._computeParticleColor && this._particle.color) {
  53153. this._colors32[colidx] = this._particle.color.r;
  53154. this._colors32[colidx + 1] = this._particle.color.g;
  53155. this._colors32[colidx + 2] = this._particle.color.b;
  53156. this._colors32[colidx + 3] = this._particle.color.a;
  53157. }
  53158. if (this._computeParticleTexture) {
  53159. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53160. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53161. }
  53162. }
  53163. }
  53164. // if the particle intersections must be computed : update the bbInfo
  53165. if (this._particlesIntersect) {
  53166. var bInfo = this._particle._boundingInfo;
  53167. var bBox = bInfo.boundingBox;
  53168. var bSphere = bInfo.boundingSphere;
  53169. if (!this._bSphereOnly) {
  53170. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53171. for (var b = 0; b < bBox.vectors.length; b++) {
  53172. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53173. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53174. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53175. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53176. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53177. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53178. 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;
  53179. 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;
  53180. 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;
  53181. }
  53182. bBox._update(this.mesh._worldMatrix);
  53183. }
  53184. // place and scale the particle bouding sphere in the SPS local system, then update it
  53185. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53186. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53187. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53188. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53189. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53190. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53191. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53192. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53193. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53194. 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));
  53195. bSphere._update(this.mesh._worldMatrix);
  53196. }
  53197. // increment indexes for the next particle
  53198. index = idx + 3;
  53199. colorIndex = colidx + 4;
  53200. uvIndex = uvidx + 2;
  53201. }
  53202. // if the VBO must be updated
  53203. if (update) {
  53204. if (this._computeParticleColor) {
  53205. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53206. }
  53207. if (this._computeParticleTexture) {
  53208. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53209. }
  53210. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53211. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53212. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53213. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53214. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53215. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53216. for (var i = 0; i < this._normals32.length; i++) {
  53217. this._fixedNormal32[i] = this._normals32[i];
  53218. }
  53219. }
  53220. if (!this.mesh.areNormalsFrozen) {
  53221. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53222. }
  53223. }
  53224. if (this._depthSort && this._depthSortParticles) {
  53225. this.depthSortedParticles.sort(this._depthSortFunction);
  53226. var dspl = this.depthSortedParticles.length;
  53227. var sorted = 0;
  53228. var lind = 0;
  53229. var sind = 0;
  53230. var sid = 0;
  53231. for (sorted = 0; sorted < dspl; sorted++) {
  53232. lind = this.depthSortedParticles[sorted].indicesLength;
  53233. sind = this.depthSortedParticles[sorted].ind;
  53234. for (var i = 0; i < lind; i++) {
  53235. this._indices32[sid] = this._indices[sind + i];
  53236. sid++;
  53237. }
  53238. }
  53239. this.mesh.updateIndices(this._indices32);
  53240. }
  53241. }
  53242. if (this._computeBoundingBox) {
  53243. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53244. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53245. }
  53246. this.afterUpdateParticles(start, end, update);
  53247. return this;
  53248. };
  53249. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53250. this._halfroll = this._roll * 0.5;
  53251. this._halfpitch = this._pitch * 0.5;
  53252. this._halfyaw = this._yaw * 0.5;
  53253. this._sinRoll = Math.sin(this._halfroll);
  53254. this._cosRoll = Math.cos(this._halfroll);
  53255. this._sinPitch = Math.sin(this._halfpitch);
  53256. this._cosPitch = Math.cos(this._halfpitch);
  53257. this._sinYaw = Math.sin(this._halfyaw);
  53258. this._cosYaw = Math.cos(this._halfyaw);
  53259. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53260. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53261. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53262. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53263. };
  53264. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53265. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53266. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53267. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53268. this._rotMatrix.m[3] = 0;
  53269. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53270. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53271. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53272. this._rotMatrix.m[7] = 0;
  53273. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53274. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53275. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53276. this._rotMatrix.m[11] = 0;
  53277. this._rotMatrix.m[12] = 0;
  53278. this._rotMatrix.m[13] = 0;
  53279. this._rotMatrix.m[14] = 0;
  53280. this._rotMatrix.m[15] = 1.0;
  53281. };
  53282. /**
  53283. * Disposes the SPS.
  53284. */
  53285. SolidParticleSystem.prototype.dispose = function () {
  53286. this.mesh.dispose();
  53287. this.vars = null;
  53288. // drop references to internal big arrays for the GC
  53289. this._positions = null;
  53290. this._indices = null;
  53291. this._normals = null;
  53292. this._uvs = null;
  53293. this._colors = null;
  53294. this._indices32 = null;
  53295. this._positions32 = null;
  53296. this._normals32 = null;
  53297. this._fixedNormal32 = null;
  53298. this._uvs32 = null;
  53299. this._colors32 = null;
  53300. this.pickedParticles = null;
  53301. };
  53302. /**
  53303. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53304. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53305. * @returns the SPS.
  53306. */
  53307. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53308. if (!this._isVisibilityBoxLocked) {
  53309. this.mesh.refreshBoundingInfo();
  53310. }
  53311. return this;
  53312. };
  53313. /**
  53314. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53315. * @param size the size (float) of the visibility box
  53316. * note : this doesn't lock the SPS mesh bounding box.
  53317. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53318. */
  53319. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53320. var vis = size / 2;
  53321. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53322. };
  53323. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53324. /**
  53325. * Gets whether the SPS as always visible or not
  53326. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53327. */
  53328. get: function () {
  53329. return this._alwaysVisible;
  53330. },
  53331. /**
  53332. * Sets the SPS as always visible or not
  53333. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53334. */
  53335. set: function (val) {
  53336. this._alwaysVisible = val;
  53337. this.mesh.alwaysSelectAsActiveMesh = val;
  53338. },
  53339. enumerable: true,
  53340. configurable: true
  53341. });
  53342. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53343. /**
  53344. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53345. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53346. */
  53347. get: function () {
  53348. return this._isVisibilityBoxLocked;
  53349. },
  53350. /**
  53351. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53352. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53353. */
  53354. set: function (val) {
  53355. this._isVisibilityBoxLocked = val;
  53356. var boundingInfo = this.mesh.getBoundingInfo();
  53357. boundingInfo.isLocked = val;
  53358. },
  53359. enumerable: true,
  53360. configurable: true
  53361. });
  53362. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53363. /**
  53364. * Gets if `setParticles()` computes the particle rotations or not.
  53365. * Default value : true. The SPS is faster when it's set to false.
  53366. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53367. */
  53368. get: function () {
  53369. return this._computeParticleRotation;
  53370. },
  53371. /**
  53372. * Tells to `setParticles()` to compute the particle rotations or not.
  53373. * Default value : true. The SPS is faster when it's set to false.
  53374. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53375. */
  53376. set: function (val) {
  53377. this._computeParticleRotation = val;
  53378. },
  53379. enumerable: true,
  53380. configurable: true
  53381. });
  53382. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53383. /**
  53384. * Gets if `setParticles()` computes the particle colors or not.
  53385. * Default value : true. The SPS is faster when it's set to false.
  53386. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53387. */
  53388. get: function () {
  53389. return this._computeParticleColor;
  53390. },
  53391. /**
  53392. * Tells to `setParticles()` to compute the particle colors or not.
  53393. * Default value : true. The SPS is faster when it's set to false.
  53394. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53395. */
  53396. set: function (val) {
  53397. this._computeParticleColor = val;
  53398. },
  53399. enumerable: true,
  53400. configurable: true
  53401. });
  53402. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53403. /**
  53404. * Gets if `setParticles()` computes the particle textures or not.
  53405. * Default value : true. The SPS is faster when it's set to false.
  53406. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53407. */
  53408. get: function () {
  53409. return this._computeParticleTexture;
  53410. },
  53411. set: function (val) {
  53412. this._computeParticleTexture = val;
  53413. },
  53414. enumerable: true,
  53415. configurable: true
  53416. });
  53417. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53418. /**
  53419. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53420. * Default value : false. The SPS is faster when it's set to false.
  53421. * Note : the particle custom vertex positions aren't stored values.
  53422. */
  53423. get: function () {
  53424. return this._computeParticleVertex;
  53425. },
  53426. /**
  53427. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53428. * Default value : false. The SPS is faster when it's set to false.
  53429. * Note : the particle custom vertex positions aren't stored values.
  53430. */
  53431. set: function (val) {
  53432. this._computeParticleVertex = val;
  53433. },
  53434. enumerable: true,
  53435. configurable: true
  53436. });
  53437. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53438. /**
  53439. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53440. */
  53441. get: function () {
  53442. return this._computeBoundingBox;
  53443. },
  53444. /**
  53445. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53446. */
  53447. set: function (val) {
  53448. this._computeBoundingBox = val;
  53449. },
  53450. enumerable: true,
  53451. configurable: true
  53452. });
  53453. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53454. /**
  53455. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53456. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53457. * Default : `true`
  53458. */
  53459. get: function () {
  53460. return this._depthSortParticles;
  53461. },
  53462. /**
  53463. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53464. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53465. * Default : `true`
  53466. */
  53467. set: function (val) {
  53468. this._depthSortParticles = val;
  53469. },
  53470. enumerable: true,
  53471. configurable: true
  53472. });
  53473. // =======================================================================
  53474. // Particle behavior logic
  53475. // these following methods may be overwritten by the user to fit his needs
  53476. /**
  53477. * This function does nothing. It may be overwritten to set all the particle first values.
  53478. * The SPS doesn't call this function, you may have to call it by your own.
  53479. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53480. */
  53481. SolidParticleSystem.prototype.initParticles = function () {
  53482. };
  53483. /**
  53484. * This function does nothing. It may be overwritten to recycle a particle.
  53485. * The SPS doesn't call this function, you may have to call it by your own.
  53486. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53487. * @param particle The particle to recycle
  53488. * @returns the recycled particle
  53489. */
  53490. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53491. return particle;
  53492. };
  53493. /**
  53494. * Updates a particle : this function should be overwritten by the user.
  53495. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53496. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53497. * @example : just set a particle position or velocity and recycle conditions
  53498. * @param particle The particle to update
  53499. * @returns the updated particle
  53500. */
  53501. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53502. return particle;
  53503. };
  53504. /**
  53505. * Updates a vertex of a particle : it can be overwritten by the user.
  53506. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53507. * @param particle the current particle
  53508. * @param vertex the current index of the current particle
  53509. * @param pt the index of the current vertex in the particle shape
  53510. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53511. * @example : just set a vertex particle position
  53512. * @returns the updated vertex
  53513. */
  53514. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53515. return vertex;
  53516. };
  53517. /**
  53518. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53519. * This does nothing and may be overwritten by the user.
  53520. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53521. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53522. * @param update the boolean update value actually passed to setParticles()
  53523. */
  53524. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53525. };
  53526. /**
  53527. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53528. * This will be passed three parameters.
  53529. * This does nothing and may be overwritten by the user.
  53530. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53531. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53532. * @param update the boolean update value actually passed to setParticles()
  53533. */
  53534. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53535. };
  53536. return SolidParticleSystem;
  53537. }());
  53538. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53539. })(BABYLON || (BABYLON = {}));
  53540. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53541. var BABYLON;
  53542. (function (BABYLON) {
  53543. var ShaderMaterial = /** @class */ (function (_super) {
  53544. __extends(ShaderMaterial, _super);
  53545. function ShaderMaterial(name, scene, shaderPath, options) {
  53546. var _this = _super.call(this, name, scene) || this;
  53547. _this._textures = {};
  53548. _this._textureArrays = {};
  53549. _this._floats = {};
  53550. _this._ints = {};
  53551. _this._floatsArrays = {};
  53552. _this._colors3 = {};
  53553. _this._colors3Arrays = {};
  53554. _this._colors4 = {};
  53555. _this._vectors2 = {};
  53556. _this._vectors3 = {};
  53557. _this._vectors4 = {};
  53558. _this._matrices = {};
  53559. _this._matrices3x3 = {};
  53560. _this._matrices2x2 = {};
  53561. _this._vectors2Arrays = {};
  53562. _this._vectors3Arrays = {};
  53563. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53564. _this._shaderPath = shaderPath;
  53565. options.needAlphaBlending = options.needAlphaBlending || false;
  53566. options.needAlphaTesting = options.needAlphaTesting || false;
  53567. options.attributes = options.attributes || ["position", "normal", "uv"];
  53568. options.uniforms = options.uniforms || ["worldViewProjection"];
  53569. options.uniformBuffers = options.uniformBuffers || [];
  53570. options.samplers = options.samplers || [];
  53571. options.defines = options.defines || [];
  53572. _this._options = options;
  53573. return _this;
  53574. }
  53575. ShaderMaterial.prototype.getClassName = function () {
  53576. return "ShaderMaterial";
  53577. };
  53578. ShaderMaterial.prototype.needAlphaBlending = function () {
  53579. return this._options.needAlphaBlending;
  53580. };
  53581. ShaderMaterial.prototype.needAlphaTesting = function () {
  53582. return this._options.needAlphaTesting;
  53583. };
  53584. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53585. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53586. this._options.uniforms.push(uniformName);
  53587. }
  53588. };
  53589. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53590. if (this._options.samplers.indexOf(name) === -1) {
  53591. this._options.samplers.push(name);
  53592. }
  53593. this._textures[name] = texture;
  53594. return this;
  53595. };
  53596. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53597. if (this._options.samplers.indexOf(name) === -1) {
  53598. this._options.samplers.push(name);
  53599. }
  53600. this._checkUniform(name);
  53601. this._textureArrays[name] = textures;
  53602. return this;
  53603. };
  53604. ShaderMaterial.prototype.setFloat = function (name, value) {
  53605. this._checkUniform(name);
  53606. this._floats[name] = value;
  53607. return this;
  53608. };
  53609. ShaderMaterial.prototype.setInt = function (name, value) {
  53610. this._checkUniform(name);
  53611. this._ints[name] = value;
  53612. return this;
  53613. };
  53614. ShaderMaterial.prototype.setFloats = function (name, value) {
  53615. this._checkUniform(name);
  53616. this._floatsArrays[name] = value;
  53617. return this;
  53618. };
  53619. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53620. this._checkUniform(name);
  53621. this._colors3[name] = value;
  53622. return this;
  53623. };
  53624. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53625. this._checkUniform(name);
  53626. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53627. color.toArray(arr, arr.length);
  53628. return arr;
  53629. }, []);
  53630. return this;
  53631. };
  53632. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53633. this._checkUniform(name);
  53634. this._colors4[name] = value;
  53635. return this;
  53636. };
  53637. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53638. this._checkUniform(name);
  53639. this._vectors2[name] = value;
  53640. return this;
  53641. };
  53642. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53643. this._checkUniform(name);
  53644. this._vectors3[name] = value;
  53645. return this;
  53646. };
  53647. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53648. this._checkUniform(name);
  53649. this._vectors4[name] = value;
  53650. return this;
  53651. };
  53652. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53653. this._checkUniform(name);
  53654. this._matrices[name] = value;
  53655. return this;
  53656. };
  53657. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53658. this._checkUniform(name);
  53659. this._matrices3x3[name] = value;
  53660. return this;
  53661. };
  53662. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53663. this._checkUniform(name);
  53664. this._matrices2x2[name] = value;
  53665. return this;
  53666. };
  53667. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53668. this._checkUniform(name);
  53669. this._vectors2Arrays[name] = value;
  53670. return this;
  53671. };
  53672. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53673. this._checkUniform(name);
  53674. this._vectors3Arrays[name] = value;
  53675. return this;
  53676. };
  53677. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53678. if (!mesh) {
  53679. return true;
  53680. }
  53681. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53682. return false;
  53683. }
  53684. return false;
  53685. };
  53686. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53687. var scene = this.getScene();
  53688. var engine = scene.getEngine();
  53689. if (!this.checkReadyOnEveryCall) {
  53690. if (this._renderId === scene.getRenderId()) {
  53691. if (this._checkCache(scene, mesh, useInstances)) {
  53692. return true;
  53693. }
  53694. }
  53695. }
  53696. // Instances
  53697. var defines = [];
  53698. var attribs = [];
  53699. var fallbacks = new BABYLON.EffectFallbacks();
  53700. if (useInstances) {
  53701. defines.push("#define INSTANCES");
  53702. }
  53703. for (var index = 0; index < this._options.defines.length; index++) {
  53704. defines.push(this._options.defines[index]);
  53705. }
  53706. for (var index = 0; index < this._options.attributes.length; index++) {
  53707. attribs.push(this._options.attributes[index]);
  53708. }
  53709. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53710. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53711. defines.push("#define VERTEXCOLOR");
  53712. }
  53713. // Bones
  53714. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53717. if (mesh.numBoneInfluencers > 4) {
  53718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53720. }
  53721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53723. fallbacks.addCPUSkinningFallback(0, mesh);
  53724. if (this._options.uniforms.indexOf("mBones") === -1) {
  53725. this._options.uniforms.push("mBones");
  53726. }
  53727. }
  53728. else {
  53729. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53730. }
  53731. // Textures
  53732. for (var name in this._textures) {
  53733. if (!this._textures[name].isReady()) {
  53734. return false;
  53735. }
  53736. }
  53737. // Alpha test
  53738. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53739. defines.push("#define ALPHATEST");
  53740. }
  53741. var previousEffect = this._effect;
  53742. var join = defines.join("\n");
  53743. this._effect = engine.createEffect(this._shaderPath, {
  53744. attributes: attribs,
  53745. uniformsNames: this._options.uniforms,
  53746. uniformBuffersNames: this._options.uniformBuffers,
  53747. samplers: this._options.samplers,
  53748. defines: join,
  53749. fallbacks: fallbacks,
  53750. onCompiled: this.onCompiled,
  53751. onError: this.onError
  53752. }, engine);
  53753. if (!this._effect.isReady()) {
  53754. return false;
  53755. }
  53756. if (previousEffect !== this._effect) {
  53757. scene.resetCachedMaterial();
  53758. }
  53759. this._renderId = scene.getRenderId();
  53760. return true;
  53761. };
  53762. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53763. var scene = this.getScene();
  53764. if (!this._effect) {
  53765. return;
  53766. }
  53767. if (this._options.uniforms.indexOf("world") !== -1) {
  53768. this._effect.setMatrix("world", world);
  53769. }
  53770. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53771. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53772. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53773. }
  53774. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53775. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53776. }
  53777. };
  53778. ShaderMaterial.prototype.bind = function (world, mesh) {
  53779. // Std values
  53780. this.bindOnlyWorldMatrix(world);
  53781. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53782. if (this._options.uniforms.indexOf("view") !== -1) {
  53783. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53784. }
  53785. if (this._options.uniforms.indexOf("projection") !== -1) {
  53786. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53787. }
  53788. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53789. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53790. }
  53791. // Bones
  53792. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53793. var name;
  53794. // Texture
  53795. for (name in this._textures) {
  53796. this._effect.setTexture(name, this._textures[name]);
  53797. }
  53798. // Texture arrays
  53799. for (name in this._textureArrays) {
  53800. this._effect.setTextureArray(name, this._textureArrays[name]);
  53801. }
  53802. // Int
  53803. for (name in this._ints) {
  53804. this._effect.setInt(name, this._ints[name]);
  53805. }
  53806. // Float
  53807. for (name in this._floats) {
  53808. this._effect.setFloat(name, this._floats[name]);
  53809. }
  53810. // Floats
  53811. for (name in this._floatsArrays) {
  53812. this._effect.setArray(name, this._floatsArrays[name]);
  53813. }
  53814. // Color3
  53815. for (name in this._colors3) {
  53816. this._effect.setColor3(name, this._colors3[name]);
  53817. }
  53818. for (name in this._colors3Arrays) {
  53819. this._effect.setArray3(name, this._colors3Arrays[name]);
  53820. }
  53821. // Color4
  53822. for (name in this._colors4) {
  53823. var color = this._colors4[name];
  53824. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53825. }
  53826. // Vector2
  53827. for (name in this._vectors2) {
  53828. this._effect.setVector2(name, this._vectors2[name]);
  53829. }
  53830. // Vector3
  53831. for (name in this._vectors3) {
  53832. this._effect.setVector3(name, this._vectors3[name]);
  53833. }
  53834. // Vector4
  53835. for (name in this._vectors4) {
  53836. this._effect.setVector4(name, this._vectors4[name]);
  53837. }
  53838. // Matrix
  53839. for (name in this._matrices) {
  53840. this._effect.setMatrix(name, this._matrices[name]);
  53841. }
  53842. // Matrix 3x3
  53843. for (name in this._matrices3x3) {
  53844. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53845. }
  53846. // Matrix 2x2
  53847. for (name in this._matrices2x2) {
  53848. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53849. }
  53850. // Vector2Array
  53851. for (name in this._vectors2Arrays) {
  53852. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53853. }
  53854. // Vector3Array
  53855. for (name in this._vectors3Arrays) {
  53856. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53857. }
  53858. }
  53859. this._afterBind(mesh);
  53860. };
  53861. ShaderMaterial.prototype.getActiveTextures = function () {
  53862. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53863. for (var name in this._textures) {
  53864. activeTextures.push(this._textures[name]);
  53865. }
  53866. for (var name in this._textureArrays) {
  53867. var array = this._textureArrays[name];
  53868. for (var index = 0; index < array.length; index++) {
  53869. activeTextures.push(array[index]);
  53870. }
  53871. }
  53872. return activeTextures;
  53873. };
  53874. ShaderMaterial.prototype.hasTexture = function (texture) {
  53875. if (_super.prototype.hasTexture.call(this, texture)) {
  53876. return true;
  53877. }
  53878. for (var name in this._textures) {
  53879. if (this._textures[name] === texture) {
  53880. return true;
  53881. }
  53882. }
  53883. for (var name in this._textureArrays) {
  53884. var array = this._textureArrays[name];
  53885. for (var index = 0; index < array.length; index++) {
  53886. if (array[index] === texture) {
  53887. return true;
  53888. }
  53889. }
  53890. }
  53891. return false;
  53892. };
  53893. ShaderMaterial.prototype.clone = function (name) {
  53894. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53895. return newShaderMaterial;
  53896. };
  53897. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53898. if (forceDisposeTextures) {
  53899. var name;
  53900. for (name in this._textures) {
  53901. this._textures[name].dispose();
  53902. }
  53903. for (name in this._textureArrays) {
  53904. var array = this._textureArrays[name];
  53905. for (var index = 0; index < array.length; index++) {
  53906. array[index].dispose();
  53907. }
  53908. }
  53909. }
  53910. this._textures = {};
  53911. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53912. };
  53913. ShaderMaterial.prototype.serialize = function () {
  53914. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53915. serializationObject.customType = "BABYLON.ShaderMaterial";
  53916. serializationObject.options = this._options;
  53917. serializationObject.shaderPath = this._shaderPath;
  53918. var name;
  53919. // Texture
  53920. serializationObject.textures = {};
  53921. for (name in this._textures) {
  53922. serializationObject.textures[name] = this._textures[name].serialize();
  53923. }
  53924. // Texture arrays
  53925. serializationObject.textureArrays = {};
  53926. for (name in this._textureArrays) {
  53927. serializationObject.textureArrays[name] = [];
  53928. var array = this._textureArrays[name];
  53929. for (var index = 0; index < array.length; index++) {
  53930. serializationObject.textureArrays[name].push(array[index].serialize());
  53931. }
  53932. }
  53933. // Float
  53934. serializationObject.floats = {};
  53935. for (name in this._floats) {
  53936. serializationObject.floats[name] = this._floats[name];
  53937. }
  53938. // Float s
  53939. serializationObject.FloatArrays = {};
  53940. for (name in this._floatsArrays) {
  53941. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53942. }
  53943. // Color3
  53944. serializationObject.colors3 = {};
  53945. for (name in this._colors3) {
  53946. serializationObject.colors3[name] = this._colors3[name].asArray();
  53947. }
  53948. // Color3 array
  53949. serializationObject.colors3Arrays = {};
  53950. for (name in this._colors3Arrays) {
  53951. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53952. }
  53953. // Color4
  53954. serializationObject.colors4 = {};
  53955. for (name in this._colors4) {
  53956. serializationObject.colors4[name] = this._colors4[name].asArray();
  53957. }
  53958. // Vector2
  53959. serializationObject.vectors2 = {};
  53960. for (name in this._vectors2) {
  53961. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53962. }
  53963. // Vector3
  53964. serializationObject.vectors3 = {};
  53965. for (name in this._vectors3) {
  53966. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53967. }
  53968. // Vector4
  53969. serializationObject.vectors4 = {};
  53970. for (name in this._vectors4) {
  53971. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53972. }
  53973. // Matrix
  53974. serializationObject.matrices = {};
  53975. for (name in this._matrices) {
  53976. serializationObject.matrices[name] = this._matrices[name].asArray();
  53977. }
  53978. // Matrix 3x3
  53979. serializationObject.matrices3x3 = {};
  53980. for (name in this._matrices3x3) {
  53981. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53982. }
  53983. // Matrix 2x2
  53984. serializationObject.matrices2x2 = {};
  53985. for (name in this._matrices2x2) {
  53986. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53987. }
  53988. // Vector2Array
  53989. serializationObject.vectors2Arrays = {};
  53990. for (name in this._vectors2Arrays) {
  53991. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53992. }
  53993. // Vector3Array
  53994. serializationObject.vectors3Arrays = {};
  53995. for (name in this._vectors3Arrays) {
  53996. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53997. }
  53998. return serializationObject;
  53999. };
  54000. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54001. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54002. var name;
  54003. // Texture
  54004. for (name in source.textures) {
  54005. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54006. }
  54007. // Texture arrays
  54008. for (name in source.textureArrays) {
  54009. var array = source.textureArrays[name];
  54010. var textureArray = new Array();
  54011. for (var index = 0; index < array.length; index++) {
  54012. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54013. }
  54014. material.setTextureArray(name, textureArray);
  54015. }
  54016. // Float
  54017. for (name in source.floats) {
  54018. material.setFloat(name, source.floats[name]);
  54019. }
  54020. // Float s
  54021. for (name in source.floatsArrays) {
  54022. material.setFloats(name, source.floatsArrays[name]);
  54023. }
  54024. // Color3
  54025. for (name in source.colors3) {
  54026. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54027. }
  54028. // Color3 arrays
  54029. for (name in source.colors3Arrays) {
  54030. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54031. if (i % 3 === 0) {
  54032. arr.push([num]);
  54033. }
  54034. else {
  54035. arr[arr.length - 1].push(num);
  54036. }
  54037. return arr;
  54038. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54039. material.setColor3Array(name, colors);
  54040. }
  54041. // Color4
  54042. for (name in source.colors4) {
  54043. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54044. }
  54045. // Vector2
  54046. for (name in source.vectors2) {
  54047. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54048. }
  54049. // Vector3
  54050. for (name in source.vectors3) {
  54051. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54052. }
  54053. // Vector4
  54054. for (name in source.vectors4) {
  54055. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54056. }
  54057. // Matrix
  54058. for (name in source.matrices) {
  54059. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54060. }
  54061. // Matrix 3x3
  54062. for (name in source.matrices3x3) {
  54063. material.setMatrix3x3(name, source.matrices3x3[name]);
  54064. }
  54065. // Matrix 2x2
  54066. for (name in source.matrices2x2) {
  54067. material.setMatrix2x2(name, source.matrices2x2[name]);
  54068. }
  54069. // Vector2Array
  54070. for (name in source.vectors2Arrays) {
  54071. material.setArray2(name, source.vectors2Arrays[name]);
  54072. }
  54073. // Vector3Array
  54074. for (name in source.vectors3Arrays) {
  54075. material.setArray3(name, source.vectors3Arrays[name]);
  54076. }
  54077. return material;
  54078. };
  54079. return ShaderMaterial;
  54080. }(BABYLON.Material));
  54081. BABYLON.ShaderMaterial = ShaderMaterial;
  54082. })(BABYLON || (BABYLON = {}));
  54083. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54084. var BABYLON;
  54085. (function (BABYLON) {
  54086. var GroundMesh = /** @class */ (function (_super) {
  54087. __extends(GroundMesh, _super);
  54088. function GroundMesh(name, scene) {
  54089. var _this = _super.call(this, name, scene) || this;
  54090. _this.generateOctree = false;
  54091. return _this;
  54092. }
  54093. GroundMesh.prototype.getClassName = function () {
  54094. return "GroundMesh";
  54095. };
  54096. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54097. get: function () {
  54098. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54099. },
  54100. enumerable: true,
  54101. configurable: true
  54102. });
  54103. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54104. get: function () {
  54105. return this._subdivisionsX;
  54106. },
  54107. enumerable: true,
  54108. configurable: true
  54109. });
  54110. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54111. get: function () {
  54112. return this._subdivisionsY;
  54113. },
  54114. enumerable: true,
  54115. configurable: true
  54116. });
  54117. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54118. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54119. this._subdivisionsX = chunksCount;
  54120. this._subdivisionsY = chunksCount;
  54121. this.subdivide(chunksCount);
  54122. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54123. };
  54124. /**
  54125. * Returns a height (y) value in the Worl system :
  54126. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54127. * Returns the ground y position if (x, z) are outside the ground surface.
  54128. */
  54129. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54130. var world = this.getWorldMatrix();
  54131. var invMat = BABYLON.Tmp.Matrix[5];
  54132. world.invertToRef(invMat);
  54133. var tmpVect = BABYLON.Tmp.Vector3[8];
  54134. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54135. x = tmpVect.x;
  54136. z = tmpVect.z;
  54137. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54138. return this.position.y;
  54139. }
  54140. if (!this._heightQuads || this._heightQuads.length == 0) {
  54141. this._initHeightQuads();
  54142. this._computeHeightQuads();
  54143. }
  54144. var facet = this._getFacetAt(x, z);
  54145. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54146. // return y in the World system
  54147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54148. return tmpVect.y;
  54149. };
  54150. /**
  54151. * Returns a normalized vector (Vector3) orthogonal to the ground
  54152. * at the ground coordinates (x, z) expressed in the World system.
  54153. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54154. */
  54155. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54156. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54157. this.getNormalAtCoordinatesToRef(x, z, normal);
  54158. return normal;
  54159. };
  54160. /**
  54161. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54162. * at the ground coordinates (x, z) expressed in the World system.
  54163. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54164. * Returns the GroundMesh.
  54165. */
  54166. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54167. var world = this.getWorldMatrix();
  54168. var tmpMat = BABYLON.Tmp.Matrix[5];
  54169. world.invertToRef(tmpMat);
  54170. var tmpVect = BABYLON.Tmp.Vector3[8];
  54171. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54172. x = tmpVect.x;
  54173. z = tmpVect.z;
  54174. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54175. return this;
  54176. }
  54177. if (!this._heightQuads || this._heightQuads.length == 0) {
  54178. this._initHeightQuads();
  54179. this._computeHeightQuads();
  54180. }
  54181. var facet = this._getFacetAt(x, z);
  54182. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54183. return this;
  54184. };
  54185. /**
  54186. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54187. * if the ground has been updated.
  54188. * This can be used in the render loop.
  54189. * Returns the GroundMesh.
  54190. */
  54191. GroundMesh.prototype.updateCoordinateHeights = function () {
  54192. if (!this._heightQuads || this._heightQuads.length == 0) {
  54193. this._initHeightQuads();
  54194. }
  54195. this._computeHeightQuads();
  54196. return this;
  54197. };
  54198. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54199. GroundMesh.prototype._getFacetAt = function (x, z) {
  54200. // retrieve col and row from x, z coordinates in the ground local system
  54201. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54202. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54203. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54204. var facet;
  54205. if (z < quad.slope.x * x + quad.slope.y) {
  54206. facet = quad.facet1;
  54207. }
  54208. else {
  54209. facet = quad.facet2;
  54210. }
  54211. return facet;
  54212. };
  54213. // Creates and populates the heightMap array with "facet" elements :
  54214. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54215. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54216. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54217. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54218. // Returns the GroundMesh.
  54219. GroundMesh.prototype._initHeightQuads = function () {
  54220. var subdivisionsX = this._subdivisionsX;
  54221. var subdivisionsY = this._subdivisionsY;
  54222. this._heightQuads = new Array();
  54223. for (var row = 0; row < subdivisionsY; row++) {
  54224. for (var col = 0; col < subdivisionsX; col++) {
  54225. 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) };
  54226. this._heightQuads[row * subdivisionsX + col] = quad;
  54227. }
  54228. }
  54229. return this;
  54230. };
  54231. // Compute each quad element values and update the the heightMap array :
  54232. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54233. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54234. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54235. // Returns the GroundMesh.
  54236. GroundMesh.prototype._computeHeightQuads = function () {
  54237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54238. if (!positions) {
  54239. return this;
  54240. }
  54241. var v1 = BABYLON.Tmp.Vector3[3];
  54242. var v2 = BABYLON.Tmp.Vector3[2];
  54243. var v3 = BABYLON.Tmp.Vector3[1];
  54244. var v4 = BABYLON.Tmp.Vector3[0];
  54245. var v1v2 = BABYLON.Tmp.Vector3[4];
  54246. var v1v3 = BABYLON.Tmp.Vector3[5];
  54247. var v1v4 = BABYLON.Tmp.Vector3[6];
  54248. var norm1 = BABYLON.Tmp.Vector3[7];
  54249. var norm2 = BABYLON.Tmp.Vector3[8];
  54250. var i = 0;
  54251. var j = 0;
  54252. var k = 0;
  54253. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54254. var h = 0;
  54255. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54256. var d2 = 0;
  54257. var subdivisionsX = this._subdivisionsX;
  54258. var subdivisionsY = this._subdivisionsY;
  54259. for (var row = 0; row < subdivisionsY; row++) {
  54260. for (var col = 0; col < subdivisionsX; col++) {
  54261. i = col * 3;
  54262. j = row * (subdivisionsX + 1) * 3;
  54263. k = (row + 1) * (subdivisionsX + 1) * 3;
  54264. v1.x = positions[j + i];
  54265. v1.y = positions[j + i + 1];
  54266. v1.z = positions[j + i + 2];
  54267. v2.x = positions[j + i + 3];
  54268. v2.y = positions[j + i + 4];
  54269. v2.z = positions[j + i + 5];
  54270. v3.x = positions[k + i];
  54271. v3.y = positions[k + i + 1];
  54272. v3.z = positions[k + i + 2];
  54273. v4.x = positions[k + i + 3];
  54274. v4.y = positions[k + i + 4];
  54275. v4.z = positions[k + i + 5];
  54276. // 2D slope V1V4
  54277. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54278. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54279. // facet equations :
  54280. // we compute each facet normal vector
  54281. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54282. // we compute the value d by applying the equation to v1 which belongs to the plane
  54283. // then we store the facet equation in a Vector4
  54284. v2.subtractToRef(v1, v1v2);
  54285. v3.subtractToRef(v1, v1v3);
  54286. v4.subtractToRef(v1, v1v4);
  54287. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54288. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54289. norm1.normalize();
  54290. norm2.normalize();
  54291. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54292. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54293. var quad = this._heightQuads[row * subdivisionsX + col];
  54294. quad.slope.copyFromFloats(cd, h);
  54295. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54296. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54297. }
  54298. }
  54299. return this;
  54300. };
  54301. GroundMesh.prototype.serialize = function (serializationObject) {
  54302. _super.prototype.serialize.call(this, serializationObject);
  54303. serializationObject.subdivisionsX = this._subdivisionsX;
  54304. serializationObject.subdivisionsY = this._subdivisionsY;
  54305. serializationObject.minX = this._minX;
  54306. serializationObject.maxX = this._maxX;
  54307. serializationObject.minZ = this._minZ;
  54308. serializationObject.maxZ = this._maxZ;
  54309. serializationObject.width = this._width;
  54310. serializationObject.height = this._height;
  54311. };
  54312. GroundMesh.Parse = function (parsedMesh, scene) {
  54313. var result = new GroundMesh(parsedMesh.name, scene);
  54314. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54315. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54316. result._minX = parsedMesh.minX;
  54317. result._maxX = parsedMesh.maxX;
  54318. result._minZ = parsedMesh.minZ;
  54319. result._maxZ = parsedMesh.maxZ;
  54320. result._width = parsedMesh.width;
  54321. result._height = parsedMesh.height;
  54322. return result;
  54323. };
  54324. return GroundMesh;
  54325. }(BABYLON.Mesh));
  54326. BABYLON.GroundMesh = GroundMesh;
  54327. })(BABYLON || (BABYLON = {}));
  54328. //# sourceMappingURL=babylon.groundMesh.js.map
  54329. var BABYLON;
  54330. (function (BABYLON) {
  54331. /**
  54332. * Creates an instance based on a source mesh.
  54333. */
  54334. var InstancedMesh = /** @class */ (function (_super) {
  54335. __extends(InstancedMesh, _super);
  54336. function InstancedMesh(name, source) {
  54337. var _this = _super.call(this, name, source.getScene()) || this;
  54338. source.instances.push(_this);
  54339. _this._sourceMesh = source;
  54340. _this.position.copyFrom(source.position);
  54341. _this.rotation.copyFrom(source.rotation);
  54342. _this.scaling.copyFrom(source.scaling);
  54343. if (source.rotationQuaternion) {
  54344. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54345. }
  54346. _this.infiniteDistance = source.infiniteDistance;
  54347. _this.setPivotMatrix(source.getPivotMatrix());
  54348. _this.refreshBoundingInfo();
  54349. _this._syncSubMeshes();
  54350. return _this;
  54351. }
  54352. /**
  54353. * Returns the string "InstancedMesh".
  54354. */
  54355. InstancedMesh.prototype.getClassName = function () {
  54356. return "InstancedMesh";
  54357. };
  54358. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54359. // Methods
  54360. get: function () {
  54361. return this._sourceMesh.receiveShadows;
  54362. },
  54363. enumerable: true,
  54364. configurable: true
  54365. });
  54366. Object.defineProperty(InstancedMesh.prototype, "material", {
  54367. get: function () {
  54368. return this._sourceMesh.material;
  54369. },
  54370. enumerable: true,
  54371. configurable: true
  54372. });
  54373. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54374. get: function () {
  54375. return this._sourceMesh.visibility;
  54376. },
  54377. enumerable: true,
  54378. configurable: true
  54379. });
  54380. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54381. get: function () {
  54382. return this._sourceMesh.skeleton;
  54383. },
  54384. enumerable: true,
  54385. configurable: true
  54386. });
  54387. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54388. get: function () {
  54389. return this._sourceMesh.renderingGroupId;
  54390. },
  54391. enumerable: true,
  54392. configurable: true
  54393. });
  54394. /**
  54395. * Returns the total number of vertices (integer).
  54396. */
  54397. InstancedMesh.prototype.getTotalVertices = function () {
  54398. return this._sourceMesh.getTotalVertices();
  54399. };
  54400. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54401. get: function () {
  54402. return this._sourceMesh;
  54403. },
  54404. enumerable: true,
  54405. configurable: true
  54406. });
  54407. /**
  54408. * Is this node ready to be used/rendered
  54409. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54410. * @return {boolean} is it ready
  54411. */
  54412. InstancedMesh.prototype.isReady = function (completeCheck) {
  54413. if (completeCheck === void 0) { completeCheck = false; }
  54414. return this._sourceMesh.isReady(completeCheck, true);
  54415. };
  54416. /**
  54417. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54418. */
  54419. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54420. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54421. };
  54422. /**
  54423. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54424. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54425. * The `data` are either a numeric array either a Float32Array.
  54426. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54427. * 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).
  54428. * Note that a new underlying VertexBuffer object is created each call.
  54429. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54430. *
  54431. * Possible `kind` values :
  54432. * - BABYLON.VertexBuffer.PositionKind
  54433. * - BABYLON.VertexBuffer.UVKind
  54434. * - BABYLON.VertexBuffer.UV2Kind
  54435. * - BABYLON.VertexBuffer.UV3Kind
  54436. * - BABYLON.VertexBuffer.UV4Kind
  54437. * - BABYLON.VertexBuffer.UV5Kind
  54438. * - BABYLON.VertexBuffer.UV6Kind
  54439. * - BABYLON.VertexBuffer.ColorKind
  54440. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54441. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54442. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54443. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54444. *
  54445. * Returns the Mesh.
  54446. */
  54447. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54448. if (this.sourceMesh) {
  54449. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54450. }
  54451. return this.sourceMesh;
  54452. };
  54453. /**
  54454. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54455. * If the mesh has no geometry, it is simply returned as it is.
  54456. * The `data` are either a numeric array either a Float32Array.
  54457. * No new underlying VertexBuffer object is created.
  54458. * 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.
  54459. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54460. *
  54461. * Possible `kind` values :
  54462. * - BABYLON.VertexBuffer.PositionKind
  54463. * - BABYLON.VertexBuffer.UVKind
  54464. * - BABYLON.VertexBuffer.UV2Kind
  54465. * - BABYLON.VertexBuffer.UV3Kind
  54466. * - BABYLON.VertexBuffer.UV4Kind
  54467. * - BABYLON.VertexBuffer.UV5Kind
  54468. * - BABYLON.VertexBuffer.UV6Kind
  54469. * - BABYLON.VertexBuffer.ColorKind
  54470. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54471. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54472. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54473. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54474. *
  54475. * Returns the Mesh.
  54476. */
  54477. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54478. if (this.sourceMesh) {
  54479. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54480. }
  54481. return this.sourceMesh;
  54482. };
  54483. /**
  54484. * Sets the mesh indices.
  54485. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54486. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54487. * This method creates a new index buffer each call.
  54488. * Returns the Mesh.
  54489. */
  54490. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54491. if (totalVertices === void 0) { totalVertices = null; }
  54492. if (this.sourceMesh) {
  54493. this.sourceMesh.setIndices(indices, totalVertices);
  54494. }
  54495. return this.sourceMesh;
  54496. };
  54497. /**
  54498. * Boolean : True if the mesh owns the requested kind of data.
  54499. */
  54500. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54501. return this._sourceMesh.isVerticesDataPresent(kind);
  54502. };
  54503. /**
  54504. * Returns an array of indices (IndicesArray).
  54505. */
  54506. InstancedMesh.prototype.getIndices = function () {
  54507. return this._sourceMesh.getIndices();
  54508. };
  54509. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54510. get: function () {
  54511. return this._sourceMesh._positions;
  54512. },
  54513. enumerable: true,
  54514. configurable: true
  54515. });
  54516. /**
  54517. * Sets a new updated BoundingInfo to the mesh.
  54518. * Returns the mesh.
  54519. */
  54520. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54521. var meshBB = this._sourceMesh.getBoundingInfo();
  54522. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54523. this._updateBoundingInfo();
  54524. return this;
  54525. };
  54526. InstancedMesh.prototype._preActivate = function () {
  54527. if (this._currentLOD) {
  54528. this._currentLOD._preActivate();
  54529. }
  54530. return this;
  54531. };
  54532. InstancedMesh.prototype._activate = function (renderId) {
  54533. if (this._currentLOD) {
  54534. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54535. }
  54536. return this;
  54537. };
  54538. /**
  54539. * Returns the current associated LOD AbstractMesh.
  54540. */
  54541. InstancedMesh.prototype.getLOD = function (camera) {
  54542. if (!camera) {
  54543. return this;
  54544. }
  54545. var boundingInfo = this.getBoundingInfo();
  54546. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54547. if (this._currentLOD === this.sourceMesh) {
  54548. return this;
  54549. }
  54550. return this._currentLOD;
  54551. };
  54552. InstancedMesh.prototype._syncSubMeshes = function () {
  54553. this.releaseSubMeshes();
  54554. if (this._sourceMesh.subMeshes) {
  54555. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54556. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54557. }
  54558. }
  54559. return this;
  54560. };
  54561. InstancedMesh.prototype._generatePointsArray = function () {
  54562. return this._sourceMesh._generatePointsArray();
  54563. };
  54564. /**
  54565. * Creates a new InstancedMesh from the current mesh.
  54566. * - name (string) : the cloned mesh name
  54567. * - newParent (optional Node) : the optional Node to parent the clone to.
  54568. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54569. *
  54570. * Returns the clone.
  54571. */
  54572. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54573. var result = this._sourceMesh.createInstance(name);
  54574. // Deep copy
  54575. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54576. // Bounding info
  54577. this.refreshBoundingInfo();
  54578. // Parent
  54579. if (newParent) {
  54580. result.parent = newParent;
  54581. }
  54582. if (!doNotCloneChildren) {
  54583. // Children
  54584. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54585. var mesh = this.getScene().meshes[index];
  54586. if (mesh.parent === this) {
  54587. mesh.clone(mesh.name, result);
  54588. }
  54589. }
  54590. }
  54591. result.computeWorldMatrix(true);
  54592. return result;
  54593. };
  54594. /**
  54595. * Disposes the InstancedMesh.
  54596. * Returns nothing.
  54597. */
  54598. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54599. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54600. // Remove from mesh
  54601. var index = this._sourceMesh.instances.indexOf(this);
  54602. this._sourceMesh.instances.splice(index, 1);
  54603. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54604. };
  54605. return InstancedMesh;
  54606. }(BABYLON.AbstractMesh));
  54607. BABYLON.InstancedMesh = InstancedMesh;
  54608. })(BABYLON || (BABYLON = {}));
  54609. //# sourceMappingURL=babylon.instancedMesh.js.map
  54610. var BABYLON;
  54611. (function (BABYLON) {
  54612. var LinesMesh = /** @class */ (function (_super) {
  54613. __extends(LinesMesh, _super);
  54614. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54615. if (scene === void 0) { scene = null; }
  54616. if (parent === void 0) { parent = null; }
  54617. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54618. _this.useVertexColor = useVertexColor;
  54619. _this.useVertexAlpha = useVertexAlpha;
  54620. _this.color = new BABYLON.Color3(1, 1, 1);
  54621. _this.alpha = 1;
  54622. if (source) {
  54623. _this.color = source.color.clone();
  54624. _this.alpha = source.alpha;
  54625. _this.useVertexColor = source.useVertexColor;
  54626. _this.useVertexAlpha = source.useVertexAlpha;
  54627. }
  54628. _this._intersectionThreshold = 0.1;
  54629. var defines = [];
  54630. var options = {
  54631. attributes: [BABYLON.VertexBuffer.PositionKind],
  54632. uniforms: ["world", "viewProjection"],
  54633. needAlphaBlending: true,
  54634. defines: defines
  54635. };
  54636. if (useVertexAlpha === false) {
  54637. options.needAlphaBlending = false;
  54638. }
  54639. if (!useVertexColor) {
  54640. options.uniforms.push("color");
  54641. }
  54642. else {
  54643. options.defines.push("#define VERTEXCOLOR");
  54644. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54645. }
  54646. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54647. return _this;
  54648. }
  54649. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54650. /**
  54651. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54652. * This margin is expressed in world space coordinates, so its value may vary.
  54653. * Default value is 0.1
  54654. * @returns the intersection Threshold value.
  54655. */
  54656. get: function () {
  54657. return this._intersectionThreshold;
  54658. },
  54659. /**
  54660. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54661. * This margin is expressed in world space coordinates, so its value may vary.
  54662. * @param value the new threshold to apply
  54663. */
  54664. set: function (value) {
  54665. if (this._intersectionThreshold === value) {
  54666. return;
  54667. }
  54668. this._intersectionThreshold = value;
  54669. if (this.geometry) {
  54670. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54671. }
  54672. },
  54673. enumerable: true,
  54674. configurable: true
  54675. });
  54676. /**
  54677. * Returns the string "LineMesh"
  54678. */
  54679. LinesMesh.prototype.getClassName = function () {
  54680. return "LinesMesh";
  54681. };
  54682. Object.defineProperty(LinesMesh.prototype, "material", {
  54683. get: function () {
  54684. return this._colorShader;
  54685. },
  54686. set: function (value) {
  54687. // Do nothing
  54688. },
  54689. enumerable: true,
  54690. configurable: true
  54691. });
  54692. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54693. get: function () {
  54694. return false;
  54695. },
  54696. enumerable: true,
  54697. configurable: true
  54698. });
  54699. LinesMesh.prototype.createInstance = function (name) {
  54700. throw new Error("LinesMeshes do not support createInstance.");
  54701. };
  54702. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54703. if (!this._geometry) {
  54704. return this;
  54705. }
  54706. // VBOs
  54707. this._geometry._bind(this._colorShader.getEffect());
  54708. // Color
  54709. if (!this.useVertexColor) {
  54710. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54711. }
  54712. return this;
  54713. };
  54714. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54715. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54716. return this;
  54717. }
  54718. var engine = this.getScene().getEngine();
  54719. // Draw order
  54720. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54721. return this;
  54722. };
  54723. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54724. this._colorShader.dispose();
  54725. _super.prototype.dispose.call(this, doNotRecurse);
  54726. };
  54727. /**
  54728. * Returns a new LineMesh object cloned from the current one.
  54729. */
  54730. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54731. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54732. };
  54733. return LinesMesh;
  54734. }(BABYLON.Mesh));
  54735. BABYLON.LinesMesh = LinesMesh;
  54736. })(BABYLON || (BABYLON = {}));
  54737. //# sourceMappingURL=babylon.linesMesh.js.map
  54738. var BABYLON;
  54739. (function (BABYLON) {
  54740. var MeshBuilder = /** @class */ (function () {
  54741. function MeshBuilder() {
  54742. }
  54743. MeshBuilder.updateSideOrientation = function (orientation) {
  54744. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54745. return BABYLON.Mesh.DOUBLESIDE;
  54746. }
  54747. if (orientation === undefined || orientation === null) {
  54748. return BABYLON.Mesh.FRONTSIDE;
  54749. }
  54750. return orientation;
  54751. };
  54752. /**
  54753. * Creates a box mesh.
  54754. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54755. * The parameter `size` sets the size (float) of each box side (default 1).
  54756. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54757. * 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).
  54758. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54760. * 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).
  54761. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54763. */
  54764. MeshBuilder.CreateBox = function (name, options, scene) {
  54765. if (scene === void 0) { scene = null; }
  54766. var box = new BABYLON.Mesh(name, scene);
  54767. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54768. box._originalBuilderSideOrientation = options.sideOrientation;
  54769. var vertexData = BABYLON.VertexData.CreateBox(options);
  54770. vertexData.applyToMesh(box, options.updatable);
  54771. return box;
  54772. };
  54773. /**
  54774. * Creates a sphere mesh.
  54775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54776. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54777. * 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`).
  54778. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54779. * 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
  54780. * 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).
  54781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54782. * 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).
  54783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54785. */
  54786. MeshBuilder.CreateSphere = function (name, options, scene) {
  54787. var sphere = new BABYLON.Mesh(name, scene);
  54788. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54789. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54790. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54791. vertexData.applyToMesh(sphere, options.updatable);
  54792. return sphere;
  54793. };
  54794. /**
  54795. * Creates a plane polygonal mesh. By default, this is a disc.
  54796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54797. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54798. * 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.
  54799. * 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
  54800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54801. * 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).
  54802. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54804. */
  54805. MeshBuilder.CreateDisc = function (name, options, scene) {
  54806. if (scene === void 0) { scene = null; }
  54807. var disc = new BABYLON.Mesh(name, scene);
  54808. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54809. disc._originalBuilderSideOrientation = options.sideOrientation;
  54810. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54811. vertexData.applyToMesh(disc, options.updatable);
  54812. return disc;
  54813. };
  54814. /**
  54815. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54816. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54817. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54818. * 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`).
  54819. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54820. * 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.
  54821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54822. * 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).
  54823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54825. */
  54826. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54827. var sphere = new BABYLON.Mesh(name, scene);
  54828. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54829. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54830. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54831. vertexData.applyToMesh(sphere, options.updatable);
  54832. return sphere;
  54833. };
  54834. ;
  54835. /**
  54836. * Creates a ribbon mesh.
  54837. * 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.
  54838. *
  54839. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54840. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54841. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54842. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54843. * 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.
  54844. * 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.
  54845. * 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
  54846. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54847. * 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).
  54848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54849. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54850. * 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.
  54851. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54852. * 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
  54853. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54854. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54855. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54856. */
  54857. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54858. if (scene === void 0) { scene = null; }
  54859. var pathArray = options.pathArray;
  54860. var closeArray = options.closeArray;
  54861. var closePath = options.closePath;
  54862. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54863. var instance = options.instance;
  54864. var updatable = options.updatable;
  54865. if (instance) {
  54866. // positionFunction : ribbon case
  54867. // only pathArray and sideOrientation parameters are taken into account for positions update
  54868. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54869. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54870. var positionFunction = function (positions) {
  54871. var minlg = pathArray[0].length;
  54872. var i = 0;
  54873. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54874. for (var si = 1; si <= ns; si++) {
  54875. for (var p = 0; p < pathArray.length; p++) {
  54876. var path = pathArray[p];
  54877. var l = path.length;
  54878. minlg = (minlg < l) ? minlg : l;
  54879. var j = 0;
  54880. while (j < minlg) {
  54881. positions[i] = path[j].x;
  54882. positions[i + 1] = path[j].y;
  54883. positions[i + 2] = path[j].z;
  54884. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54885. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54886. }
  54887. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54888. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54889. }
  54890. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54891. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54892. }
  54893. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54894. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54895. }
  54896. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54897. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54898. }
  54899. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54900. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54901. }
  54902. j++;
  54903. i += 3;
  54904. }
  54905. if (instance._closePath) {
  54906. positions[i] = path[0].x;
  54907. positions[i + 1] = path[0].y;
  54908. positions[i + 2] = path[0].z;
  54909. i += 3;
  54910. }
  54911. }
  54912. }
  54913. };
  54914. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54915. positionFunction(positions);
  54916. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54917. instance._boundingInfo.update(instance._worldMatrix);
  54918. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54919. if (options.colors) {
  54920. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54921. for (var c = 0; c < options.colors.length; c++) {
  54922. colors[c * 4] = options.colors[c].r;
  54923. colors[c * 4 + 1] = options.colors[c].g;
  54924. colors[c * 4 + 2] = options.colors[c].b;
  54925. colors[c * 4 + 3] = options.colors[c].a;
  54926. }
  54927. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54928. }
  54929. if (options.uvs) {
  54930. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54931. for (var i = 0; i < options.uvs.length; i++) {
  54932. uvs[i * 2] = options.uvs[i].x;
  54933. uvs[i * 2 + 1] = options.uvs[i].y;
  54934. }
  54935. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54936. }
  54937. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54938. var indices = instance.getIndices();
  54939. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54940. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54941. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54942. if (instance._closePath) {
  54943. var indexFirst = 0;
  54944. var indexLast = 0;
  54945. for (var p = 0; p < pathArray.length; p++) {
  54946. indexFirst = instance._idx[p] * 3;
  54947. if (p + 1 < pathArray.length) {
  54948. indexLast = (instance._idx[p + 1] - 1) * 3;
  54949. }
  54950. else {
  54951. indexLast = normals.length - 3;
  54952. }
  54953. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54954. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54955. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54956. normals[indexLast] = normals[indexFirst];
  54957. normals[indexLast + 1] = normals[indexFirst + 1];
  54958. normals[indexLast + 2] = normals[indexFirst + 2];
  54959. }
  54960. }
  54961. if (!(instance.areNormalsFrozen)) {
  54962. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54963. }
  54964. }
  54965. return instance;
  54966. }
  54967. else {
  54968. var ribbon = new BABYLON.Mesh(name, scene);
  54969. ribbon._originalBuilderSideOrientation = sideOrientation;
  54970. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54971. if (closePath) {
  54972. ribbon._idx = vertexData._idx;
  54973. }
  54974. ribbon._closePath = closePath;
  54975. ribbon._closeArray = closeArray;
  54976. vertexData.applyToMesh(ribbon, updatable);
  54977. return ribbon;
  54978. }
  54979. };
  54980. /**
  54981. * Creates a cylinder or a cone mesh.
  54982. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54983. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54984. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54985. * 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.
  54986. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54987. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54988. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54989. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54990. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54991. * 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).
  54992. * 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
  54993. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54994. * 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
  54995. * 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.
  54996. * If `enclose` is false, a ring surface is one element.
  54997. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54998. * 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
  54999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55000. * 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).
  55001. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55003. */
  55004. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55005. var cylinder = new BABYLON.Mesh(name, scene);
  55006. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55007. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55008. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55009. vertexData.applyToMesh(cylinder, options.updatable);
  55010. return cylinder;
  55011. };
  55012. /**
  55013. * Creates a torus mesh.
  55014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55015. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55016. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55017. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55019. * 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).
  55020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55022. */
  55023. MeshBuilder.CreateTorus = function (name, options, scene) {
  55024. var torus = new BABYLON.Mesh(name, scene);
  55025. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55026. torus._originalBuilderSideOrientation = options.sideOrientation;
  55027. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55028. vertexData.applyToMesh(torus, options.updatable);
  55029. return torus;
  55030. };
  55031. /**
  55032. * Creates a torus knot mesh.
  55033. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55034. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55035. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55036. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55037. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55038. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55039. * 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).
  55040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55042. */
  55043. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55044. var torusKnot = new BABYLON.Mesh(name, scene);
  55045. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55046. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55047. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55048. vertexData.applyToMesh(torusKnot, options.updatable);
  55049. return torusKnot;
  55050. };
  55051. /**
  55052. * Creates a line system mesh.
  55053. * A line system is a pool of many lines gathered in a single mesh.
  55054. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55055. * 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.
  55056. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55057. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55058. * 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
  55059. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55060. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55061. * 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
  55062. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55064. */
  55065. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55066. var instance = options.instance;
  55067. var lines = options.lines;
  55068. var colors = options.colors;
  55069. if (instance) {
  55070. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55071. var vertexColor;
  55072. var lineColors;
  55073. if (colors) {
  55074. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55075. }
  55076. var i = 0;
  55077. var c = 0;
  55078. for (var l = 0; l < lines.length; l++) {
  55079. var points = lines[l];
  55080. for (var p = 0; p < points.length; p++) {
  55081. positions[i] = points[p].x;
  55082. positions[i + 1] = points[p].y;
  55083. positions[i + 2] = points[p].z;
  55084. if (colors && vertexColor) {
  55085. lineColors = colors[l];
  55086. vertexColor[c] = lineColors[p].r;
  55087. vertexColor[c + 1] = lineColors[p].g;
  55088. vertexColor[c + 2] = lineColors[p].b;
  55089. vertexColor[c + 3] = lineColors[p].a;
  55090. c += 4;
  55091. }
  55092. i += 3;
  55093. }
  55094. }
  55095. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55096. if (colors && vertexColor) {
  55097. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55098. }
  55099. return instance;
  55100. }
  55101. // line system creation
  55102. var useVertexColor = (colors) ? true : false;
  55103. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55104. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55105. vertexData.applyToMesh(lineSystem, options.updatable);
  55106. return lineSystem;
  55107. };
  55108. /**
  55109. * Creates a line mesh.
  55110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55111. * 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.
  55112. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55113. * The parameter `points` is an array successive Vector3.
  55114. * 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
  55115. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55116. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55117. * When updating an instance, remember that only point positions can change, not the number of points.
  55118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55119. */
  55120. MeshBuilder.CreateLines = function (name, options, scene) {
  55121. if (scene === void 0) { scene = null; }
  55122. var colors = (options.colors) ? [options.colors] : null;
  55123. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55124. return lines;
  55125. };
  55126. /**
  55127. * Creates a dashed line mesh.
  55128. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55129. * 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.
  55130. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55131. * The parameter `points` is an array successive Vector3.
  55132. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55133. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55134. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55135. * 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
  55136. * When updating an instance, remember that only point positions can change, not the number of points.
  55137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55138. */
  55139. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55140. if (scene === void 0) { scene = null; }
  55141. var points = options.points;
  55142. var instance = options.instance;
  55143. var gapSize = options.gapSize || 1;
  55144. var dashSize = options.dashSize || 3;
  55145. if (instance) {
  55146. var positionFunction = function (positions) {
  55147. var curvect = BABYLON.Vector3.Zero();
  55148. var nbSeg = positions.length / 6;
  55149. var lg = 0;
  55150. var nb = 0;
  55151. var shft = 0;
  55152. var dashshft = 0;
  55153. var curshft = 0;
  55154. var p = 0;
  55155. var i = 0;
  55156. var j = 0;
  55157. for (i = 0; i < points.length - 1; i++) {
  55158. points[i + 1].subtractToRef(points[i], curvect);
  55159. lg += curvect.length();
  55160. }
  55161. shft = lg / nbSeg;
  55162. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55163. for (i = 0; i < points.length - 1; i++) {
  55164. points[i + 1].subtractToRef(points[i], curvect);
  55165. nb = Math.floor(curvect.length() / shft);
  55166. curvect.normalize();
  55167. j = 0;
  55168. while (j < nb && p < positions.length) {
  55169. curshft = shft * j;
  55170. positions[p] = points[i].x + curshft * curvect.x;
  55171. positions[p + 1] = points[i].y + curshft * curvect.y;
  55172. positions[p + 2] = points[i].z + curshft * curvect.z;
  55173. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55174. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55175. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55176. p += 6;
  55177. j++;
  55178. }
  55179. }
  55180. while (p < positions.length) {
  55181. positions[p] = points[i].x;
  55182. positions[p + 1] = points[i].y;
  55183. positions[p + 2] = points[i].z;
  55184. p += 3;
  55185. }
  55186. };
  55187. instance.updateMeshPositions(positionFunction, false);
  55188. return instance;
  55189. }
  55190. // dashed lines creation
  55191. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55192. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55193. vertexData.applyToMesh(dashedLines, options.updatable);
  55194. dashedLines.dashSize = dashSize;
  55195. dashedLines.gapSize = gapSize;
  55196. return dashedLines;
  55197. };
  55198. /**
  55199. * Creates an extruded shape mesh.
  55200. * 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.
  55201. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55202. *
  55203. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55204. * 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
  55205. * extruded along the Z axis.
  55206. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55207. * 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.
  55208. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55209. * 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
  55210. * 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
  55211. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55213. * 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).
  55214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55215. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55217. */
  55218. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55219. if (scene === void 0) { scene = null; }
  55220. var path = options.path;
  55221. var shape = options.shape;
  55222. var scale = options.scale || 1;
  55223. var rotation = options.rotation || 0;
  55224. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55225. var updatable = options.updatable;
  55226. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55227. var instance = options.instance || null;
  55228. var invertUV = options.invertUV || false;
  55229. 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);
  55230. };
  55231. /**
  55232. * Creates an custom extruded shape mesh.
  55233. * 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.
  55234. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55235. *
  55236. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55237. * 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
  55238. * extruded along the Z axis.
  55239. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55240. * 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
  55241. * and the distance of this point from the begining of the path :
  55242. * ```javascript
  55243. * var rotationFunction = function(i, distance) {
  55244. * // do things
  55245. * return rotationValue; }
  55246. * ```
  55247. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55248. * 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
  55249. * and the distance of this point from the begining of the path :
  55250. * ```javascript
  55251. * var scaleFunction = function(i, distance) {
  55252. * // do things
  55253. * return scaleValue;}
  55254. * ```
  55255. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55256. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55257. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55258. * 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
  55259. * 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
  55260. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55262. * 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).
  55263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55264. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55266. */
  55267. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55268. var path = options.path;
  55269. var shape = options.shape;
  55270. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55271. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55272. var ribbonCloseArray = options.ribbonCloseArray || false;
  55273. var ribbonClosePath = options.ribbonClosePath || false;
  55274. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55275. var updatable = options.updatable;
  55276. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55277. var instance = options.instance;
  55278. var invertUV = options.invertUV || false;
  55279. 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);
  55280. };
  55281. /**
  55282. * Creates lathe mesh.
  55283. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55284. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55285. *
  55286. * 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
  55287. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55288. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55289. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55290. * 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.
  55291. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55292. * 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
  55293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55294. * 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).
  55295. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55296. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55298. */
  55299. MeshBuilder.CreateLathe = function (name, options, scene) {
  55300. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55301. var closed = (options.closed === undefined) ? true : options.closed;
  55302. var shape = options.shape;
  55303. var radius = options.radius || 1;
  55304. var tessellation = options.tessellation || 64;
  55305. var updatable = options.updatable;
  55306. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55307. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55308. var pi2 = Math.PI * 2;
  55309. var paths = new Array();
  55310. var invertUV = options.invertUV || false;
  55311. var i = 0;
  55312. var p = 0;
  55313. var step = pi2 / tessellation * arc;
  55314. var rotated;
  55315. var path = new Array();
  55316. ;
  55317. for (i = 0; i <= tessellation; i++) {
  55318. var path = [];
  55319. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55320. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55321. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55322. }
  55323. for (p = 0; p < shape.length; p++) {
  55324. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55325. path.push(rotated);
  55326. }
  55327. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55328. 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));
  55329. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55330. }
  55331. paths.push(path);
  55332. }
  55333. // lathe ribbon
  55334. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55335. return lathe;
  55336. };
  55337. /**
  55338. * Creates a plane mesh.
  55339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55340. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55341. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55342. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55344. * 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).
  55345. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55347. */
  55348. MeshBuilder.CreatePlane = function (name, options, scene) {
  55349. var plane = new BABYLON.Mesh(name, scene);
  55350. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55351. plane._originalBuilderSideOrientation = options.sideOrientation;
  55352. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55353. vertexData.applyToMesh(plane, options.updatable);
  55354. if (options.sourcePlane) {
  55355. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55356. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55357. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55358. plane.rotate(vectorProduct, product);
  55359. }
  55360. return plane;
  55361. };
  55362. /**
  55363. * Creates a ground mesh.
  55364. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55365. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55366. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55368. */
  55369. MeshBuilder.CreateGround = function (name, options, scene) {
  55370. var ground = new BABYLON.GroundMesh(name, scene);
  55371. ground._setReady(false);
  55372. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55373. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55374. ground._width = options.width || 1;
  55375. ground._height = options.height || 1;
  55376. ground._maxX = ground._width / 2;
  55377. ground._maxZ = ground._height / 2;
  55378. ground._minX = -ground._maxX;
  55379. ground._minZ = -ground._maxZ;
  55380. var vertexData = BABYLON.VertexData.CreateGround(options);
  55381. vertexData.applyToMesh(ground, options.updatable);
  55382. ground._setReady(true);
  55383. return ground;
  55384. };
  55385. /**
  55386. * Creates a tiled ground mesh.
  55387. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55388. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55389. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55390. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55391. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55392. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55393. * numbers of subdivisions on the ground width and height of each tile.
  55394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55395. */
  55396. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55397. var tiledGround = new BABYLON.Mesh(name, scene);
  55398. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55399. vertexData.applyToMesh(tiledGround, options.updatable);
  55400. return tiledGround;
  55401. };
  55402. /**
  55403. * Creates a ground mesh from a height map.
  55404. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55405. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55406. * The parameter `url` sets the URL of the height map image resource.
  55407. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55408. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55409. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55410. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55411. * 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.
  55412. * 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).
  55413. * This function is passed the newly built mesh :
  55414. * ```javascript
  55415. * function(mesh) { // do things
  55416. * return; }
  55417. * ```
  55418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55419. */
  55420. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55421. var width = options.width || 10.0;
  55422. var height = options.height || 10.0;
  55423. var subdivisions = options.subdivisions || 1 | 0;
  55424. var minHeight = options.minHeight || 0.0;
  55425. var maxHeight = options.maxHeight || 1.0;
  55426. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55427. var updatable = options.updatable;
  55428. var onReady = options.onReady;
  55429. var ground = new BABYLON.GroundMesh(name, scene);
  55430. ground._subdivisionsX = subdivisions;
  55431. ground._subdivisionsY = subdivisions;
  55432. ground._width = width;
  55433. ground._height = height;
  55434. ground._maxX = ground._width / 2.0;
  55435. ground._maxZ = ground._height / 2.0;
  55436. ground._minX = -ground._maxX;
  55437. ground._minZ = -ground._maxZ;
  55438. ground._setReady(false);
  55439. var onload = function (img) {
  55440. // Getting height map data
  55441. var canvas = document.createElement("canvas");
  55442. var context = canvas.getContext("2d");
  55443. if (!context) {
  55444. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55445. }
  55446. if (scene.isDisposed) {
  55447. return;
  55448. }
  55449. var bufferWidth = img.width;
  55450. var bufferHeight = img.height;
  55451. canvas.width = bufferWidth;
  55452. canvas.height = bufferHeight;
  55453. context.drawImage(img, 0, 0);
  55454. // Create VertexData from map data
  55455. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55456. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55457. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55458. width: width, height: height,
  55459. subdivisions: subdivisions,
  55460. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55461. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55462. });
  55463. vertexData.applyToMesh(ground, updatable);
  55464. ground._setReady(true);
  55465. //execute ready callback, if set
  55466. if (onReady) {
  55467. onReady(ground);
  55468. }
  55469. };
  55470. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55471. return ground;
  55472. };
  55473. /**
  55474. * Creates a polygon mesh.
  55475. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55476. * 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.
  55477. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  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. * 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).
  55480. * Remember you can only change the shape positions, not their number when updating a polygon.
  55481. */
  55482. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55483. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55484. var shape = options.shape;
  55485. var holes = options.holes || [];
  55486. var depth = options.depth || 0;
  55487. var contours = [];
  55488. var hole = [];
  55489. for (var i = 0; i < shape.length; i++) {
  55490. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55491. }
  55492. var epsilon = 0.00000001;
  55493. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55494. contours.pop();
  55495. }
  55496. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55497. for (var hNb = 0; hNb < holes.length; hNb++) {
  55498. hole = [];
  55499. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55500. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55501. }
  55502. polygonTriangulation.addHole(hole);
  55503. }
  55504. var polygon = polygonTriangulation.build(options.updatable, depth);
  55505. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55506. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55507. vertexData.applyToMesh(polygon, options.updatable);
  55508. return polygon;
  55509. };
  55510. ;
  55511. /**
  55512. * Creates an extruded polygon mesh, with depth in the Y direction.
  55513. * 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).
  55514. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55515. */
  55516. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55517. return MeshBuilder.CreatePolygon(name, options, scene);
  55518. };
  55519. ;
  55520. /**
  55521. * Creates a tube mesh.
  55522. * 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.
  55523. *
  55524. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55525. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55526. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55527. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55528. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55529. * 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.
  55530. * It must return a radius value (positive float) :
  55531. * ```javascript
  55532. * var radiusFunction = function(i, distance) {
  55533. * // do things
  55534. * return radius; }
  55535. * ```
  55536. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55537. * 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
  55538. * 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
  55539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55540. * 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).
  55541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55542. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55544. */
  55545. MeshBuilder.CreateTube = function (name, options, scene) {
  55546. var path = options.path;
  55547. var instance = options.instance;
  55548. var radius = 1.0;
  55549. if (instance) {
  55550. radius = instance.radius;
  55551. }
  55552. if (options.radius !== undefined) {
  55553. radius = options.radius;
  55554. }
  55555. ;
  55556. var tessellation = options.tessellation || 64 | 0;
  55557. var radiusFunction = options.radiusFunction || null;
  55558. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55559. var invertUV = options.invertUV || false;
  55560. var updatable = options.updatable;
  55561. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55562. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55563. // tube geometry
  55564. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55565. var tangents = path3D.getTangents();
  55566. var normals = path3D.getNormals();
  55567. var distances = path3D.getDistances();
  55568. var pi2 = Math.PI * 2;
  55569. var step = pi2 / tessellation * arc;
  55570. var returnRadius = function () { return radius; };
  55571. var radiusFunctionFinal = radiusFunction || returnRadius;
  55572. var circlePath;
  55573. var rad;
  55574. var normal;
  55575. var rotated;
  55576. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55577. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55578. for (var i = 0; i < path.length; i++) {
  55579. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55580. circlePath = Array(); // current circle array
  55581. normal = normals[i]; // current normal
  55582. for (var t = 0; t < tessellation; t++) {
  55583. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55584. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55585. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55586. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55587. circlePath[t] = rotated;
  55588. }
  55589. circlePaths[index] = circlePath;
  55590. index++;
  55591. }
  55592. // cap
  55593. var capPath = function (nbPoints, pathIndex) {
  55594. var pointCap = Array();
  55595. for (var i = 0; i < nbPoints; i++) {
  55596. pointCap.push(path[pathIndex]);
  55597. }
  55598. return pointCap;
  55599. };
  55600. switch (cap) {
  55601. case BABYLON.Mesh.NO_CAP:
  55602. break;
  55603. case BABYLON.Mesh.CAP_START:
  55604. circlePaths[0] = capPath(tessellation, 0);
  55605. circlePaths[1] = circlePaths[2].slice(0);
  55606. break;
  55607. case BABYLON.Mesh.CAP_END:
  55608. circlePaths[index] = circlePaths[index - 1].slice(0);
  55609. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55610. break;
  55611. case BABYLON.Mesh.CAP_ALL:
  55612. circlePaths[0] = capPath(tessellation, 0);
  55613. circlePaths[1] = circlePaths[2].slice(0);
  55614. circlePaths[index] = circlePaths[index - 1].slice(0);
  55615. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55616. break;
  55617. default:
  55618. break;
  55619. }
  55620. return circlePaths;
  55621. };
  55622. var path3D;
  55623. var pathArray;
  55624. if (instance) {
  55625. var arc = options.arc || instance.arc;
  55626. path3D = (instance.path3D).update(path);
  55627. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55628. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55629. instance.path3D = path3D;
  55630. instance.pathArray = pathArray;
  55631. instance.arc = arc;
  55632. instance.radius = radius;
  55633. return instance;
  55634. }
  55635. // tube creation
  55636. path3D = new BABYLON.Path3D(path);
  55637. var newPathArray = new Array();
  55638. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55639. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55640. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55641. tube.pathArray = pathArray;
  55642. tube.path3D = path3D;
  55643. tube.tessellation = tessellation;
  55644. tube.cap = cap;
  55645. tube.arc = options.arc;
  55646. tube.radius = radius;
  55647. return tube;
  55648. };
  55649. /**
  55650. * Creates a polyhedron mesh.
  55651. *
  55652. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55653. * 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
  55654. * to choose the wanted type.
  55655. * The parameter `size` (positive float, default 1) sets the polygon size.
  55656. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55657. * 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`.
  55658. * 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
  55659. * 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)`).
  55660. * 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
  55661. * 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.
  55662. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55663. * 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).
  55664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55666. */
  55667. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55668. var polyhedron = new BABYLON.Mesh(name, scene);
  55669. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55670. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55671. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55672. vertexData.applyToMesh(polyhedron, options.updatable);
  55673. return polyhedron;
  55674. };
  55675. /**
  55676. * Creates a decal mesh.
  55677. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55678. * 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.
  55679. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55680. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55681. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55682. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55683. */
  55684. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55685. var indices = sourceMesh.getIndices();
  55686. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55687. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55688. var position = options.position || BABYLON.Vector3.Zero();
  55689. var normal = options.normal || BABYLON.Vector3.Up();
  55690. var size = options.size || BABYLON.Vector3.One();
  55691. var angle = options.angle || 0;
  55692. // Getting correct rotation
  55693. if (!normal) {
  55694. var target = new BABYLON.Vector3(0, 0, 1);
  55695. var camera = sourceMesh.getScene().activeCamera;
  55696. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55697. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55698. }
  55699. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55700. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55701. var pitch = Math.atan2(normal.y, len);
  55702. // Matrix
  55703. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55704. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55705. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55706. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55707. var vertexData = new BABYLON.VertexData();
  55708. vertexData.indices = [];
  55709. vertexData.positions = [];
  55710. vertexData.normals = [];
  55711. vertexData.uvs = [];
  55712. var currentVertexDataIndex = 0;
  55713. var extractDecalVector3 = function (indexId) {
  55714. var result = new BABYLON.PositionNormalVertex();
  55715. if (!indices || !positions || !normals) {
  55716. return result;
  55717. }
  55718. var vertexId = indices[indexId];
  55719. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55720. // Send vector to decal local world
  55721. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55722. // Get normal
  55723. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55724. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55725. return result;
  55726. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55727. var clip = function (vertices, axis) {
  55728. if (vertices.length === 0) {
  55729. return vertices;
  55730. }
  55731. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55732. var clipVertices = function (v0, v1) {
  55733. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55734. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55735. };
  55736. var result = new Array();
  55737. for (var index = 0; index < vertices.length; index += 3) {
  55738. var v1Out;
  55739. var v2Out;
  55740. var v3Out;
  55741. var total = 0;
  55742. var nV1 = null;
  55743. var nV2 = null;
  55744. var nV3 = null;
  55745. var nV4 = null;
  55746. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55747. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55748. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55749. v1Out = d1 > 0;
  55750. v2Out = d2 > 0;
  55751. v3Out = d3 > 0;
  55752. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55753. switch (total) {
  55754. case 0:
  55755. result.push(vertices[index]);
  55756. result.push(vertices[index + 1]);
  55757. result.push(vertices[index + 2]);
  55758. break;
  55759. case 1:
  55760. if (v1Out) {
  55761. nV1 = vertices[index + 1];
  55762. nV2 = vertices[index + 2];
  55763. nV3 = clipVertices(vertices[index], nV1);
  55764. nV4 = clipVertices(vertices[index], nV2);
  55765. }
  55766. if (v2Out) {
  55767. nV1 = vertices[index];
  55768. nV2 = vertices[index + 2];
  55769. nV3 = clipVertices(vertices[index + 1], nV1);
  55770. nV4 = clipVertices(vertices[index + 1], nV2);
  55771. result.push(nV3);
  55772. result.push(nV2.clone());
  55773. result.push(nV1.clone());
  55774. result.push(nV2.clone());
  55775. result.push(nV3.clone());
  55776. result.push(nV4);
  55777. break;
  55778. }
  55779. if (v3Out) {
  55780. nV1 = vertices[index];
  55781. nV2 = vertices[index + 1];
  55782. nV3 = clipVertices(vertices[index + 2], nV1);
  55783. nV4 = clipVertices(vertices[index + 2], nV2);
  55784. }
  55785. if (nV1 && nV2 && nV3 && nV4) {
  55786. result.push(nV1.clone());
  55787. result.push(nV2.clone());
  55788. result.push(nV3);
  55789. result.push(nV4);
  55790. result.push(nV3.clone());
  55791. result.push(nV2.clone());
  55792. }
  55793. break;
  55794. case 2:
  55795. if (!v1Out) {
  55796. nV1 = vertices[index].clone();
  55797. nV2 = clipVertices(nV1, vertices[index + 1]);
  55798. nV3 = clipVertices(nV1, vertices[index + 2]);
  55799. result.push(nV1);
  55800. result.push(nV2);
  55801. result.push(nV3);
  55802. }
  55803. if (!v2Out) {
  55804. nV1 = vertices[index + 1].clone();
  55805. nV2 = clipVertices(nV1, vertices[index + 2]);
  55806. nV3 = clipVertices(nV1, vertices[index]);
  55807. result.push(nV1);
  55808. result.push(nV2);
  55809. result.push(nV3);
  55810. }
  55811. if (!v3Out) {
  55812. nV1 = vertices[index + 2].clone();
  55813. nV2 = clipVertices(nV1, vertices[index]);
  55814. nV3 = clipVertices(nV1, vertices[index + 1]);
  55815. result.push(nV1);
  55816. result.push(nV2);
  55817. result.push(nV3);
  55818. }
  55819. break;
  55820. case 3:
  55821. break;
  55822. }
  55823. }
  55824. return result;
  55825. };
  55826. for (var index = 0; index < indices.length; index += 3) {
  55827. var faceVertices = new Array();
  55828. faceVertices.push(extractDecalVector3(index));
  55829. faceVertices.push(extractDecalVector3(index + 1));
  55830. faceVertices.push(extractDecalVector3(index + 2));
  55831. // Clip
  55832. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55833. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55834. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55835. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55836. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55837. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55838. if (faceVertices.length === 0) {
  55839. continue;
  55840. }
  55841. // Add UVs and get back to world
  55842. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55843. var vertex = faceVertices[vIndex];
  55844. //TODO check for Int32Array | Uint32Array | Uint16Array
  55845. vertexData.indices.push(currentVertexDataIndex);
  55846. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55847. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55848. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55849. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55850. currentVertexDataIndex++;
  55851. }
  55852. }
  55853. // Return mesh
  55854. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55855. vertexData.applyToMesh(decal);
  55856. decal.position = position.clone();
  55857. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55858. return decal;
  55859. };
  55860. // Privates
  55861. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55862. // extrusion geometry
  55863. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55864. var tangents = path3D.getTangents();
  55865. var normals = path3D.getNormals();
  55866. var binormals = path3D.getBinormals();
  55867. var distances = path3D.getDistances();
  55868. var angle = 0;
  55869. var returnScale = function () { return scale !== null ? scale : 1; };
  55870. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55871. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55872. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55873. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55874. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55875. for (var i = 0; i < curve.length; i++) {
  55876. var shapePath = new Array();
  55877. var angleStep = rotate(i, distances[i]);
  55878. var scaleRatio = scl(i, distances[i]);
  55879. for (var p = 0; p < shape.length; p++) {
  55880. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55881. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55882. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55883. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55884. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55885. shapePath[p] = rotated;
  55886. }
  55887. shapePaths[index] = shapePath;
  55888. angle += angleStep;
  55889. index++;
  55890. }
  55891. // cap
  55892. var capPath = function (shapePath) {
  55893. var pointCap = Array();
  55894. var barycenter = BABYLON.Vector3.Zero();
  55895. var i;
  55896. for (i = 0; i < shapePath.length; i++) {
  55897. barycenter.addInPlace(shapePath[i]);
  55898. }
  55899. barycenter.scaleInPlace(1.0 / shapePath.length);
  55900. for (i = 0; i < shapePath.length; i++) {
  55901. pointCap.push(barycenter);
  55902. }
  55903. return pointCap;
  55904. };
  55905. switch (cap) {
  55906. case BABYLON.Mesh.NO_CAP:
  55907. break;
  55908. case BABYLON.Mesh.CAP_START:
  55909. shapePaths[0] = capPath(shapePaths[2]);
  55910. shapePaths[1] = shapePaths[2];
  55911. break;
  55912. case BABYLON.Mesh.CAP_END:
  55913. shapePaths[index] = shapePaths[index - 1];
  55914. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55915. break;
  55916. case BABYLON.Mesh.CAP_ALL:
  55917. shapePaths[0] = capPath(shapePaths[2]);
  55918. shapePaths[1] = shapePaths[2];
  55919. shapePaths[index] = shapePaths[index - 1];
  55920. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55921. break;
  55922. default:
  55923. break;
  55924. }
  55925. return shapePaths;
  55926. };
  55927. var path3D;
  55928. var pathArray;
  55929. if (instance) {
  55930. path3D = (instance.path3D).update(curve);
  55931. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55932. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55933. return instance;
  55934. }
  55935. // extruded shape creation
  55936. path3D = new BABYLON.Path3D(curve);
  55937. var newShapePaths = new Array();
  55938. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55939. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55940. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55941. extrudedGeneric.pathArray = pathArray;
  55942. extrudedGeneric.path3D = path3D;
  55943. extrudedGeneric.cap = cap;
  55944. return extrudedGeneric;
  55945. };
  55946. return MeshBuilder;
  55947. }());
  55948. BABYLON.MeshBuilder = MeshBuilder;
  55949. })(BABYLON || (BABYLON = {}));
  55950. //# sourceMappingURL=babylon.meshBuilder.js.map
  55951. var BABYLON;
  55952. (function (BABYLON) {
  55953. /**
  55954. * Draco compression (https://google.github.io/draco/)
  55955. */
  55956. var DracoCompression = /** @class */ (function () {
  55957. /**
  55958. * Constructor
  55959. * @param numWorkers The number of workers for async operations
  55960. */
  55961. function DracoCompression(numWorkers) {
  55962. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55963. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55964. if (!workerBlobUrl || !Worker) {
  55965. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  55966. return;
  55967. }
  55968. var workers = new Array(numWorkers);
  55969. for (var i = 0; i < workers.length; i++) {
  55970. var worker = new Worker(workerBlobUrl);
  55971. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55972. workers[i] = worker;
  55973. }
  55974. this._workerPool = new BABYLON.WorkerPool(workers);
  55975. }
  55976. /**
  55977. * Stop all async operations and release resources.
  55978. */
  55979. DracoCompression.prototype.dispose = function () {
  55980. this._workerPool.dispose();
  55981. delete this._workerPool;
  55982. };
  55983. /**
  55984. * Decode Draco compressed mesh data to vertex data.
  55985. * @param data The array buffer view for the Draco compression data
  55986. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55987. * @returns A promise that resolves with the decoded vertex data
  55988. */
  55989. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55990. var _this = this;
  55991. return new Promise(function (resolve, reject) {
  55992. _this._workerPool.push(function (worker, onComplete) {
  55993. var vertexData = new BABYLON.VertexData();
  55994. var onError = function (error) {
  55995. worker.removeEventListener("error", onError);
  55996. worker.removeEventListener("message", onMessage);
  55997. reject(error);
  55998. onComplete();
  55999. };
  56000. var onMessage = function (message) {
  56001. if (message.data === "done") {
  56002. worker.removeEventListener("error", onError);
  56003. worker.removeEventListener("message", onMessage);
  56004. resolve(vertexData);
  56005. onComplete();
  56006. }
  56007. else if (message.data.id === "indices") {
  56008. vertexData.indices = message.data.value;
  56009. }
  56010. else {
  56011. vertexData.set(message.data.value, message.data.id);
  56012. }
  56013. };
  56014. worker.addEventListener("error", onError);
  56015. worker.addEventListener("message", onMessage);
  56016. var dataCopy = new Uint8Array(data.byteLength);
  56017. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56018. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56019. });
  56020. });
  56021. };
  56022. /**
  56023. * The worker function that gets converted to a blob url to pass into a worker.
  56024. */
  56025. DracoCompression._Worker = function () {
  56026. // self is actually a DedicatedWorkerGlobalScope
  56027. var _self = self;
  56028. var decodeMesh = function (data, attributes) {
  56029. var dracoModule = new DracoDecoderModule();
  56030. var buffer = new dracoModule.DecoderBuffer();
  56031. buffer.Init(data, data.byteLength);
  56032. var decoder = new dracoModule.Decoder();
  56033. var geometry;
  56034. var status;
  56035. try {
  56036. var type = decoder.GetEncodedGeometryType(buffer);
  56037. switch (type) {
  56038. case dracoModule.TRIANGULAR_MESH:
  56039. geometry = new dracoModule.Mesh();
  56040. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56041. break;
  56042. case dracoModule.POINT_CLOUD:
  56043. geometry = new dracoModule.PointCloud();
  56044. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56045. break;
  56046. default:
  56047. throw new Error("Invalid geometry type " + type);
  56048. }
  56049. if (!status.ok() || !geometry.ptr) {
  56050. throw new Error(status.error_msg());
  56051. }
  56052. var numPoints = geometry.num_points();
  56053. if (type === dracoModule.TRIANGULAR_MESH) {
  56054. var numFaces = geometry.num_faces();
  56055. var faceIndices = new dracoModule.DracoInt32Array();
  56056. try {
  56057. var indices = new Uint32Array(numFaces * 3);
  56058. for (var i = 0; i < numFaces; i++) {
  56059. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56060. var offset = i * 3;
  56061. indices[offset + 0] = faceIndices.GetValue(0);
  56062. indices[offset + 1] = faceIndices.GetValue(1);
  56063. indices[offset + 2] = faceIndices.GetValue(2);
  56064. }
  56065. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56066. }
  56067. finally {
  56068. dracoModule.destroy(faceIndices);
  56069. }
  56070. }
  56071. for (var kind in attributes) {
  56072. var uniqueId = attributes[kind];
  56073. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56074. var dracoData = new dracoModule.DracoFloat32Array();
  56075. try {
  56076. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56077. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56078. for (var i = 0; i < babylonData.length; i++) {
  56079. babylonData[i] = dracoData.GetValue(i);
  56080. }
  56081. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56082. }
  56083. finally {
  56084. dracoModule.destroy(dracoData);
  56085. }
  56086. }
  56087. }
  56088. finally {
  56089. if (geometry) {
  56090. dracoModule.destroy(geometry);
  56091. }
  56092. dracoModule.destroy(decoder);
  56093. dracoModule.destroy(buffer);
  56094. }
  56095. _self.postMessage("done");
  56096. };
  56097. _self.onmessage = function (event) {
  56098. switch (event.data.id) {
  56099. case "initDecoder": {
  56100. importScripts(event.data.url);
  56101. break;
  56102. }
  56103. case "decodeMesh": {
  56104. decodeMesh(event.data.data, event.data.attributes);
  56105. break;
  56106. }
  56107. }
  56108. };
  56109. };
  56110. DracoCompression._GetDefaultDecoderUrl = function () {
  56111. if (!BABYLON.Tools.IsWindowObjectExist) {
  56112. return null;
  56113. }
  56114. for (var i = 0; i < document.scripts.length; i++) {
  56115. if (document.scripts[i].type === "text/x-draco-decoder") {
  56116. return document.scripts[i].src;
  56117. }
  56118. }
  56119. return null;
  56120. };
  56121. /**
  56122. * Gets the url to the draco decoder if available.
  56123. */
  56124. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56125. return DracoCompression;
  56126. }());
  56127. BABYLON.DracoCompression = DracoCompression;
  56128. })(BABYLON || (BABYLON = {}));
  56129. //# sourceMappingURL=babylon.dracoCompression.js.map
  56130. var BABYLON;
  56131. (function (BABYLON) {
  56132. var AudioEngine = /** @class */ (function () {
  56133. function AudioEngine() {
  56134. this._audioContext = null;
  56135. this._audioContextInitialized = false;
  56136. this.canUseWebAudio = false;
  56137. this.WarnedWebAudioUnsupported = false;
  56138. this.unlocked = false;
  56139. this.isMP3supported = false;
  56140. this.isOGGsupported = false;
  56141. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56142. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56143. this.canUseWebAudio = true;
  56144. }
  56145. var audioElem = document.createElement('audio');
  56146. try {
  56147. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56148. this.isMP3supported = true;
  56149. }
  56150. }
  56151. catch (e) {
  56152. // protect error during capability check.
  56153. }
  56154. try {
  56155. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56156. this.isOGGsupported = true;
  56157. }
  56158. }
  56159. catch (e) {
  56160. // protect error during capability check.
  56161. }
  56162. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56163. this._unlockiOSaudio();
  56164. }
  56165. else {
  56166. this.unlocked = true;
  56167. }
  56168. }
  56169. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56170. get: function () {
  56171. if (!this._audioContextInitialized) {
  56172. this._initializeAudioContext();
  56173. }
  56174. return this._audioContext;
  56175. },
  56176. enumerable: true,
  56177. configurable: true
  56178. });
  56179. AudioEngine.prototype._unlockiOSaudio = function () {
  56180. var _this = this;
  56181. var unlockaudio = function () {
  56182. if (!_this.audioContext) {
  56183. return;
  56184. }
  56185. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56186. var source = _this.audioContext.createBufferSource();
  56187. source.buffer = buffer;
  56188. source.connect(_this.audioContext.destination);
  56189. source.start(0);
  56190. setTimeout(function () {
  56191. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56192. _this.unlocked = true;
  56193. window.removeEventListener('touchend', unlockaudio, false);
  56194. if (_this.onAudioUnlocked) {
  56195. _this.onAudioUnlocked();
  56196. }
  56197. }
  56198. }, 0);
  56199. };
  56200. window.addEventListener('touchend', unlockaudio, false);
  56201. };
  56202. AudioEngine.prototype._initializeAudioContext = function () {
  56203. try {
  56204. if (this.canUseWebAudio) {
  56205. this._audioContext = new AudioContext();
  56206. // create a global volume gain node
  56207. this.masterGain = this._audioContext.createGain();
  56208. this.masterGain.gain.value = 1;
  56209. this.masterGain.connect(this._audioContext.destination);
  56210. this._audioContextInitialized = true;
  56211. }
  56212. }
  56213. catch (e) {
  56214. this.canUseWebAudio = false;
  56215. BABYLON.Tools.Error("Web Audio: " + e.message);
  56216. }
  56217. };
  56218. AudioEngine.prototype.dispose = function () {
  56219. if (this.canUseWebAudio && this._audioContextInitialized) {
  56220. if (this._connectedAnalyser && this._audioContext) {
  56221. this._connectedAnalyser.stopDebugCanvas();
  56222. this._connectedAnalyser.dispose();
  56223. this.masterGain.disconnect();
  56224. this.masterGain.connect(this._audioContext.destination);
  56225. this._connectedAnalyser = null;
  56226. }
  56227. this.masterGain.gain.value = 1;
  56228. }
  56229. this.WarnedWebAudioUnsupported = false;
  56230. };
  56231. AudioEngine.prototype.getGlobalVolume = function () {
  56232. if (this.canUseWebAudio && this._audioContextInitialized) {
  56233. return this.masterGain.gain.value;
  56234. }
  56235. else {
  56236. return -1;
  56237. }
  56238. };
  56239. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56240. if (this.canUseWebAudio && this._audioContextInitialized) {
  56241. this.masterGain.gain.value = newVolume;
  56242. }
  56243. };
  56244. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56245. if (this._connectedAnalyser) {
  56246. this._connectedAnalyser.stopDebugCanvas();
  56247. }
  56248. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56249. this._connectedAnalyser = analyser;
  56250. this.masterGain.disconnect();
  56251. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56252. }
  56253. };
  56254. return AudioEngine;
  56255. }());
  56256. BABYLON.AudioEngine = AudioEngine;
  56257. })(BABYLON || (BABYLON = {}));
  56258. //# sourceMappingURL=babylon.audioEngine.js.map
  56259. var BABYLON;
  56260. (function (BABYLON) {
  56261. var Sound = /** @class */ (function () {
  56262. /**
  56263. * Create a sound and attach it to a scene
  56264. * @param name Name of your sound
  56265. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56266. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56267. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56268. */
  56269. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56270. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56271. var _this = this;
  56272. this.autoplay = false;
  56273. this.loop = false;
  56274. this.useCustomAttenuation = false;
  56275. this.spatialSound = false;
  56276. this.refDistance = 1;
  56277. this.rolloffFactor = 1;
  56278. this.maxDistance = 100;
  56279. this.distanceModel = "linear";
  56280. this._panningModel = "equalpower";
  56281. this._playbackRate = 1;
  56282. this._streaming = false;
  56283. this._startTime = 0;
  56284. this._startOffset = 0;
  56285. this._position = BABYLON.Vector3.Zero();
  56286. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56287. this._volume = 1;
  56288. this._isReadyToPlay = false;
  56289. this.isPlaying = false;
  56290. this.isPaused = false;
  56291. this._isDirectional = false;
  56292. // Used if you'd like to create a directional sound.
  56293. // If not set, the sound will be omnidirectional
  56294. this._coneInnerAngle = 360;
  56295. this._coneOuterAngle = 360;
  56296. this._coneOuterGain = 0;
  56297. this._isOutputConnected = false;
  56298. this._urlType = "Unknown";
  56299. this.name = name;
  56300. this._scene = scene;
  56301. this._readyToPlayCallback = readyToPlayCallback;
  56302. // Default custom attenuation function is a linear attenuation
  56303. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56304. if (currentDistance < maxDistance) {
  56305. return currentVolume * (1 - currentDistance / maxDistance);
  56306. }
  56307. else {
  56308. return 0;
  56309. }
  56310. };
  56311. if (options) {
  56312. this.autoplay = options.autoplay || false;
  56313. this.loop = options.loop || false;
  56314. // if volume === 0, we need another way to check this option
  56315. if (options.volume !== undefined) {
  56316. this._volume = options.volume;
  56317. }
  56318. this.spatialSound = options.spatialSound || false;
  56319. this.maxDistance = options.maxDistance || 100;
  56320. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56321. this.rolloffFactor = options.rolloffFactor || 1;
  56322. this.refDistance = options.refDistance || 1;
  56323. this.distanceModel = options.distanceModel || "linear";
  56324. this._playbackRate = options.playbackRate || 1;
  56325. this._streaming = options.streaming || false;
  56326. }
  56327. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56328. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56329. this._soundGain.gain.value = this._volume;
  56330. this._inputAudioNode = this._soundGain;
  56331. this._ouputAudioNode = this._soundGain;
  56332. if (this.spatialSound) {
  56333. this._createSpatialParameters();
  56334. }
  56335. this._scene.mainSoundTrack.AddSound(this);
  56336. var validParameter = true;
  56337. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56338. if (urlOrArrayBuffer) {
  56339. if (typeof (urlOrArrayBuffer) === "string")
  56340. this._urlType = "String";
  56341. if (Array.isArray(urlOrArrayBuffer))
  56342. this._urlType = "Array";
  56343. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56344. this._urlType = "ArrayBuffer";
  56345. var urls = [];
  56346. var codecSupportedFound = false;
  56347. switch (this._urlType) {
  56348. case "ArrayBuffer":
  56349. if (urlOrArrayBuffer.byteLength > 0) {
  56350. codecSupportedFound = true;
  56351. this._soundLoaded(urlOrArrayBuffer);
  56352. }
  56353. break;
  56354. case "String":
  56355. urls.push(urlOrArrayBuffer);
  56356. case "Array":
  56357. if (urls.length === 0)
  56358. urls = urlOrArrayBuffer;
  56359. // If we found a supported format, we load it immediately and stop the loop
  56360. for (var i = 0; i < urls.length; i++) {
  56361. var url = urls[i];
  56362. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56363. codecSupportedFound = true;
  56364. }
  56365. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56366. codecSupportedFound = true;
  56367. }
  56368. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56369. codecSupportedFound = true;
  56370. }
  56371. if (url.indexOf("blob:") !== -1) {
  56372. codecSupportedFound = true;
  56373. }
  56374. if (codecSupportedFound) {
  56375. // Loading sound using XHR2
  56376. if (!this._streaming) {
  56377. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56378. }
  56379. else {
  56380. this._htmlAudioElement = new Audio(url);
  56381. this._htmlAudioElement.controls = false;
  56382. this._htmlAudioElement.loop = this.loop;
  56383. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56384. this._htmlAudioElement.preload = "auto";
  56385. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56386. _this._isReadyToPlay = true;
  56387. if (_this.autoplay) {
  56388. _this.play();
  56389. }
  56390. if (_this._readyToPlayCallback) {
  56391. _this._readyToPlayCallback();
  56392. }
  56393. });
  56394. document.body.appendChild(this._htmlAudioElement);
  56395. }
  56396. break;
  56397. }
  56398. }
  56399. break;
  56400. default:
  56401. validParameter = false;
  56402. break;
  56403. }
  56404. if (!validParameter) {
  56405. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56406. }
  56407. else {
  56408. if (!codecSupportedFound) {
  56409. this._isReadyToPlay = true;
  56410. // Simulating a ready to play event to avoid breaking code path
  56411. if (this._readyToPlayCallback) {
  56412. window.setTimeout(function () {
  56413. if (_this._readyToPlayCallback) {
  56414. _this._readyToPlayCallback();
  56415. }
  56416. }, 1000);
  56417. }
  56418. }
  56419. }
  56420. }
  56421. }
  56422. else {
  56423. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56424. this._scene.mainSoundTrack.AddSound(this);
  56425. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56426. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56427. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56428. }
  56429. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56430. if (this._readyToPlayCallback) {
  56431. window.setTimeout(function () {
  56432. if (_this._readyToPlayCallback) {
  56433. _this._readyToPlayCallback();
  56434. }
  56435. }, 1000);
  56436. }
  56437. }
  56438. }
  56439. Sound.prototype.dispose = function () {
  56440. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56441. if (this.isPlaying) {
  56442. this.stop();
  56443. }
  56444. this._isReadyToPlay = false;
  56445. if (this.soundTrackId === -1) {
  56446. this._scene.mainSoundTrack.RemoveSound(this);
  56447. }
  56448. else {
  56449. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56450. }
  56451. if (this._soundGain) {
  56452. this._soundGain.disconnect();
  56453. this._soundGain = null;
  56454. }
  56455. if (this._soundPanner) {
  56456. this._soundPanner.disconnect();
  56457. this._soundPanner = null;
  56458. }
  56459. if (this._soundSource) {
  56460. this._soundSource.disconnect();
  56461. this._soundSource = null;
  56462. }
  56463. this._audioBuffer = null;
  56464. if (this._htmlAudioElement) {
  56465. this._htmlAudioElement.pause();
  56466. this._htmlAudioElement.src = "";
  56467. document.body.removeChild(this._htmlAudioElement);
  56468. }
  56469. if (this._connectedMesh && this._registerFunc) {
  56470. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56471. this._connectedMesh = null;
  56472. }
  56473. }
  56474. };
  56475. Sound.prototype.isReady = function () {
  56476. return this._isReadyToPlay;
  56477. };
  56478. Sound.prototype._soundLoaded = function (audioData) {
  56479. var _this = this;
  56480. if (!BABYLON.Engine.audioEngine.audioContext) {
  56481. return;
  56482. }
  56483. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56484. _this._audioBuffer = buffer;
  56485. _this._isReadyToPlay = true;
  56486. if (_this.autoplay) {
  56487. _this.play();
  56488. }
  56489. if (_this._readyToPlayCallback) {
  56490. _this._readyToPlayCallback();
  56491. }
  56492. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56493. };
  56494. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56496. this._audioBuffer = audioBuffer;
  56497. this._isReadyToPlay = true;
  56498. }
  56499. };
  56500. Sound.prototype.updateOptions = function (options) {
  56501. if (options) {
  56502. this.loop = options.loop || this.loop;
  56503. this.maxDistance = options.maxDistance || this.maxDistance;
  56504. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56505. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56506. this.refDistance = options.refDistance || this.refDistance;
  56507. this.distanceModel = options.distanceModel || this.distanceModel;
  56508. this._playbackRate = options.playbackRate || this._playbackRate;
  56509. this._updateSpatialParameters();
  56510. if (this.isPlaying) {
  56511. if (this._streaming) {
  56512. this._htmlAudioElement.playbackRate = this._playbackRate;
  56513. }
  56514. else {
  56515. if (this._soundSource) {
  56516. this._soundSource.playbackRate.value = this._playbackRate;
  56517. }
  56518. }
  56519. }
  56520. }
  56521. };
  56522. Sound.prototype._createSpatialParameters = function () {
  56523. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56524. if (this._scene.headphone) {
  56525. this._panningModel = "HRTF";
  56526. }
  56527. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56528. this._updateSpatialParameters();
  56529. this._soundPanner.connect(this._ouputAudioNode);
  56530. this._inputAudioNode = this._soundPanner;
  56531. }
  56532. };
  56533. Sound.prototype._updateSpatialParameters = function () {
  56534. if (this.spatialSound && this._soundPanner) {
  56535. if (this.useCustomAttenuation) {
  56536. // Tricks to disable in a way embedded Web Audio attenuation
  56537. this._soundPanner.distanceModel = "linear";
  56538. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56539. this._soundPanner.refDistance = 1;
  56540. this._soundPanner.rolloffFactor = 1;
  56541. this._soundPanner.panningModel = this._panningModel;
  56542. }
  56543. else {
  56544. this._soundPanner.distanceModel = this.distanceModel;
  56545. this._soundPanner.maxDistance = this.maxDistance;
  56546. this._soundPanner.refDistance = this.refDistance;
  56547. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56548. this._soundPanner.panningModel = this._panningModel;
  56549. }
  56550. }
  56551. };
  56552. Sound.prototype.switchPanningModelToHRTF = function () {
  56553. this._panningModel = "HRTF";
  56554. this._switchPanningModel();
  56555. };
  56556. Sound.prototype.switchPanningModelToEqualPower = function () {
  56557. this._panningModel = "equalpower";
  56558. this._switchPanningModel();
  56559. };
  56560. Sound.prototype._switchPanningModel = function () {
  56561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56562. this._soundPanner.panningModel = this._panningModel;
  56563. }
  56564. };
  56565. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56567. if (this._isOutputConnected) {
  56568. this._ouputAudioNode.disconnect();
  56569. }
  56570. this._ouputAudioNode.connect(soundTrackAudioNode);
  56571. this._isOutputConnected = true;
  56572. }
  56573. };
  56574. /**
  56575. * Transform this sound into a directional source
  56576. * @param coneInnerAngle Size of the inner cone in degree
  56577. * @param coneOuterAngle Size of the outer cone in degree
  56578. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56579. */
  56580. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56581. if (coneOuterAngle < coneInnerAngle) {
  56582. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56583. return;
  56584. }
  56585. this._coneInnerAngle = coneInnerAngle;
  56586. this._coneOuterAngle = coneOuterAngle;
  56587. this._coneOuterGain = coneOuterGain;
  56588. this._isDirectional = true;
  56589. if (this.isPlaying && this.loop) {
  56590. this.stop();
  56591. this.play();
  56592. }
  56593. };
  56594. Sound.prototype.setPosition = function (newPosition) {
  56595. this._position = newPosition;
  56596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56597. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56598. }
  56599. };
  56600. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56601. this._localDirection = newLocalDirection;
  56602. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56603. this._updateDirection();
  56604. }
  56605. };
  56606. Sound.prototype._updateDirection = function () {
  56607. if (!this._connectedMesh || !this._soundPanner) {
  56608. return;
  56609. }
  56610. var mat = this._connectedMesh.getWorldMatrix();
  56611. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56612. direction.normalize();
  56613. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56614. };
  56615. Sound.prototype.updateDistanceFromListener = function () {
  56616. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56617. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56618. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56619. }
  56620. };
  56621. Sound.prototype.setAttenuationFunction = function (callback) {
  56622. this._customAttenuationFunction = callback;
  56623. };
  56624. /**
  56625. * Play the sound
  56626. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56627. * @param offset (optional) Start the sound setting it at a specific time
  56628. */
  56629. Sound.prototype.play = function (time, offset) {
  56630. var _this = this;
  56631. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56632. try {
  56633. if (this._startOffset < 0) {
  56634. time = -this._startOffset;
  56635. this._startOffset = 0;
  56636. }
  56637. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56638. if (!this._soundSource || !this._streamingSource) {
  56639. if (this.spatialSound && this._soundPanner) {
  56640. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56641. if (this._isDirectional) {
  56642. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56643. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56644. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56645. if (this._connectedMesh) {
  56646. this._updateDirection();
  56647. }
  56648. else {
  56649. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56650. }
  56651. }
  56652. }
  56653. }
  56654. if (this._streaming) {
  56655. if (!this._streamingSource) {
  56656. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56657. this._htmlAudioElement.onended = function () { _this._onended(); };
  56658. this._htmlAudioElement.playbackRate = this._playbackRate;
  56659. }
  56660. this._streamingSource.disconnect();
  56661. this._streamingSource.connect(this._inputAudioNode);
  56662. this._htmlAudioElement.play();
  56663. }
  56664. else {
  56665. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56666. this._soundSource.buffer = this._audioBuffer;
  56667. this._soundSource.connect(this._inputAudioNode);
  56668. this._soundSource.loop = this.loop;
  56669. this._soundSource.playbackRate.value = this._playbackRate;
  56670. this._soundSource.onended = function () { _this._onended(); };
  56671. if (this._soundSource.buffer) {
  56672. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56673. }
  56674. }
  56675. this._startTime = startTime;
  56676. this.isPlaying = true;
  56677. this.isPaused = false;
  56678. }
  56679. catch (ex) {
  56680. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56681. }
  56682. }
  56683. };
  56684. Sound.prototype._onended = function () {
  56685. this.isPlaying = false;
  56686. if (this.onended) {
  56687. this.onended();
  56688. }
  56689. };
  56690. /**
  56691. * Stop the sound
  56692. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56693. */
  56694. Sound.prototype.stop = function (time) {
  56695. if (this.isPlaying) {
  56696. if (this._streaming) {
  56697. this._htmlAudioElement.pause();
  56698. // Test needed for Firefox or it will generate an Invalid State Error
  56699. if (this._htmlAudioElement.currentTime > 0) {
  56700. this._htmlAudioElement.currentTime = 0;
  56701. }
  56702. }
  56703. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56704. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56705. this._soundSource.stop(stopTime);
  56706. this._soundSource.onended = function () { };
  56707. if (!this.isPaused) {
  56708. this._startOffset = 0;
  56709. }
  56710. }
  56711. this.isPlaying = false;
  56712. }
  56713. };
  56714. Sound.prototype.pause = function () {
  56715. if (this.isPlaying) {
  56716. this.isPaused = true;
  56717. if (this._streaming) {
  56718. this._htmlAudioElement.pause();
  56719. }
  56720. else if (BABYLON.Engine.audioEngine.audioContext) {
  56721. this.stop(0);
  56722. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56723. }
  56724. }
  56725. };
  56726. Sound.prototype.setVolume = function (newVolume, time) {
  56727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56728. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56729. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56730. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56731. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56732. }
  56733. else {
  56734. this._soundGain.gain.value = newVolume;
  56735. }
  56736. }
  56737. this._volume = newVolume;
  56738. };
  56739. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56740. this._playbackRate = newPlaybackRate;
  56741. if (this.isPlaying) {
  56742. if (this._streaming) {
  56743. this._htmlAudioElement.playbackRate = this._playbackRate;
  56744. }
  56745. else if (this._soundSource) {
  56746. this._soundSource.playbackRate.value = this._playbackRate;
  56747. }
  56748. }
  56749. };
  56750. Sound.prototype.getVolume = function () {
  56751. return this._volume;
  56752. };
  56753. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56754. var _this = this;
  56755. if (this._connectedMesh && this._registerFunc) {
  56756. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56757. this._registerFunc = null;
  56758. }
  56759. this._connectedMesh = meshToConnectTo;
  56760. if (!this.spatialSound) {
  56761. this.spatialSound = true;
  56762. this._createSpatialParameters();
  56763. if (this.isPlaying && this.loop) {
  56764. this.stop();
  56765. this.play();
  56766. }
  56767. }
  56768. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56769. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56770. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56771. };
  56772. Sound.prototype.detachFromMesh = function () {
  56773. if (this._connectedMesh && this._registerFunc) {
  56774. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56775. this._registerFunc = null;
  56776. this._connectedMesh = null;
  56777. }
  56778. };
  56779. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56780. if (!node.getBoundingInfo) {
  56781. return;
  56782. }
  56783. var mesh = node;
  56784. var boundingInfo = mesh.getBoundingInfo();
  56785. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56787. this._updateDirection();
  56788. }
  56789. };
  56790. Sound.prototype.clone = function () {
  56791. var _this = this;
  56792. if (!this._streaming) {
  56793. var setBufferAndRun = function () {
  56794. if (_this._isReadyToPlay) {
  56795. clonedSound._audioBuffer = _this.getAudioBuffer();
  56796. clonedSound._isReadyToPlay = true;
  56797. if (clonedSound.autoplay) {
  56798. clonedSound.play();
  56799. }
  56800. }
  56801. else {
  56802. window.setTimeout(setBufferAndRun, 300);
  56803. }
  56804. };
  56805. var currentOptions = {
  56806. autoplay: this.autoplay, loop: this.loop,
  56807. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56808. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56809. refDistance: this.refDistance, distanceModel: this.distanceModel
  56810. };
  56811. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56812. if (this.useCustomAttenuation) {
  56813. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56814. }
  56815. clonedSound.setPosition(this._position);
  56816. clonedSound.setPlaybackRate(this._playbackRate);
  56817. setBufferAndRun();
  56818. return clonedSound;
  56819. }
  56820. else {
  56821. return null;
  56822. }
  56823. };
  56824. Sound.prototype.getAudioBuffer = function () {
  56825. return this._audioBuffer;
  56826. };
  56827. Sound.prototype.serialize = function () {
  56828. var serializationObject = {
  56829. name: this.name,
  56830. url: this.name,
  56831. autoplay: this.autoplay,
  56832. loop: this.loop,
  56833. volume: this._volume,
  56834. spatialSound: this.spatialSound,
  56835. maxDistance: this.maxDistance,
  56836. rolloffFactor: this.rolloffFactor,
  56837. refDistance: this.refDistance,
  56838. distanceModel: this.distanceModel,
  56839. playbackRate: this._playbackRate,
  56840. panningModel: this._panningModel,
  56841. soundTrackId: this.soundTrackId
  56842. };
  56843. if (this.spatialSound) {
  56844. if (this._connectedMesh)
  56845. serializationObject.connectedMeshId = this._connectedMesh.id;
  56846. serializationObject.position = this._position.asArray();
  56847. serializationObject.refDistance = this.refDistance;
  56848. serializationObject.distanceModel = this.distanceModel;
  56849. serializationObject.isDirectional = this._isDirectional;
  56850. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56851. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56852. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56853. serializationObject.coneOuterGain = this._coneOuterGain;
  56854. }
  56855. return serializationObject;
  56856. };
  56857. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56858. var soundName = parsedSound.name;
  56859. var soundUrl;
  56860. if (parsedSound.url) {
  56861. soundUrl = rootUrl + parsedSound.url;
  56862. }
  56863. else {
  56864. soundUrl = rootUrl + soundName;
  56865. }
  56866. var options = {
  56867. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56868. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56869. rolloffFactor: parsedSound.rolloffFactor,
  56870. refDistance: parsedSound.refDistance,
  56871. distanceModel: parsedSound.distanceModel,
  56872. playbackRate: parsedSound.playbackRate
  56873. };
  56874. var newSound;
  56875. if (!sourceSound) {
  56876. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56877. scene._addPendingData(newSound);
  56878. }
  56879. else {
  56880. var setBufferAndRun = function () {
  56881. if (sourceSound._isReadyToPlay) {
  56882. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56883. newSound._isReadyToPlay = true;
  56884. if (newSound.autoplay) {
  56885. newSound.play();
  56886. }
  56887. }
  56888. else {
  56889. window.setTimeout(setBufferAndRun, 300);
  56890. }
  56891. };
  56892. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56893. setBufferAndRun();
  56894. }
  56895. if (parsedSound.position) {
  56896. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56897. newSound.setPosition(soundPosition);
  56898. }
  56899. if (parsedSound.isDirectional) {
  56900. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56901. if (parsedSound.localDirectionToMesh) {
  56902. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56903. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56904. }
  56905. }
  56906. if (parsedSound.connectedMeshId) {
  56907. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56908. if (connectedMesh) {
  56909. newSound.attachToMesh(connectedMesh);
  56910. }
  56911. }
  56912. return newSound;
  56913. };
  56914. return Sound;
  56915. }());
  56916. BABYLON.Sound = Sound;
  56917. })(BABYLON || (BABYLON = {}));
  56918. //# sourceMappingURL=babylon.sound.js.map
  56919. var BABYLON;
  56920. (function (BABYLON) {
  56921. var SoundTrack = /** @class */ (function () {
  56922. function SoundTrack(scene, options) {
  56923. this.id = -1;
  56924. this._isMainTrack = false;
  56925. this._isInitialized = false;
  56926. this._scene = scene;
  56927. this.soundCollection = new Array();
  56928. this._options = options;
  56929. if (!this._isMainTrack) {
  56930. this._scene.soundTracks.push(this);
  56931. this.id = this._scene.soundTracks.length - 1;
  56932. }
  56933. }
  56934. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56935. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56936. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56937. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56938. if (this._options) {
  56939. if (this._options.volume) {
  56940. this._outputAudioNode.gain.value = this._options.volume;
  56941. }
  56942. if (this._options.mainTrack) {
  56943. this._isMainTrack = this._options.mainTrack;
  56944. }
  56945. }
  56946. this._isInitialized = true;
  56947. }
  56948. };
  56949. SoundTrack.prototype.dispose = function () {
  56950. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56951. if (this._connectedAnalyser) {
  56952. this._connectedAnalyser.stopDebugCanvas();
  56953. }
  56954. while (this.soundCollection.length) {
  56955. this.soundCollection[0].dispose();
  56956. }
  56957. if (this._outputAudioNode) {
  56958. this._outputAudioNode.disconnect();
  56959. }
  56960. this._outputAudioNode = null;
  56961. }
  56962. };
  56963. SoundTrack.prototype.AddSound = function (sound) {
  56964. if (!this._isInitialized) {
  56965. this._initializeSoundTrackAudioGraph();
  56966. }
  56967. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56968. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56969. }
  56970. if (sound.soundTrackId) {
  56971. if (sound.soundTrackId === -1) {
  56972. this._scene.mainSoundTrack.RemoveSound(sound);
  56973. }
  56974. else {
  56975. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56976. }
  56977. }
  56978. this.soundCollection.push(sound);
  56979. sound.soundTrackId = this.id;
  56980. };
  56981. SoundTrack.prototype.RemoveSound = function (sound) {
  56982. var index = this.soundCollection.indexOf(sound);
  56983. if (index !== -1) {
  56984. this.soundCollection.splice(index, 1);
  56985. }
  56986. };
  56987. SoundTrack.prototype.setVolume = function (newVolume) {
  56988. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56989. this._outputAudioNode.gain.value = newVolume;
  56990. }
  56991. };
  56992. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56994. for (var i = 0; i < this.soundCollection.length; i++) {
  56995. this.soundCollection[i].switchPanningModelToHRTF();
  56996. }
  56997. }
  56998. };
  56999. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57000. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57001. for (var i = 0; i < this.soundCollection.length; i++) {
  57002. this.soundCollection[i].switchPanningModelToEqualPower();
  57003. }
  57004. }
  57005. };
  57006. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57007. if (this._connectedAnalyser) {
  57008. this._connectedAnalyser.stopDebugCanvas();
  57009. }
  57010. this._connectedAnalyser = analyser;
  57011. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57012. this._outputAudioNode.disconnect();
  57013. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57014. }
  57015. };
  57016. return SoundTrack;
  57017. }());
  57018. BABYLON.SoundTrack = SoundTrack;
  57019. })(BABYLON || (BABYLON = {}));
  57020. //# sourceMappingURL=babylon.soundtrack.js.map
  57021. var BABYLON;
  57022. (function (BABYLON) {
  57023. var Analyser = /** @class */ (function () {
  57024. function Analyser(scene) {
  57025. this.SMOOTHING = 0.75;
  57026. this.FFT_SIZE = 512;
  57027. this.BARGRAPHAMPLITUDE = 256;
  57028. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57029. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57030. this._scene = scene;
  57031. this._audioEngine = BABYLON.Engine.audioEngine;
  57032. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57033. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57034. this._webAudioAnalyser.minDecibels = -140;
  57035. this._webAudioAnalyser.maxDecibels = 0;
  57036. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57037. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57038. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57039. }
  57040. }
  57041. Analyser.prototype.getFrequencyBinCount = function () {
  57042. if (this._audioEngine.canUseWebAudio) {
  57043. return this._webAudioAnalyser.frequencyBinCount;
  57044. }
  57045. else {
  57046. return 0;
  57047. }
  57048. };
  57049. Analyser.prototype.getByteFrequencyData = function () {
  57050. if (this._audioEngine.canUseWebAudio) {
  57051. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57052. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57053. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57054. }
  57055. return this._byteFreqs;
  57056. };
  57057. Analyser.prototype.getByteTimeDomainData = function () {
  57058. if (this._audioEngine.canUseWebAudio) {
  57059. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57060. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57061. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57062. }
  57063. return this._byteTime;
  57064. };
  57065. Analyser.prototype.getFloatFrequencyData = function () {
  57066. if (this._audioEngine.canUseWebAudio) {
  57067. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57068. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57069. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57070. }
  57071. return this._floatFreqs;
  57072. };
  57073. Analyser.prototype.drawDebugCanvas = function () {
  57074. var _this = this;
  57075. if (this._audioEngine.canUseWebAudio) {
  57076. if (!this._debugCanvas) {
  57077. this._debugCanvas = document.createElement("canvas");
  57078. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57079. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57080. this._debugCanvas.style.position = "absolute";
  57081. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57082. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57083. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57084. document.body.appendChild(this._debugCanvas);
  57085. this._registerFunc = function () {
  57086. _this.drawDebugCanvas();
  57087. };
  57088. this._scene.registerBeforeRender(this._registerFunc);
  57089. }
  57090. if (this._registerFunc && this._debugCanvasContext) {
  57091. var workingArray = this.getByteFrequencyData();
  57092. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57093. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57094. // Draw the frequency domain chart.
  57095. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57096. var value = workingArray[i];
  57097. var percent = value / this.BARGRAPHAMPLITUDE;
  57098. var height = this.DEBUGCANVASSIZE.height * percent;
  57099. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57100. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57101. var hue = i / this.getFrequencyBinCount() * 360;
  57102. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57103. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57104. }
  57105. }
  57106. }
  57107. };
  57108. Analyser.prototype.stopDebugCanvas = function () {
  57109. if (this._debugCanvas) {
  57110. if (this._registerFunc) {
  57111. this._scene.unregisterBeforeRender(this._registerFunc);
  57112. this._registerFunc = null;
  57113. }
  57114. document.body.removeChild(this._debugCanvas);
  57115. this._debugCanvas = null;
  57116. this._debugCanvasContext = null;
  57117. }
  57118. };
  57119. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57120. if (this._audioEngine.canUseWebAudio) {
  57121. inputAudioNode.connect(this._webAudioAnalyser);
  57122. this._webAudioAnalyser.connect(outputAudioNode);
  57123. }
  57124. };
  57125. Analyser.prototype.dispose = function () {
  57126. if (this._audioEngine.canUseWebAudio) {
  57127. this._webAudioAnalyser.disconnect();
  57128. }
  57129. };
  57130. return Analyser;
  57131. }());
  57132. BABYLON.Analyser = Analyser;
  57133. })(BABYLON || (BABYLON = {}));
  57134. //# sourceMappingURL=babylon.analyser.js.map
  57135. var BABYLON;
  57136. (function (BABYLON) {
  57137. var CubeTexture = /** @class */ (function (_super) {
  57138. __extends(CubeTexture, _super);
  57139. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57140. if (extensions === void 0) { extensions = null; }
  57141. if (noMipmap === void 0) { noMipmap = false; }
  57142. if (files === void 0) { files = null; }
  57143. if (onLoad === void 0) { onLoad = null; }
  57144. if (onError === void 0) { onError = null; }
  57145. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57146. if (prefiltered === void 0) { prefiltered = false; }
  57147. if (forcedExtension === void 0) { forcedExtension = null; }
  57148. var _this = _super.call(this, scene) || this;
  57149. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57150. /**
  57151. * Gets or sets the center of the bounding box associated with the cube texture
  57152. * It must define where the camera used to render the texture was set
  57153. */
  57154. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57155. _this.name = rootUrl;
  57156. _this.url = rootUrl;
  57157. _this._noMipmap = noMipmap;
  57158. _this.hasAlpha = false;
  57159. _this._format = format;
  57160. _this._prefiltered = prefiltered;
  57161. _this.isCube = true;
  57162. _this._textureMatrix = BABYLON.Matrix.Identity();
  57163. if (prefiltered) {
  57164. _this.gammaSpace = false;
  57165. }
  57166. if (!rootUrl && !files) {
  57167. return _this;
  57168. }
  57169. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57170. var lastDot = rootUrl.lastIndexOf(".");
  57171. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57172. var isDDS = (extension === ".dds");
  57173. if (!files) {
  57174. if (!isDDS && !extensions) {
  57175. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57176. }
  57177. files = [];
  57178. if (extensions) {
  57179. for (var index = 0; index < extensions.length; index++) {
  57180. files.push(rootUrl + extensions[index]);
  57181. }
  57182. }
  57183. }
  57184. _this._files = files;
  57185. if (!_this._texture) {
  57186. if (!scene.useDelayedTextureLoading) {
  57187. if (prefiltered) {
  57188. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57189. }
  57190. else {
  57191. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57192. }
  57193. }
  57194. else {
  57195. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57196. }
  57197. }
  57198. else if (onLoad) {
  57199. if (_this._texture.isReady) {
  57200. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57201. }
  57202. else {
  57203. _this._texture.onLoadedObservable.add(onLoad);
  57204. }
  57205. }
  57206. return _this;
  57207. }
  57208. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57209. get: function () {
  57210. return this._boundingBoxSize;
  57211. },
  57212. /**
  57213. * Gets or sets the size of the bounding box associated with the cube texture
  57214. * When defined, the cubemap will switch to local mode
  57215. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57216. * @example https://www.babylonjs-playground.com/#RNASML
  57217. */
  57218. set: function (value) {
  57219. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57220. return;
  57221. }
  57222. this._boundingBoxSize = value;
  57223. var scene = this.getScene();
  57224. if (scene) {
  57225. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57226. }
  57227. },
  57228. enumerable: true,
  57229. configurable: true
  57230. });
  57231. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57232. var rootUrlKey = "";
  57233. files.forEach(function (url) { return rootUrlKey += url; });
  57234. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57235. };
  57236. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57237. if (forcedExtension === void 0) { forcedExtension = null; }
  57238. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57239. };
  57240. // Methods
  57241. CubeTexture.prototype.delayLoad = function () {
  57242. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57243. return;
  57244. }
  57245. var scene = this.getScene();
  57246. if (!scene) {
  57247. return;
  57248. }
  57249. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57250. this._texture = this._getFromCache(this.url, this._noMipmap);
  57251. if (!this._texture) {
  57252. if (this._prefiltered) {
  57253. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57254. }
  57255. else {
  57256. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57257. }
  57258. }
  57259. };
  57260. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57261. return this._textureMatrix;
  57262. };
  57263. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57264. this._textureMatrix = value;
  57265. };
  57266. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57267. var texture = BABYLON.SerializationHelper.Parse(function () {
  57268. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57269. }, parsedTexture, scene);
  57270. // Local Cubemaps
  57271. if (parsedTexture.boundingBoxPosition) {
  57272. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57273. }
  57274. if (parsedTexture.boundingBoxSize) {
  57275. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57276. }
  57277. // Animations
  57278. if (parsedTexture.animations) {
  57279. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57280. var parsedAnimation = parsedTexture.animations[animationIndex];
  57281. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57282. }
  57283. }
  57284. return texture;
  57285. };
  57286. CubeTexture.prototype.clone = function () {
  57287. var _this = this;
  57288. return BABYLON.SerializationHelper.Clone(function () {
  57289. var scene = _this.getScene();
  57290. if (!scene) {
  57291. return _this;
  57292. }
  57293. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57294. }, this);
  57295. };
  57296. return CubeTexture;
  57297. }(BABYLON.BaseTexture));
  57298. BABYLON.CubeTexture = CubeTexture;
  57299. })(BABYLON || (BABYLON = {}));
  57300. //# sourceMappingURL=babylon.cubeTexture.js.map
  57301. var BABYLON;
  57302. (function (BABYLON) {
  57303. var RenderTargetTexture = /** @class */ (function (_super) {
  57304. __extends(RenderTargetTexture, _super);
  57305. /**
  57306. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57307. * or used a shadow, depth texture...
  57308. * @param name The friendly name of the texture
  57309. * @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)
  57310. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57311. * @param generateMipMaps True if mip maps need to be generated after render.
  57312. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57313. * @param type The type of the buffer in the RTT (int, half float, float...)
  57314. * @param isCube True if a cube texture needs to be created
  57315. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57316. * @param generateDepthBuffer True to generate a depth buffer
  57317. * @param generateStencilBuffer True to generate a stencil buffer
  57318. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57319. */
  57320. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57321. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57322. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57323. if (isCube === void 0) { isCube = false; }
  57324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57325. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57326. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57327. if (isMulti === void 0) { isMulti = false; }
  57328. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57329. _this.isCube = isCube;
  57330. /**
  57331. * Use this list to define the list of mesh you want to render.
  57332. */
  57333. _this.renderList = new Array();
  57334. _this.renderParticles = true;
  57335. _this.renderSprites = false;
  57336. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57337. _this.ignoreCameraViewport = false;
  57338. // Events
  57339. /**
  57340. * An event triggered when the texture is unbind.
  57341. * @type {BABYLON.Observable}
  57342. */
  57343. _this.onBeforeBindObservable = new BABYLON.Observable();
  57344. /**
  57345. * An event triggered when the texture is unbind.
  57346. * @type {BABYLON.Observable}
  57347. */
  57348. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57349. /**
  57350. * An event triggered before rendering the texture
  57351. * @type {BABYLON.Observable}
  57352. */
  57353. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57354. /**
  57355. * An event triggered after rendering the texture
  57356. * @type {BABYLON.Observable}
  57357. */
  57358. _this.onAfterRenderObservable = new BABYLON.Observable();
  57359. /**
  57360. * An event triggered after the texture clear
  57361. * @type {BABYLON.Observable}
  57362. */
  57363. _this.onClearObservable = new BABYLON.Observable();
  57364. _this._currentRefreshId = -1;
  57365. _this._refreshRate = 1;
  57366. _this._samples = 1;
  57367. /**
  57368. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57369. * It must define where the camera used to render the texture is set
  57370. */
  57371. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57372. scene = _this.getScene();
  57373. if (!scene) {
  57374. return _this;
  57375. }
  57376. _this._engine = scene.getEngine();
  57377. _this.name = name;
  57378. _this.isRenderTarget = true;
  57379. _this._initialSizeParameter = size;
  57380. _this._processSizeParameter(size);
  57381. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57382. });
  57383. _this._generateMipMaps = generateMipMaps ? true : false;
  57384. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57385. // Rendering groups
  57386. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57387. if (isMulti) {
  57388. return _this;
  57389. }
  57390. _this._renderTargetOptions = {
  57391. generateMipMaps: generateMipMaps,
  57392. type: type,
  57393. samplingMode: samplingMode,
  57394. generateDepthBuffer: generateDepthBuffer,
  57395. generateStencilBuffer: generateStencilBuffer
  57396. };
  57397. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57398. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57399. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57400. }
  57401. if (isCube) {
  57402. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57403. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57404. _this._textureMatrix = BABYLON.Matrix.Identity();
  57405. }
  57406. else {
  57407. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57408. }
  57409. return _this;
  57410. }
  57411. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57412. get: function () {
  57413. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57414. },
  57415. enumerable: true,
  57416. configurable: true
  57417. });
  57418. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57419. get: function () {
  57420. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57426. get: function () {
  57427. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57428. },
  57429. enumerable: true,
  57430. configurable: true
  57431. });
  57432. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57433. set: function (callback) {
  57434. if (this._onAfterUnbindObserver) {
  57435. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57436. }
  57437. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57438. },
  57439. enumerable: true,
  57440. configurable: true
  57441. });
  57442. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57443. set: function (callback) {
  57444. if (this._onBeforeRenderObserver) {
  57445. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57446. }
  57447. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57448. },
  57449. enumerable: true,
  57450. configurable: true
  57451. });
  57452. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57453. set: function (callback) {
  57454. if (this._onAfterRenderObserver) {
  57455. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57456. }
  57457. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57458. },
  57459. enumerable: true,
  57460. configurable: true
  57461. });
  57462. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57463. set: function (callback) {
  57464. if (this._onClearObserver) {
  57465. this.onClearObservable.remove(this._onClearObserver);
  57466. }
  57467. this._onClearObserver = this.onClearObservable.add(callback);
  57468. },
  57469. enumerable: true,
  57470. configurable: true
  57471. });
  57472. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57473. get: function () {
  57474. return this._renderTargetOptions;
  57475. },
  57476. enumerable: true,
  57477. configurable: true
  57478. });
  57479. RenderTargetTexture.prototype._onRatioRescale = function () {
  57480. if (this._sizeRatio) {
  57481. this.resize(this._initialSizeParameter);
  57482. }
  57483. };
  57484. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57485. get: function () {
  57486. return this._boundingBoxSize;
  57487. },
  57488. /**
  57489. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57490. * When defined, the cubemap will switch to local mode
  57491. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57492. * @example https://www.babylonjs-playground.com/#RNASML
  57493. */
  57494. set: function (value) {
  57495. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57496. return;
  57497. }
  57498. this._boundingBoxSize = value;
  57499. var scene = this.getScene();
  57500. if (scene) {
  57501. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57502. }
  57503. },
  57504. enumerable: true,
  57505. configurable: true
  57506. });
  57507. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57508. if (size.ratio) {
  57509. this._sizeRatio = size.ratio;
  57510. this._size = {
  57511. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57512. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57513. };
  57514. }
  57515. else {
  57516. this._size = size;
  57517. }
  57518. };
  57519. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57520. get: function () {
  57521. return this._samples;
  57522. },
  57523. set: function (value) {
  57524. if (this._samples === value) {
  57525. return;
  57526. }
  57527. var scene = this.getScene();
  57528. if (!scene) {
  57529. return;
  57530. }
  57531. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57532. },
  57533. enumerable: true,
  57534. configurable: true
  57535. });
  57536. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57537. this._currentRefreshId = -1;
  57538. };
  57539. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57540. get: function () {
  57541. return this._refreshRate;
  57542. },
  57543. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57544. set: function (value) {
  57545. this._refreshRate = value;
  57546. this.resetRefreshCounter();
  57547. },
  57548. enumerable: true,
  57549. configurable: true
  57550. });
  57551. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57552. if (!this._postProcessManager) {
  57553. var scene = this.getScene();
  57554. if (!scene) {
  57555. return;
  57556. }
  57557. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57558. this._postProcesses = new Array();
  57559. }
  57560. this._postProcesses.push(postProcess);
  57561. this._postProcesses[0].autoClear = false;
  57562. };
  57563. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57564. if (!this._postProcesses) {
  57565. return;
  57566. }
  57567. if (dispose) {
  57568. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57569. var postProcess = _a[_i];
  57570. postProcess.dispose();
  57571. }
  57572. }
  57573. this._postProcesses = [];
  57574. };
  57575. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57576. if (!this._postProcesses) {
  57577. return;
  57578. }
  57579. var index = this._postProcesses.indexOf(postProcess);
  57580. if (index === -1) {
  57581. return;
  57582. }
  57583. this._postProcesses.splice(index, 1);
  57584. if (this._postProcesses.length > 0) {
  57585. this._postProcesses[0].autoClear = false;
  57586. }
  57587. };
  57588. RenderTargetTexture.prototype._shouldRender = function () {
  57589. if (this._currentRefreshId === -1) {
  57590. this._currentRefreshId = 1;
  57591. return true;
  57592. }
  57593. if (this.refreshRate === this._currentRefreshId) {
  57594. this._currentRefreshId = 1;
  57595. return true;
  57596. }
  57597. this._currentRefreshId++;
  57598. return false;
  57599. };
  57600. RenderTargetTexture.prototype.getRenderSize = function () {
  57601. if (this._size.width) {
  57602. return this._size.width;
  57603. }
  57604. return this._size;
  57605. };
  57606. RenderTargetTexture.prototype.getRenderWidth = function () {
  57607. if (this._size.width) {
  57608. return this._size.width;
  57609. }
  57610. return this._size;
  57611. };
  57612. RenderTargetTexture.prototype.getRenderHeight = function () {
  57613. if (this._size.width) {
  57614. return this._size.height;
  57615. }
  57616. return this._size;
  57617. };
  57618. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57619. get: function () {
  57620. return true;
  57621. },
  57622. enumerable: true,
  57623. configurable: true
  57624. });
  57625. RenderTargetTexture.prototype.scale = function (ratio) {
  57626. var newSize = this.getRenderSize() * ratio;
  57627. this.resize(newSize);
  57628. };
  57629. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57630. if (this.isCube) {
  57631. return this._textureMatrix;
  57632. }
  57633. return _super.prototype.getReflectionTextureMatrix.call(this);
  57634. };
  57635. RenderTargetTexture.prototype.resize = function (size) {
  57636. this.releaseInternalTexture();
  57637. var scene = this.getScene();
  57638. if (!scene) {
  57639. return;
  57640. }
  57641. this._processSizeParameter(size);
  57642. if (this.isCube) {
  57643. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57644. }
  57645. else {
  57646. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57647. }
  57648. };
  57649. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57650. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57651. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57652. var scene = this.getScene();
  57653. if (!scene) {
  57654. return;
  57655. }
  57656. var engine = scene.getEngine();
  57657. if (this.useCameraPostProcesses !== undefined) {
  57658. useCameraPostProcess = this.useCameraPostProcesses;
  57659. }
  57660. if (this._waitingRenderList) {
  57661. this.renderList = [];
  57662. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57663. var id = this._waitingRenderList[index];
  57664. var mesh_1 = scene.getMeshByID(id);
  57665. if (mesh_1) {
  57666. this.renderList.push(mesh_1);
  57667. }
  57668. }
  57669. delete this._waitingRenderList;
  57670. }
  57671. // Is predicate defined?
  57672. if (this.renderListPredicate) {
  57673. if (this.renderList) {
  57674. this.renderList.splice(0); // Clear previous renderList
  57675. }
  57676. else {
  57677. this.renderList = [];
  57678. }
  57679. var scene = this.getScene();
  57680. if (!scene) {
  57681. return;
  57682. }
  57683. var sceneMeshes = scene.meshes;
  57684. for (var index = 0; index < sceneMeshes.length; index++) {
  57685. var mesh = sceneMeshes[index];
  57686. if (this.renderListPredicate(mesh)) {
  57687. this.renderList.push(mesh);
  57688. }
  57689. }
  57690. }
  57691. this.onBeforeBindObservable.notifyObservers(this);
  57692. // Set custom projection.
  57693. // Needs to be before binding to prevent changing the aspect ratio.
  57694. var camera;
  57695. if (this.activeCamera) {
  57696. camera = this.activeCamera;
  57697. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57698. if (this.activeCamera !== scene.activeCamera) {
  57699. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57700. }
  57701. }
  57702. else {
  57703. camera = scene.activeCamera;
  57704. if (camera) {
  57705. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57706. }
  57707. }
  57708. // Prepare renderingManager
  57709. this._renderingManager.reset();
  57710. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57711. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57712. var sceneRenderId = scene.getRenderId();
  57713. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57714. var mesh = currentRenderList[meshIndex];
  57715. if (mesh) {
  57716. if (!mesh.isReady()) {
  57717. // Reset _currentRefreshId
  57718. this.resetRefreshCounter();
  57719. continue;
  57720. }
  57721. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57722. var isMasked = void 0;
  57723. if (!this.renderList && camera) {
  57724. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57725. }
  57726. else {
  57727. isMasked = false;
  57728. }
  57729. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57730. mesh._activate(sceneRenderId);
  57731. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57732. var subMesh = mesh.subMeshes[subIndex];
  57733. scene._activeIndices.addCount(subMesh.indexCount, false);
  57734. this._renderingManager.dispatch(subMesh, mesh);
  57735. }
  57736. }
  57737. }
  57738. }
  57739. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57740. var particleSystem = scene.particleSystems[particleIndex];
  57741. var emitter = particleSystem.emitter;
  57742. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57743. continue;
  57744. }
  57745. if (currentRenderList.indexOf(emitter) >= 0) {
  57746. this._renderingManager.dispatchParticles(particleSystem);
  57747. }
  57748. }
  57749. if (this.isCube) {
  57750. for (var face = 0; face < 6; face++) {
  57751. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57752. scene.incrementRenderId();
  57753. scene.resetCachedMaterial();
  57754. }
  57755. }
  57756. else {
  57757. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57758. }
  57759. this.onAfterUnbindObservable.notifyObservers(this);
  57760. if (scene.activeCamera) {
  57761. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57762. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57763. }
  57764. engine.setViewport(scene.activeCamera.viewport);
  57765. }
  57766. scene.resetCachedMaterial();
  57767. };
  57768. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57769. var minimum = 128;
  57770. var x = renderDimension * scale;
  57771. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57772. // Ensure we don't exceed the render dimension (while staying POT)
  57773. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57774. };
  57775. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57776. var _this = this;
  57777. if (!this._texture) {
  57778. return;
  57779. }
  57780. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57781. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57782. });
  57783. };
  57784. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57785. var scene = this.getScene();
  57786. if (!scene) {
  57787. return;
  57788. }
  57789. var engine = scene.getEngine();
  57790. if (!this._texture) {
  57791. return;
  57792. }
  57793. // Bind
  57794. if (this._postProcessManager) {
  57795. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57796. }
  57797. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57798. if (this._texture) {
  57799. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57800. }
  57801. }
  57802. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57803. // Clear
  57804. if (this.onClearObservable.hasObservers()) {
  57805. this.onClearObservable.notifyObservers(engine);
  57806. }
  57807. else {
  57808. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57809. }
  57810. if (!this._doNotChangeAspectRatio) {
  57811. scene.updateTransformMatrix(true);
  57812. }
  57813. // Render
  57814. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57815. if (this._postProcessManager) {
  57816. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57817. }
  57818. else if (useCameraPostProcess) {
  57819. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57820. }
  57821. if (!this._doNotChangeAspectRatio) {
  57822. scene.updateTransformMatrix(true);
  57823. }
  57824. // Dump ?
  57825. if (dumpForDebug) {
  57826. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57827. }
  57828. // Unbind
  57829. if (!this.isCube || faceIndex === 5) {
  57830. if (this.isCube) {
  57831. if (faceIndex === 5) {
  57832. engine.generateMipMapsForCubemap(this._texture);
  57833. }
  57834. }
  57835. this.unbindFrameBuffer(engine, faceIndex);
  57836. }
  57837. else {
  57838. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57839. }
  57840. };
  57841. /**
  57842. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57843. * This allowed control for front to back rendering or reversly depending of the special needs.
  57844. *
  57845. * @param renderingGroupId The rendering group id corresponding to its index
  57846. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57847. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57848. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57849. */
  57850. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57851. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57852. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57853. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57854. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57855. };
  57856. /**
  57857. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57858. *
  57859. * @param renderingGroupId The rendering group id corresponding to its index
  57860. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57861. */
  57862. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57863. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57864. };
  57865. RenderTargetTexture.prototype.clone = function () {
  57866. var textureSize = this.getSize();
  57867. 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);
  57868. // Base texture
  57869. newTexture.hasAlpha = this.hasAlpha;
  57870. newTexture.level = this.level;
  57871. // RenderTarget Texture
  57872. newTexture.coordinatesMode = this.coordinatesMode;
  57873. if (this.renderList) {
  57874. newTexture.renderList = this.renderList.slice(0);
  57875. }
  57876. return newTexture;
  57877. };
  57878. RenderTargetTexture.prototype.serialize = function () {
  57879. if (!this.name) {
  57880. return null;
  57881. }
  57882. var serializationObject = _super.prototype.serialize.call(this);
  57883. serializationObject.renderTargetSize = this.getRenderSize();
  57884. serializationObject.renderList = [];
  57885. if (this.renderList) {
  57886. for (var index = 0; index < this.renderList.length; index++) {
  57887. serializationObject.renderList.push(this.renderList[index].id);
  57888. }
  57889. }
  57890. return serializationObject;
  57891. };
  57892. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57893. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57894. var objBuffer = this.getInternalTexture();
  57895. var scene = this.getScene();
  57896. if (objBuffer && scene) {
  57897. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57898. }
  57899. };
  57900. RenderTargetTexture.prototype.dispose = function () {
  57901. if (this._postProcessManager) {
  57902. this._postProcessManager.dispose();
  57903. this._postProcessManager = null;
  57904. }
  57905. this.clearPostProcesses(true);
  57906. if (this._resizeObserver) {
  57907. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57908. this._resizeObserver = null;
  57909. }
  57910. this.renderList = null;
  57911. // Remove from custom render targets
  57912. var scene = this.getScene();
  57913. if (!scene) {
  57914. return;
  57915. }
  57916. var index = scene.customRenderTargets.indexOf(this);
  57917. if (index >= 0) {
  57918. scene.customRenderTargets.splice(index, 1);
  57919. }
  57920. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57921. var camera = _a[_i];
  57922. index = camera.customRenderTargets.indexOf(this);
  57923. if (index >= 0) {
  57924. camera.customRenderTargets.splice(index, 1);
  57925. }
  57926. }
  57927. _super.prototype.dispose.call(this);
  57928. };
  57929. RenderTargetTexture.prototype._rebuild = function () {
  57930. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57931. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57932. }
  57933. if (this._postProcessManager) {
  57934. this._postProcessManager._rebuild();
  57935. }
  57936. };
  57937. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57938. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57939. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57940. return RenderTargetTexture;
  57941. }(BABYLON.Texture));
  57942. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57943. })(BABYLON || (BABYLON = {}));
  57944. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57945. var BABYLON;
  57946. (function (BABYLON) {
  57947. ;
  57948. var MultiRenderTarget = /** @class */ (function (_super) {
  57949. __extends(MultiRenderTarget, _super);
  57950. function MultiRenderTarget(name, size, count, scene, options) {
  57951. var _this = this;
  57952. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57953. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57954. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57955. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57956. _this._engine = scene.getEngine();
  57957. if (!_this.isSupported) {
  57958. _this.dispose();
  57959. return;
  57960. }
  57961. var types = [];
  57962. var samplingModes = [];
  57963. for (var i = 0; i < count; i++) {
  57964. if (options && options.types && options.types[i] !== undefined) {
  57965. types.push(options.types[i]);
  57966. }
  57967. else {
  57968. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57969. }
  57970. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57971. samplingModes.push(options.samplingModes[i]);
  57972. }
  57973. else {
  57974. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57975. }
  57976. }
  57977. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57978. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57979. _this._size = size;
  57980. _this._multiRenderTargetOptions = {
  57981. samplingModes: samplingModes,
  57982. generateMipMaps: generateMipMaps,
  57983. generateDepthBuffer: generateDepthBuffer,
  57984. generateStencilBuffer: generateStencilBuffer,
  57985. generateDepthTexture: generateDepthTexture,
  57986. types: types,
  57987. textureCount: count
  57988. };
  57989. _this._createInternalTextures();
  57990. _this._createTextures();
  57991. return _this;
  57992. }
  57993. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57994. get: function () {
  57995. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58001. get: function () {
  58002. return this._textures;
  58003. },
  58004. enumerable: true,
  58005. configurable: true
  58006. });
  58007. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58008. get: function () {
  58009. return this._textures[this._textures.length - 1];
  58010. },
  58011. enumerable: true,
  58012. configurable: true
  58013. });
  58014. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58015. set: function (wrap) {
  58016. if (this._textures) {
  58017. for (var i = 0; i < this._textures.length; i++) {
  58018. this._textures[i].wrapU = wrap;
  58019. }
  58020. }
  58021. },
  58022. enumerable: true,
  58023. configurable: true
  58024. });
  58025. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58026. set: function (wrap) {
  58027. if (this._textures) {
  58028. for (var i = 0; i < this._textures.length; i++) {
  58029. this._textures[i].wrapV = wrap;
  58030. }
  58031. }
  58032. },
  58033. enumerable: true,
  58034. configurable: true
  58035. });
  58036. MultiRenderTarget.prototype._rebuild = function () {
  58037. this.releaseInternalTextures();
  58038. this._createInternalTextures();
  58039. for (var i = 0; i < this._internalTextures.length; i++) {
  58040. var texture = this._textures[i];
  58041. texture._texture = this._internalTextures[i];
  58042. }
  58043. // Keeps references to frame buffer and stencil/depth buffer
  58044. this._texture = this._internalTextures[0];
  58045. };
  58046. MultiRenderTarget.prototype._createInternalTextures = function () {
  58047. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58048. };
  58049. MultiRenderTarget.prototype._createTextures = function () {
  58050. this._textures = [];
  58051. for (var i = 0; i < this._internalTextures.length; i++) {
  58052. var texture = new BABYLON.Texture(null, this.getScene());
  58053. texture._texture = this._internalTextures[i];
  58054. this._textures.push(texture);
  58055. }
  58056. // Keeps references to frame buffer and stencil/depth buffer
  58057. this._texture = this._internalTextures[0];
  58058. };
  58059. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58060. get: function () {
  58061. return this._samples;
  58062. },
  58063. set: function (value) {
  58064. if (this._samples === value) {
  58065. return;
  58066. }
  58067. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58068. },
  58069. enumerable: true,
  58070. configurable: true
  58071. });
  58072. MultiRenderTarget.prototype.resize = function (size) {
  58073. this.releaseInternalTextures();
  58074. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58075. this._createInternalTextures();
  58076. };
  58077. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58078. var _this = this;
  58079. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58080. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58081. });
  58082. };
  58083. MultiRenderTarget.prototype.dispose = function () {
  58084. this.releaseInternalTextures();
  58085. _super.prototype.dispose.call(this);
  58086. };
  58087. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58088. if (!this._internalTextures) {
  58089. return;
  58090. }
  58091. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58092. if (this._internalTextures[i] !== undefined) {
  58093. this._internalTextures[i].dispose();
  58094. this._internalTextures.splice(i, 1);
  58095. }
  58096. }
  58097. };
  58098. return MultiRenderTarget;
  58099. }(BABYLON.RenderTargetTexture));
  58100. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58101. })(BABYLON || (BABYLON = {}));
  58102. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58103. var BABYLON;
  58104. (function (BABYLON) {
  58105. var MirrorTexture = /** @class */ (function (_super) {
  58106. __extends(MirrorTexture, _super);
  58107. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58108. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58110. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58111. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58112. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58113. _this._transformMatrix = BABYLON.Matrix.Zero();
  58114. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58115. _this._adaptiveBlurKernel = 0;
  58116. _this._blurKernelX = 0;
  58117. _this._blurKernelY = 0;
  58118. _this._blurRatio = 1.0;
  58119. _this.ignoreCameraViewport = true;
  58120. _this.onBeforeRenderObservable.add(function () {
  58121. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58122. _this._savedViewMatrix = scene.getViewMatrix();
  58123. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58124. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58125. scene.clipPlane = _this.mirrorPlane;
  58126. scene.getEngine().cullBackFaces = false;
  58127. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58128. });
  58129. _this.onAfterRenderObservable.add(function () {
  58130. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58131. scene.getEngine().cullBackFaces = true;
  58132. scene._mirroredCameraPosition = null;
  58133. delete scene.clipPlane;
  58134. });
  58135. return _this;
  58136. }
  58137. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58138. get: function () {
  58139. return this._blurRatio;
  58140. },
  58141. set: function (value) {
  58142. if (this._blurRatio === value) {
  58143. return;
  58144. }
  58145. this._blurRatio = value;
  58146. this._preparePostProcesses();
  58147. },
  58148. enumerable: true,
  58149. configurable: true
  58150. });
  58151. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58152. set: function (value) {
  58153. this._adaptiveBlurKernel = value;
  58154. this._autoComputeBlurKernel();
  58155. },
  58156. enumerable: true,
  58157. configurable: true
  58158. });
  58159. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58160. set: function (value) {
  58161. this.blurKernelX = value;
  58162. this.blurKernelY = value;
  58163. },
  58164. enumerable: true,
  58165. configurable: true
  58166. });
  58167. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58168. get: function () {
  58169. return this._blurKernelX;
  58170. },
  58171. set: function (value) {
  58172. if (this._blurKernelX === value) {
  58173. return;
  58174. }
  58175. this._blurKernelX = value;
  58176. this._preparePostProcesses();
  58177. },
  58178. enumerable: true,
  58179. configurable: true
  58180. });
  58181. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58182. get: function () {
  58183. return this._blurKernelY;
  58184. },
  58185. set: function (value) {
  58186. if (this._blurKernelY === value) {
  58187. return;
  58188. }
  58189. this._blurKernelY = value;
  58190. this._preparePostProcesses();
  58191. },
  58192. enumerable: true,
  58193. configurable: true
  58194. });
  58195. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58196. var engine = this.getScene().getEngine();
  58197. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58198. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58199. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58200. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58201. };
  58202. MirrorTexture.prototype._onRatioRescale = function () {
  58203. if (this._sizeRatio) {
  58204. this.resize(this._initialSizeParameter);
  58205. if (!this._adaptiveBlurKernel) {
  58206. this._preparePostProcesses();
  58207. }
  58208. }
  58209. if (this._adaptiveBlurKernel) {
  58210. this._autoComputeBlurKernel();
  58211. }
  58212. };
  58213. MirrorTexture.prototype._preparePostProcesses = function () {
  58214. this.clearPostProcesses(true);
  58215. if (this._blurKernelX && this._blurKernelY) {
  58216. var engine = this.getScene().getEngine();
  58217. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58218. 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);
  58219. this._blurX.autoClear = false;
  58220. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58221. this._blurX.inputTexture = this._texture;
  58222. }
  58223. else {
  58224. this._blurX.alwaysForcePOT = true;
  58225. }
  58226. 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);
  58227. this._blurY.autoClear = false;
  58228. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58229. this.addPostProcess(this._blurX);
  58230. this.addPostProcess(this._blurY);
  58231. }
  58232. else {
  58233. if (this._blurY) {
  58234. this.removePostProcess(this._blurY);
  58235. this._blurY.dispose();
  58236. this._blurY = null;
  58237. }
  58238. if (this._blurX) {
  58239. this.removePostProcess(this._blurX);
  58240. this._blurX.dispose();
  58241. this._blurX = null;
  58242. }
  58243. }
  58244. };
  58245. MirrorTexture.prototype.clone = function () {
  58246. var scene = this.getScene();
  58247. if (!scene) {
  58248. return this;
  58249. }
  58250. var textureSize = this.getSize();
  58251. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58252. // Base texture
  58253. newTexture.hasAlpha = this.hasAlpha;
  58254. newTexture.level = this.level;
  58255. // Mirror Texture
  58256. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58257. if (this.renderList) {
  58258. newTexture.renderList = this.renderList.slice(0);
  58259. }
  58260. return newTexture;
  58261. };
  58262. MirrorTexture.prototype.serialize = function () {
  58263. if (!this.name) {
  58264. return null;
  58265. }
  58266. var serializationObject = _super.prototype.serialize.call(this);
  58267. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58268. return serializationObject;
  58269. };
  58270. return MirrorTexture;
  58271. }(BABYLON.RenderTargetTexture));
  58272. BABYLON.MirrorTexture = MirrorTexture;
  58273. })(BABYLON || (BABYLON = {}));
  58274. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58275. var BABYLON;
  58276. (function (BABYLON) {
  58277. /**
  58278. * Creates a refraction texture used by refraction channel of the standard material.
  58279. * @param name the texture name
  58280. * @param size size of the underlying texture
  58281. * @param scene root scene
  58282. */
  58283. var RefractionTexture = /** @class */ (function (_super) {
  58284. __extends(RefractionTexture, _super);
  58285. function RefractionTexture(name, size, scene, generateMipMaps) {
  58286. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58287. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58288. _this.depth = 2.0;
  58289. _this.onBeforeRenderObservable.add(function () {
  58290. scene.clipPlane = _this.refractionPlane;
  58291. });
  58292. _this.onAfterRenderObservable.add(function () {
  58293. delete scene.clipPlane;
  58294. });
  58295. return _this;
  58296. }
  58297. RefractionTexture.prototype.clone = function () {
  58298. var scene = this.getScene();
  58299. if (!scene) {
  58300. return this;
  58301. }
  58302. var textureSize = this.getSize();
  58303. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58304. // Base texture
  58305. newTexture.hasAlpha = this.hasAlpha;
  58306. newTexture.level = this.level;
  58307. // Refraction Texture
  58308. newTexture.refractionPlane = this.refractionPlane.clone();
  58309. if (this.renderList) {
  58310. newTexture.renderList = this.renderList.slice(0);
  58311. }
  58312. newTexture.depth = this.depth;
  58313. return newTexture;
  58314. };
  58315. RefractionTexture.prototype.serialize = function () {
  58316. if (!this.name) {
  58317. return null;
  58318. }
  58319. var serializationObject = _super.prototype.serialize.call(this);
  58320. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58321. serializationObject.depth = this.depth;
  58322. return serializationObject;
  58323. };
  58324. return RefractionTexture;
  58325. }(BABYLON.RenderTargetTexture));
  58326. BABYLON.RefractionTexture = RefractionTexture;
  58327. })(BABYLON || (BABYLON = {}));
  58328. //# sourceMappingURL=babylon.refractionTexture.js.map
  58329. var BABYLON;
  58330. (function (BABYLON) {
  58331. var DynamicTexture = /** @class */ (function (_super) {
  58332. __extends(DynamicTexture, _super);
  58333. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58334. if (scene === void 0) { scene = null; }
  58335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58336. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58337. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58338. _this.name = name;
  58339. _this._engine = _this.getScene().getEngine();
  58340. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58341. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58342. _this._generateMipMaps = generateMipMaps;
  58343. if (options.getContext) {
  58344. _this._canvas = options;
  58345. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58346. }
  58347. else {
  58348. _this._canvas = document.createElement("canvas");
  58349. if (options.width) {
  58350. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58351. }
  58352. else {
  58353. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58354. }
  58355. }
  58356. var textureSize = _this.getSize();
  58357. _this._canvas.width = textureSize.width;
  58358. _this._canvas.height = textureSize.height;
  58359. _this._context = _this._canvas.getContext("2d");
  58360. return _this;
  58361. }
  58362. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58363. get: function () {
  58364. return true;
  58365. },
  58366. enumerable: true,
  58367. configurable: true
  58368. });
  58369. DynamicTexture.prototype._recreate = function (textureSize) {
  58370. this._canvas.width = textureSize.width;
  58371. this._canvas.height = textureSize.height;
  58372. this.releaseInternalTexture();
  58373. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58374. };
  58375. DynamicTexture.prototype.scale = function (ratio) {
  58376. var textureSize = this.getSize();
  58377. textureSize.width *= ratio;
  58378. textureSize.height *= ratio;
  58379. this._recreate(textureSize);
  58380. };
  58381. DynamicTexture.prototype.scaleTo = function (width, height) {
  58382. var textureSize = this.getSize();
  58383. textureSize.width = width;
  58384. textureSize.height = height;
  58385. this._recreate(textureSize);
  58386. };
  58387. DynamicTexture.prototype.getContext = function () {
  58388. return this._context;
  58389. };
  58390. DynamicTexture.prototype.clear = function () {
  58391. var size = this.getSize();
  58392. this._context.fillRect(0, 0, size.width, size.height);
  58393. };
  58394. DynamicTexture.prototype.update = function (invertY) {
  58395. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58396. };
  58397. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58398. if (update === void 0) { update = true; }
  58399. var size = this.getSize();
  58400. if (clearColor) {
  58401. this._context.fillStyle = clearColor;
  58402. this._context.fillRect(0, 0, size.width, size.height);
  58403. }
  58404. this._context.font = font;
  58405. if (x === null || x === undefined) {
  58406. var textSize = this._context.measureText(text);
  58407. x = (size.width - textSize.width) / 2;
  58408. }
  58409. if (y === null || y === undefined) {
  58410. var fontSize = parseInt((font.replace(/\D/g, '')));
  58411. ;
  58412. y = (size.height / 2) + (fontSize / 3.65);
  58413. }
  58414. this._context.fillStyle = color;
  58415. this._context.fillText(text, x, y);
  58416. if (update) {
  58417. this.update(invertY);
  58418. }
  58419. };
  58420. DynamicTexture.prototype.clone = function () {
  58421. var scene = this.getScene();
  58422. if (!scene) {
  58423. return this;
  58424. }
  58425. var textureSize = this.getSize();
  58426. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58427. // Base texture
  58428. newTexture.hasAlpha = this.hasAlpha;
  58429. newTexture.level = this.level;
  58430. // Dynamic Texture
  58431. newTexture.wrapU = this.wrapU;
  58432. newTexture.wrapV = this.wrapV;
  58433. return newTexture;
  58434. };
  58435. DynamicTexture.prototype._rebuild = function () {
  58436. this.update();
  58437. };
  58438. return DynamicTexture;
  58439. }(BABYLON.Texture));
  58440. BABYLON.DynamicTexture = DynamicTexture;
  58441. })(BABYLON || (BABYLON = {}));
  58442. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58443. var BABYLON;
  58444. (function (BABYLON) {
  58445. var VideoTexture = /** @class */ (function (_super) {
  58446. __extends(VideoTexture, _super);
  58447. /**
  58448. * Creates a video texture.
  58449. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58450. * @param {string | null} name optional name, will detect from video source, if not defined
  58451. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58452. * @param {BABYLON.Scene} scene is obviously the current scene.
  58453. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58454. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58455. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58456. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58457. */
  58458. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58459. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58460. if (invertY === void 0) { invertY = false; }
  58461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58462. if (settings === void 0) { settings = {
  58463. autoPlay: true,
  58464. loop: true,
  58465. autoUpdateTexture: true,
  58466. }; }
  58467. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58468. _this._createInternalTexture = function () {
  58469. if (_this._texture != null) {
  58470. return;
  58471. }
  58472. if (!_this._engine.needPOTTextures ||
  58473. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58474. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58475. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58476. }
  58477. else {
  58478. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58479. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58480. _this._generateMipMaps = false;
  58481. }
  58482. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58483. _this._texture.isReady = true;
  58484. _this._updateInternalTexture();
  58485. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58486. _this.onLoadObservable.notifyObservers(_this);
  58487. }
  58488. };
  58489. _this.reset = function () {
  58490. if (_this._texture == null) {
  58491. return;
  58492. }
  58493. _this._texture.dispose();
  58494. _this._texture = null;
  58495. };
  58496. _this._updateInternalTexture = function (e) {
  58497. if (_this._texture == null || !_this._texture.isReady) {
  58498. return;
  58499. }
  58500. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58501. return;
  58502. }
  58503. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58504. };
  58505. _this._engine = _this.getScene().getEngine();
  58506. _this._generateMipMaps = generateMipMaps;
  58507. _this._samplingMode = samplingMode;
  58508. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58509. _this.name = name || _this._getName(src);
  58510. _this.video = _this._getVideo(src);
  58511. if (settings.autoPlay !== undefined) {
  58512. _this.video.autoplay = settings.autoPlay;
  58513. }
  58514. if (settings.loop !== undefined) {
  58515. _this.video.loop = settings.loop;
  58516. }
  58517. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58518. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58519. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58520. _this.video.addEventListener("emptied", _this.reset);
  58521. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58522. _this._createInternalTexture();
  58523. }
  58524. return _this;
  58525. }
  58526. VideoTexture.prototype._getName = function (src) {
  58527. if (src instanceof HTMLVideoElement) {
  58528. return src.currentSrc;
  58529. }
  58530. if (typeof src === "object") {
  58531. return src.toString();
  58532. }
  58533. return src;
  58534. };
  58535. ;
  58536. VideoTexture.prototype._getVideo = function (src) {
  58537. if (src instanceof HTMLVideoElement) {
  58538. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58539. return src;
  58540. }
  58541. var video = document.createElement("video");
  58542. if (typeof src === "string") {
  58543. BABYLON.Tools.SetCorsBehavior(src, video);
  58544. video.src = src;
  58545. }
  58546. else {
  58547. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58548. src.forEach(function (url) {
  58549. var source = document.createElement("source");
  58550. source.src = url;
  58551. video.appendChild(source);
  58552. });
  58553. }
  58554. return video;
  58555. };
  58556. ;
  58557. /**
  58558. * Internal method to initiate `update`.
  58559. */
  58560. VideoTexture.prototype._rebuild = function () {
  58561. this.update();
  58562. };
  58563. /**
  58564. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58565. */
  58566. VideoTexture.prototype.update = function () {
  58567. if (!this.autoUpdateTexture) {
  58568. // Expecting user to call `updateTexture` manually
  58569. return;
  58570. }
  58571. this.updateTexture(true);
  58572. };
  58573. /**
  58574. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58575. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58576. */
  58577. VideoTexture.prototype.updateTexture = function (isVisible) {
  58578. if (!isVisible) {
  58579. return;
  58580. }
  58581. if (this.video.paused) {
  58582. return;
  58583. }
  58584. this._updateInternalTexture();
  58585. };
  58586. /**
  58587. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58588. * @param url New url.
  58589. */
  58590. VideoTexture.prototype.updateURL = function (url) {
  58591. this.video.src = url;
  58592. };
  58593. VideoTexture.prototype.dispose = function () {
  58594. _super.prototype.dispose.call(this);
  58595. this.video.removeEventListener("canplay", this._createInternalTexture);
  58596. this.video.removeEventListener("paused", this._updateInternalTexture);
  58597. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58598. this.video.removeEventListener("emptied", this.reset);
  58599. this.video.pause();
  58600. };
  58601. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58602. var video = document.createElement("video");
  58603. var constraintsDeviceId;
  58604. if (constraints && constraints.deviceId) {
  58605. constraintsDeviceId = {
  58606. exact: constraints.deviceId,
  58607. };
  58608. }
  58609. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58610. if (navigator.mediaDevices) {
  58611. navigator.mediaDevices.getUserMedia({ video: constraints })
  58612. .then(function (stream) {
  58613. if (video.mozSrcObject !== undefined) {
  58614. // hack for Firefox < 19
  58615. video.mozSrcObject = stream;
  58616. }
  58617. else {
  58618. video.srcObject = stream;
  58619. }
  58620. var onPlaying = function () {
  58621. if (onReady) {
  58622. onReady(new VideoTexture("video", video, scene, true, true));
  58623. }
  58624. video.removeEventListener("playing", onPlaying);
  58625. };
  58626. video.addEventListener("playing", onPlaying);
  58627. video.play();
  58628. })
  58629. .catch(function (err) {
  58630. BABYLON.Tools.Error(err.name);
  58631. });
  58632. }
  58633. else {
  58634. navigator.getUserMedia =
  58635. navigator.getUserMedia ||
  58636. navigator.webkitGetUserMedia ||
  58637. navigator.mozGetUserMedia ||
  58638. navigator.msGetUserMedia;
  58639. if (navigator.getUserMedia) {
  58640. navigator.getUserMedia({
  58641. video: {
  58642. deviceId: constraintsDeviceId,
  58643. width: {
  58644. min: (constraints && constraints.minWidth) || 256,
  58645. max: (constraints && constraints.maxWidth) || 640,
  58646. },
  58647. height: {
  58648. min: (constraints && constraints.minHeight) || 256,
  58649. max: (constraints && constraints.maxHeight) || 480,
  58650. },
  58651. },
  58652. }, function (stream) {
  58653. if (video.mozSrcObject !== undefined) {
  58654. // hack for Firefox < 19
  58655. video.mozSrcObject = stream;
  58656. }
  58657. else {
  58658. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58659. }
  58660. video.play();
  58661. if (onReady) {
  58662. onReady(new VideoTexture("video", video, scene, true, true));
  58663. }
  58664. }, function (e) {
  58665. BABYLON.Tools.Error(e.name);
  58666. });
  58667. }
  58668. }
  58669. };
  58670. return VideoTexture;
  58671. }(BABYLON.Texture));
  58672. BABYLON.VideoTexture = VideoTexture;
  58673. })(BABYLON || (BABYLON = {}));
  58674. //# sourceMappingURL=babylon.videoTexture.js.map
  58675. var BABYLON;
  58676. (function (BABYLON) {
  58677. var RawTexture = /** @class */ (function (_super) {
  58678. __extends(RawTexture, _super);
  58679. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58680. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58681. if (invertY === void 0) { invertY = false; }
  58682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58683. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58684. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58685. _this.format = format;
  58686. _this._engine = scene.getEngine();
  58687. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58688. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58689. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58690. return _this;
  58691. }
  58692. RawTexture.prototype.update = function (data) {
  58693. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58694. };
  58695. // Statics
  58696. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58698. if (invertY === void 0) { invertY = false; }
  58699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58700. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58701. };
  58702. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58703. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58704. if (invertY === void 0) { invertY = false; }
  58705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58706. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58707. };
  58708. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58709. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58710. if (invertY === void 0) { invertY = false; }
  58711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58712. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58713. };
  58714. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58715. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58716. if (invertY === void 0) { invertY = false; }
  58717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58718. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58719. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58720. };
  58721. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58722. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58723. if (invertY === void 0) { invertY = false; }
  58724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58725. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58726. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58727. };
  58728. return RawTexture;
  58729. }(BABYLON.Texture));
  58730. BABYLON.RawTexture = RawTexture;
  58731. })(BABYLON || (BABYLON = {}));
  58732. //# sourceMappingURL=babylon.rawTexture.js.map
  58733. var BABYLON;
  58734. (function (BABYLON) {
  58735. /**
  58736. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58737. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58738. */
  58739. var PostProcess = /** @class */ (function () {
  58740. /**
  58741. * Creates a new instance of @see PostProcess
  58742. * @param name The name of the PostProcess.
  58743. * @param fragmentUrl The url of the fragment shader to be used.
  58744. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58745. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58746. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58747. * @param camera The camera to apply the render pass to.
  58748. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58749. * @param engine The engine which the post process will be applied. (default: current engine)
  58750. * @param reusable If the post process can be reused on the same frame. (default: false)
  58751. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58752. * @param textureType Type of textures used when performing the post process. (default: 0)
  58753. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58754. * @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
  58755. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58756. */
  58757. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58759. if (defines === void 0) { defines = null; }
  58760. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58761. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58762. if (blockCompilation === void 0) { blockCompilation = false; }
  58763. this.name = name;
  58764. /**
  58765. * Width of the texture to apply the post process on
  58766. */
  58767. this.width = -1;
  58768. /**
  58769. * Height of the texture to apply the post process on
  58770. */
  58771. this.height = -1;
  58772. /**
  58773. * If the buffer needs to be cleared before applying the post process. (default: true)
  58774. * Should be set to false if shader will overwrite all previous pixels.
  58775. */
  58776. this.autoClear = true;
  58777. /**
  58778. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58779. */
  58780. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58781. /**
  58782. * Animations to be used for the post processing
  58783. */
  58784. this.animations = new Array();
  58785. /**
  58786. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58787. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58788. */
  58789. this.enablePixelPerfectMode = false;
  58790. /**
  58791. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58792. */
  58793. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58794. /**
  58795. * Force textures to be a power of two (default: false)
  58796. */
  58797. this.alwaysForcePOT = false;
  58798. /**
  58799. * Number of sample textures (default: 1)
  58800. */
  58801. this.samples = 1;
  58802. /**
  58803. * Modify the scale of the post process to be the same as the viewport (default: false)
  58804. */
  58805. this.adaptScaleToCurrentViewport = false;
  58806. this._reusable = false;
  58807. /**
  58808. * Smart array of input and output textures for the post process.
  58809. */
  58810. this._textures = new BABYLON.SmartArray(2);
  58811. /**
  58812. * The index in _textures that corresponds to the output texture.
  58813. */
  58814. this._currentRenderTextureInd = 0;
  58815. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58816. this._texelSize = BABYLON.Vector2.Zero();
  58817. // Events
  58818. /**
  58819. * An event triggered when the postprocess is activated.
  58820. * @type {BABYLON.Observable}
  58821. */
  58822. this.onActivateObservable = new BABYLON.Observable();
  58823. /**
  58824. * An event triggered when the postprocess changes its size.
  58825. * @type {BABYLON.Observable}
  58826. */
  58827. this.onSizeChangedObservable = new BABYLON.Observable();
  58828. /**
  58829. * An event triggered when the postprocess applies its effect.
  58830. * @type {BABYLON.Observable}
  58831. */
  58832. this.onApplyObservable = new BABYLON.Observable();
  58833. /**
  58834. * An event triggered before rendering the postprocess
  58835. * @type {BABYLON.Observable}
  58836. */
  58837. this.onBeforeRenderObservable = new BABYLON.Observable();
  58838. /**
  58839. * An event triggered after rendering the postprocess
  58840. * @type {BABYLON.Observable}
  58841. */
  58842. this.onAfterRenderObservable = new BABYLON.Observable();
  58843. if (camera != null) {
  58844. this._camera = camera;
  58845. this._scene = camera.getScene();
  58846. camera.attachPostProcess(this);
  58847. this._engine = this._scene.getEngine();
  58848. this._scene.postProcesses.push(this);
  58849. }
  58850. else if (engine) {
  58851. this._engine = engine;
  58852. this._engine.postProcesses.push(this);
  58853. }
  58854. this._options = options;
  58855. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58856. this._reusable = reusable || false;
  58857. this._textureType = textureType;
  58858. this._samplers = samplers || [];
  58859. this._samplers.push("textureSampler");
  58860. this._fragmentUrl = fragmentUrl;
  58861. this._vertexUrl = vertexUrl;
  58862. this._parameters = parameters || [];
  58863. this._parameters.push("scale");
  58864. this._indexParameters = indexParameters;
  58865. if (!blockCompilation) {
  58866. this.updateEffect(defines);
  58867. }
  58868. }
  58869. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58870. /**
  58871. * A function that is added to the onActivateObservable
  58872. */
  58873. set: function (callback) {
  58874. if (this._onActivateObserver) {
  58875. this.onActivateObservable.remove(this._onActivateObserver);
  58876. }
  58877. if (callback) {
  58878. this._onActivateObserver = this.onActivateObservable.add(callback);
  58879. }
  58880. },
  58881. enumerable: true,
  58882. configurable: true
  58883. });
  58884. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58885. /**
  58886. * A function that is added to the onSizeChangedObservable
  58887. */
  58888. set: function (callback) {
  58889. if (this._onSizeChangedObserver) {
  58890. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58891. }
  58892. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58893. },
  58894. enumerable: true,
  58895. configurable: true
  58896. });
  58897. Object.defineProperty(PostProcess.prototype, "onApply", {
  58898. /**
  58899. * A function that is added to the onApplyObservable
  58900. */
  58901. set: function (callback) {
  58902. if (this._onApplyObserver) {
  58903. this.onApplyObservable.remove(this._onApplyObserver);
  58904. }
  58905. this._onApplyObserver = this.onApplyObservable.add(callback);
  58906. },
  58907. enumerable: true,
  58908. configurable: true
  58909. });
  58910. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58911. /**
  58912. * A function that is added to the onBeforeRenderObservable
  58913. */
  58914. set: function (callback) {
  58915. if (this._onBeforeRenderObserver) {
  58916. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58917. }
  58918. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58919. },
  58920. enumerable: true,
  58921. configurable: true
  58922. });
  58923. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58924. /**
  58925. * A function that is added to the onAfterRenderObservable
  58926. */
  58927. set: function (callback) {
  58928. if (this._onAfterRenderObserver) {
  58929. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58930. }
  58931. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58932. },
  58933. enumerable: true,
  58934. configurable: true
  58935. });
  58936. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58937. /**
  58938. * 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
  58939. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58940. */
  58941. get: function () {
  58942. return this._textures.data[this._currentRenderTextureInd];
  58943. },
  58944. set: function (value) {
  58945. this._forcedOutputTexture = value;
  58946. },
  58947. enumerable: true,
  58948. configurable: true
  58949. });
  58950. /**
  58951. * Gets the camera which post process is applied to.
  58952. * @returns The camera the post process is applied to.
  58953. */
  58954. PostProcess.prototype.getCamera = function () {
  58955. return this._camera;
  58956. };
  58957. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58958. /**
  58959. * Gets the texel size of the postprocess.
  58960. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58961. */
  58962. get: function () {
  58963. if (this._shareOutputWithPostProcess) {
  58964. return this._shareOutputWithPostProcess.texelSize;
  58965. }
  58966. if (this._forcedOutputTexture) {
  58967. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58968. }
  58969. return this._texelSize;
  58970. },
  58971. enumerable: true,
  58972. configurable: true
  58973. });
  58974. /**
  58975. * Gets the engine which this post process belongs to.
  58976. * @returns The engine the post process was enabled with.
  58977. */
  58978. PostProcess.prototype.getEngine = function () {
  58979. return this._engine;
  58980. };
  58981. /**
  58982. * The effect that is created when initializing the post process.
  58983. * @returns The created effect corrisponding the the postprocess.
  58984. */
  58985. PostProcess.prototype.getEffect = function () {
  58986. return this._effect;
  58987. };
  58988. /**
  58989. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58990. * @param postProcess The post process to share the output with.
  58991. * @returns This post process.
  58992. */
  58993. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58994. this._disposeTextures();
  58995. this._shareOutputWithPostProcess = postProcess;
  58996. return this;
  58997. };
  58998. /**
  58999. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59000. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59001. */
  59002. PostProcess.prototype.useOwnOutput = function () {
  59003. if (this._textures.length == 0) {
  59004. this._textures = new BABYLON.SmartArray(2);
  59005. }
  59006. this._shareOutputWithPostProcess = null;
  59007. };
  59008. /**
  59009. * Updates the effect with the current post process compile time values and recompiles the shader.
  59010. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59011. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59012. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59013. * @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
  59014. * @param onCompiled Called when the shader has been compiled.
  59015. * @param onError Called if there is an error when compiling a shader.
  59016. */
  59017. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59018. if (defines === void 0) { defines = null; }
  59019. if (uniforms === void 0) { uniforms = null; }
  59020. if (samplers === void 0) { samplers = null; }
  59021. 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);
  59022. };
  59023. /**
  59024. * The post process is reusable if it can be used multiple times within one frame.
  59025. * @returns If the post process is reusable
  59026. */
  59027. PostProcess.prototype.isReusable = function () {
  59028. return this._reusable;
  59029. };
  59030. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59031. PostProcess.prototype.markTextureDirty = function () {
  59032. this.width = -1;
  59033. };
  59034. /**
  59035. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59036. * 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.
  59037. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59038. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59039. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59040. */
  59041. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59042. var _this = this;
  59043. if (sourceTexture === void 0) { sourceTexture = null; }
  59044. camera = camera || this._camera;
  59045. var scene = camera.getScene();
  59046. var engine = scene.getEngine();
  59047. var maxSize = engine.getCaps().maxTextureSize;
  59048. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59049. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59050. // 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
  59051. var webVRCamera = camera.parent;
  59052. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59053. requiredWidth /= 2;
  59054. }
  59055. var desiredWidth = (this._options.width || requiredWidth);
  59056. var desiredHeight = this._options.height || requiredHeight;
  59057. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59058. if (this.adaptScaleToCurrentViewport) {
  59059. var currentViewport = engine.currentViewport;
  59060. if (currentViewport) {
  59061. desiredWidth *= currentViewport.width;
  59062. desiredHeight *= currentViewport.height;
  59063. }
  59064. }
  59065. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59066. if (!this._options.width) {
  59067. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59068. }
  59069. if (!this._options.height) {
  59070. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59071. }
  59072. }
  59073. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59074. if (this._textures.length > 0) {
  59075. for (var i = 0; i < this._textures.length; i++) {
  59076. this._engine._releaseTexture(this._textures.data[i]);
  59077. }
  59078. this._textures.reset();
  59079. }
  59080. this.width = desiredWidth;
  59081. this.height = desiredHeight;
  59082. var textureSize = { width: this.width, height: this.height };
  59083. var textureOptions = {
  59084. generateMipMaps: false,
  59085. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59086. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59087. samplingMode: this.renderTargetSamplingMode,
  59088. type: this._textureType
  59089. };
  59090. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59091. if (this._reusable) {
  59092. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59093. }
  59094. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59095. this.onSizeChangedObservable.notifyObservers(this);
  59096. }
  59097. this._textures.forEach(function (texture) {
  59098. if (texture.samples !== _this.samples) {
  59099. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59100. }
  59101. });
  59102. }
  59103. var target;
  59104. if (this._shareOutputWithPostProcess) {
  59105. target = this._shareOutputWithPostProcess.inputTexture;
  59106. }
  59107. else if (this._forcedOutputTexture) {
  59108. target = this._forcedOutputTexture;
  59109. this.width = this._forcedOutputTexture.width;
  59110. this.height = this._forcedOutputTexture.height;
  59111. }
  59112. else {
  59113. target = this.inputTexture;
  59114. }
  59115. // Bind the input of this post process to be used as the output of the previous post process.
  59116. if (this.enablePixelPerfectMode) {
  59117. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59118. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59119. }
  59120. else {
  59121. this._scaleRatio.copyFromFloats(1, 1);
  59122. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59123. }
  59124. this.onActivateObservable.notifyObservers(camera);
  59125. // Clear
  59126. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59127. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59128. }
  59129. if (this._reusable) {
  59130. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59131. }
  59132. };
  59133. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59134. /**
  59135. * If the post process is supported.
  59136. */
  59137. get: function () {
  59138. return this._effect.isSupported;
  59139. },
  59140. enumerable: true,
  59141. configurable: true
  59142. });
  59143. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59144. /**
  59145. * The aspect ratio of the output texture.
  59146. */
  59147. get: function () {
  59148. if (this._shareOutputWithPostProcess) {
  59149. return this._shareOutputWithPostProcess.aspectRatio;
  59150. }
  59151. if (this._forcedOutputTexture) {
  59152. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59153. }
  59154. return this.width / this.height;
  59155. },
  59156. enumerable: true,
  59157. configurable: true
  59158. });
  59159. /**
  59160. * Get a value indicating if the post-process is ready to be used
  59161. * @returns true if the post-process is ready (shader is compiled)
  59162. */
  59163. PostProcess.prototype.isReady = function () {
  59164. return this._effect && this._effect.isReady();
  59165. };
  59166. /**
  59167. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59168. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59169. */
  59170. PostProcess.prototype.apply = function () {
  59171. // Check
  59172. if (!this._effect || !this._effect.isReady())
  59173. return null;
  59174. // States
  59175. this._engine.enableEffect(this._effect);
  59176. this._engine.setState(false);
  59177. this._engine.setDepthBuffer(false);
  59178. this._engine.setDepthWrite(false);
  59179. // Alpha
  59180. this._engine.setAlphaMode(this.alphaMode);
  59181. if (this.alphaConstants) {
  59182. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59183. }
  59184. // Bind the output texture of the preivous post process as the input to this post process.
  59185. var source;
  59186. if (this._shareOutputWithPostProcess) {
  59187. source = this._shareOutputWithPostProcess.inputTexture;
  59188. }
  59189. else if (this._forcedOutputTexture) {
  59190. source = this._forcedOutputTexture;
  59191. }
  59192. else {
  59193. source = this.inputTexture;
  59194. }
  59195. this._effect._bindTexture("textureSampler", source);
  59196. // Parameters
  59197. this._effect.setVector2("scale", this._scaleRatio);
  59198. this.onApplyObservable.notifyObservers(this._effect);
  59199. return this._effect;
  59200. };
  59201. PostProcess.prototype._disposeTextures = function () {
  59202. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59203. return;
  59204. }
  59205. if (this._textures.length > 0) {
  59206. for (var i = 0; i < this._textures.length; i++) {
  59207. this._engine._releaseTexture(this._textures.data[i]);
  59208. }
  59209. }
  59210. this._textures.dispose();
  59211. };
  59212. /**
  59213. * Disposes the post process.
  59214. * @param camera The camera to dispose the post process on.
  59215. */
  59216. PostProcess.prototype.dispose = function (camera) {
  59217. camera = camera || this._camera;
  59218. this._disposeTextures();
  59219. if (this._scene) {
  59220. var index_1 = this._scene.postProcesses.indexOf(this);
  59221. if (index_1 !== -1) {
  59222. this._scene.postProcesses.splice(index_1, 1);
  59223. }
  59224. }
  59225. else {
  59226. var index_2 = this._engine.postProcesses.indexOf(this);
  59227. if (index_2 !== -1) {
  59228. this._engine.postProcesses.splice(index_2, 1);
  59229. }
  59230. }
  59231. if (!camera) {
  59232. return;
  59233. }
  59234. camera.detachPostProcess(this);
  59235. var index = camera._postProcesses.indexOf(this);
  59236. if (index === 0 && camera._postProcesses.length > 0) {
  59237. this._camera._postProcesses[0].markTextureDirty();
  59238. }
  59239. this.onActivateObservable.clear();
  59240. this.onAfterRenderObservable.clear();
  59241. this.onApplyObservable.clear();
  59242. this.onBeforeRenderObservable.clear();
  59243. this.onSizeChangedObservable.clear();
  59244. };
  59245. return PostProcess;
  59246. }());
  59247. BABYLON.PostProcess = PostProcess;
  59248. })(BABYLON || (BABYLON = {}));
  59249. //# sourceMappingURL=babylon.postProcess.js.map
  59250. var BABYLON;
  59251. (function (BABYLON) {
  59252. var PassPostProcess = /** @class */ (function (_super) {
  59253. __extends(PassPostProcess, _super);
  59254. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59255. if (camera === void 0) { camera = null; }
  59256. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59257. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59258. }
  59259. return PassPostProcess;
  59260. }(BABYLON.PostProcess));
  59261. BABYLON.PassPostProcess = PassPostProcess;
  59262. })(BABYLON || (BABYLON = {}));
  59263. //# sourceMappingURL=babylon.passPostProcess.js.map
  59264. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59265. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59266. s = arguments[i];
  59267. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59268. t[p] = s[p];
  59269. }
  59270. return t;
  59271. };
  59272. var BABYLON;
  59273. (function (BABYLON) {
  59274. /**
  59275. * Default implementation of @see IShadowGenerator.
  59276. * This is the main object responsible of generating shadows in the framework.
  59277. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59278. */
  59279. var ShadowGenerator = /** @class */ (function () {
  59280. /**
  59281. * Creates a ShadowGenerator object.
  59282. * A ShadowGenerator is the required tool to use the shadows.
  59283. * Each light casting shadows needs to use its own ShadowGenerator.
  59284. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59285. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59286. * @param light The light object generating the shadows.
  59287. * @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.
  59288. */
  59289. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59290. this._bias = 0.00005;
  59291. this._blurBoxOffset = 1;
  59292. this._blurScale = 2;
  59293. this._blurKernel = 1;
  59294. this._useKernelBlur = false;
  59295. this._filter = ShadowGenerator.FILTER_NONE;
  59296. this._darkness = 0;
  59297. this._transparencyShadow = false;
  59298. /**
  59299. * Controls the extent to which the shadows fade out at the edge of the frustum
  59300. * Used only by directionals and spots
  59301. */
  59302. this.frustumEdgeFalloff = 0;
  59303. /**
  59304. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59305. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59306. * It might on the other hand introduce peter panning.
  59307. */
  59308. this.forceBackFacesOnly = false;
  59309. this._lightDirection = BABYLON.Vector3.Zero();
  59310. this._viewMatrix = BABYLON.Matrix.Zero();
  59311. this._projectionMatrix = BABYLON.Matrix.Zero();
  59312. this._transformMatrix = BABYLON.Matrix.Zero();
  59313. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59314. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59315. this._currentFaceIndex = 0;
  59316. this._currentFaceIndexCache = 0;
  59317. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59318. this._mapSize = mapSize;
  59319. this._light = light;
  59320. this._scene = light.getScene();
  59321. light._shadowGenerator = this;
  59322. // Texture type fallback from float to int if not supported.
  59323. var caps = this._scene.getEngine().getCaps();
  59324. if (!useFullFloatFirst) {
  59325. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59326. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59327. }
  59328. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59329. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59330. }
  59331. else {
  59332. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59333. }
  59334. }
  59335. else {
  59336. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59337. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59338. }
  59339. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59340. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59341. }
  59342. else {
  59343. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59344. }
  59345. }
  59346. this._initializeGenerator();
  59347. }
  59348. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59349. /**
  59350. * Shadow generator mode None: no filtering applied.
  59351. */
  59352. get: function () {
  59353. return ShadowGenerator._FILTER_NONE;
  59354. },
  59355. enumerable: true,
  59356. configurable: true
  59357. });
  59358. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59359. /**
  59360. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59361. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59362. */
  59363. get: function () {
  59364. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59365. },
  59366. enumerable: true,
  59367. configurable: true
  59368. });
  59369. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59370. /**
  59371. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59372. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59373. */
  59374. get: function () {
  59375. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59376. },
  59377. enumerable: true,
  59378. configurable: true
  59379. });
  59380. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59381. /**
  59382. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59383. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59384. */
  59385. get: function () {
  59386. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59387. },
  59388. enumerable: true,
  59389. configurable: true
  59390. });
  59391. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59392. /**
  59393. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59394. * edge artifacts on steep falloff.
  59395. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59396. */
  59397. get: function () {
  59398. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59399. },
  59400. enumerable: true,
  59401. configurable: true
  59402. });
  59403. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59404. /**
  59405. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59406. * edge artifacts on steep falloff.
  59407. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59408. */
  59409. get: function () {
  59410. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59411. },
  59412. enumerable: true,
  59413. configurable: true
  59414. });
  59415. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59416. /**
  59417. * Gets the bias: offset applied on the depth preventing acnea.
  59418. */
  59419. get: function () {
  59420. return this._bias;
  59421. },
  59422. /**
  59423. * Sets the bias: offset applied on the depth preventing acnea.
  59424. */
  59425. set: function (bias) {
  59426. this._bias = bias;
  59427. },
  59428. enumerable: true,
  59429. configurable: true
  59430. });
  59431. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59432. /**
  59433. * Gets the blur box offset: offset applied during the blur pass.
  59434. * Only usefull if useKernelBlur = false
  59435. */
  59436. get: function () {
  59437. return this._blurBoxOffset;
  59438. },
  59439. /**
  59440. * Sets the blur box offset: offset applied during the blur pass.
  59441. * Only usefull if useKernelBlur = false
  59442. */
  59443. set: function (value) {
  59444. if (this._blurBoxOffset === value) {
  59445. return;
  59446. }
  59447. this._blurBoxOffset = value;
  59448. this._disposeBlurPostProcesses();
  59449. },
  59450. enumerable: true,
  59451. configurable: true
  59452. });
  59453. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59454. /**
  59455. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59456. * 2 means half of the size.
  59457. */
  59458. get: function () {
  59459. return this._blurScale;
  59460. },
  59461. /**
  59462. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59463. * 2 means half of the size.
  59464. */
  59465. set: function (value) {
  59466. if (this._blurScale === value) {
  59467. return;
  59468. }
  59469. this._blurScale = value;
  59470. this._disposeBlurPostProcesses();
  59471. },
  59472. enumerable: true,
  59473. configurable: true
  59474. });
  59475. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59476. /**
  59477. * Gets the blur kernel: kernel size of the blur pass.
  59478. * Only usefull if useKernelBlur = true
  59479. */
  59480. get: function () {
  59481. return this._blurKernel;
  59482. },
  59483. /**
  59484. * Sets the blur kernel: kernel size of the blur pass.
  59485. * Only usefull if useKernelBlur = true
  59486. */
  59487. set: function (value) {
  59488. if (this._blurKernel === value) {
  59489. return;
  59490. }
  59491. this._blurKernel = value;
  59492. this._disposeBlurPostProcesses();
  59493. },
  59494. enumerable: true,
  59495. configurable: true
  59496. });
  59497. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59498. /**
  59499. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59500. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59501. */
  59502. get: function () {
  59503. return this._useKernelBlur;
  59504. },
  59505. /**
  59506. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59507. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59508. */
  59509. set: function (value) {
  59510. if (this._useKernelBlur === value) {
  59511. return;
  59512. }
  59513. this._useKernelBlur = value;
  59514. this._disposeBlurPostProcesses();
  59515. },
  59516. enumerable: true,
  59517. configurable: true
  59518. });
  59519. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59520. /**
  59521. * Gets the depth scale used in ESM mode.
  59522. */
  59523. get: function () {
  59524. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59525. },
  59526. /**
  59527. * Sets the depth scale used in ESM mode.
  59528. * This can override the scale stored on the light.
  59529. */
  59530. set: function (value) {
  59531. this._depthScale = value;
  59532. },
  59533. enumerable: true,
  59534. configurable: true
  59535. });
  59536. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59537. /**
  59538. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59539. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59540. */
  59541. get: function () {
  59542. return this._filter;
  59543. },
  59544. /**
  59545. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59546. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59547. */
  59548. set: function (value) {
  59549. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59550. if (this._light.needCube()) {
  59551. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59552. this.useExponentialShadowMap = true;
  59553. return;
  59554. }
  59555. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59556. this.useCloseExponentialShadowMap = true;
  59557. return;
  59558. }
  59559. }
  59560. if (this._filter === value) {
  59561. return;
  59562. }
  59563. this._filter = value;
  59564. this._disposeBlurPostProcesses();
  59565. this._applyFilterValues();
  59566. this._light._markMeshesAsLightDirty();
  59567. },
  59568. enumerable: true,
  59569. configurable: true
  59570. });
  59571. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59572. /**
  59573. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59574. */
  59575. get: function () {
  59576. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59577. },
  59578. /**
  59579. * Sets the current filter to Poisson Sampling aka PCF.
  59580. */
  59581. set: function (value) {
  59582. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59583. return;
  59584. }
  59585. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59586. },
  59587. enumerable: true,
  59588. configurable: true
  59589. });
  59590. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59591. /**
  59592. * Gets if the current filter is set to VSM.
  59593. * DEPRECATED. Should use useExponentialShadowMap instead.
  59594. */
  59595. get: function () {
  59596. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59597. return this.useExponentialShadowMap;
  59598. },
  59599. /**
  59600. * Sets the current filter is to VSM.
  59601. * DEPRECATED. Should use useExponentialShadowMap instead.
  59602. */
  59603. set: function (value) {
  59604. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59605. this.useExponentialShadowMap = value;
  59606. },
  59607. enumerable: true,
  59608. configurable: true
  59609. });
  59610. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59611. /**
  59612. * Gets if the current filter is set to blurred VSM.
  59613. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59614. */
  59615. get: function () {
  59616. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59617. return this.useBlurExponentialShadowMap;
  59618. },
  59619. /**
  59620. * Sets the current filter is to blurred VSM.
  59621. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59622. */
  59623. set: function (value) {
  59624. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59625. this.useBlurExponentialShadowMap = value;
  59626. },
  59627. enumerable: true,
  59628. configurable: true
  59629. });
  59630. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59631. /**
  59632. * Gets if the current filter is set to ESM.
  59633. */
  59634. get: function () {
  59635. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59636. },
  59637. /**
  59638. * Sets the current filter is to ESM.
  59639. */
  59640. set: function (value) {
  59641. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59642. return;
  59643. }
  59644. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59645. },
  59646. enumerable: true,
  59647. configurable: true
  59648. });
  59649. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59650. /**
  59651. * Gets if the current filter is set to filtered ESM.
  59652. */
  59653. get: function () {
  59654. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59655. },
  59656. /**
  59657. * Gets if the current filter is set to filtered ESM.
  59658. */
  59659. set: function (value) {
  59660. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59661. return;
  59662. }
  59663. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59664. },
  59665. enumerable: true,
  59666. configurable: true
  59667. });
  59668. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59669. /**
  59670. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59671. * exponential to prevent steep falloff artifacts).
  59672. */
  59673. get: function () {
  59674. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59675. },
  59676. /**
  59677. * Sets the current filter to "close ESM" (using the inverse of the
  59678. * exponential to prevent steep falloff artifacts).
  59679. */
  59680. set: function (value) {
  59681. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59682. return;
  59683. }
  59684. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59685. },
  59686. enumerable: true,
  59687. configurable: true
  59688. });
  59689. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59690. /**
  59691. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59692. * exponential to prevent steep falloff artifacts).
  59693. */
  59694. get: function () {
  59695. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59696. },
  59697. /**
  59698. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59699. * exponential to prevent steep falloff artifacts).
  59700. */
  59701. set: function (value) {
  59702. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59703. return;
  59704. }
  59705. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59706. },
  59707. enumerable: true,
  59708. configurable: true
  59709. });
  59710. /**
  59711. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59712. * 0 means strongest and 1 would means no shadow.
  59713. * @returns the darkness.
  59714. */
  59715. ShadowGenerator.prototype.getDarkness = function () {
  59716. return this._darkness;
  59717. };
  59718. /**
  59719. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59720. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59721. * @returns the shadow generator allowing fluent coding.
  59722. */
  59723. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59724. if (darkness >= 1.0)
  59725. this._darkness = 1.0;
  59726. else if (darkness <= 0.0)
  59727. this._darkness = 0.0;
  59728. else
  59729. this._darkness = darkness;
  59730. return this;
  59731. };
  59732. /**
  59733. * Sets the ability to have transparent shadow (boolean).
  59734. * @param transparent True if transparent else False
  59735. * @returns the shadow generator allowing fluent coding
  59736. */
  59737. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59738. this._transparencyShadow = transparent;
  59739. return this;
  59740. };
  59741. /**
  59742. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59743. * @returns The render target texture if present otherwise, null
  59744. */
  59745. ShadowGenerator.prototype.getShadowMap = function () {
  59746. return this._shadowMap;
  59747. };
  59748. /**
  59749. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59750. * @returns The render target texture if the shadow map is present otherwise, null
  59751. */
  59752. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59753. if (this._shadowMap2) {
  59754. return this._shadowMap2;
  59755. }
  59756. return this._shadowMap;
  59757. };
  59758. /**
  59759. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59760. * @param mesh Mesh to add
  59761. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59762. * @returns the Shadow Generator itself
  59763. */
  59764. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59765. if (includeDescendants === void 0) { includeDescendants = true; }
  59766. if (!this._shadowMap) {
  59767. return this;
  59768. }
  59769. if (!this._shadowMap.renderList) {
  59770. this._shadowMap.renderList = [];
  59771. }
  59772. this._shadowMap.renderList.push(mesh);
  59773. if (includeDescendants) {
  59774. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59775. }
  59776. return this;
  59777. var _a;
  59778. };
  59779. /**
  59780. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59781. * @param mesh Mesh to remove
  59782. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59783. * @returns the Shadow Generator itself
  59784. */
  59785. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59786. if (includeDescendants === void 0) { includeDescendants = true; }
  59787. if (!this._shadowMap || !this._shadowMap.renderList) {
  59788. return this;
  59789. }
  59790. var index = this._shadowMap.renderList.indexOf(mesh);
  59791. if (index !== -1) {
  59792. this._shadowMap.renderList.splice(index, 1);
  59793. }
  59794. if (includeDescendants) {
  59795. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59796. var child = _a[_i];
  59797. this.removeShadowCaster(child);
  59798. }
  59799. }
  59800. return this;
  59801. };
  59802. /**
  59803. * Returns the associated light object.
  59804. * @returns the light generating the shadow
  59805. */
  59806. ShadowGenerator.prototype.getLight = function () {
  59807. return this._light;
  59808. };
  59809. ShadowGenerator.prototype._initializeGenerator = function () {
  59810. this._light._markMeshesAsLightDirty();
  59811. this._initializeShadowMap();
  59812. };
  59813. ShadowGenerator.prototype._initializeShadowMap = function () {
  59814. var _this = this;
  59815. // Render target
  59816. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59817. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59818. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59819. this._shadowMap.anisotropicFilteringLevel = 1;
  59820. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59821. this._shadowMap.renderParticles = false;
  59822. this._shadowMap.ignoreCameraViewport = true;
  59823. // Record Face Index before render.
  59824. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59825. _this._currentFaceIndex = faceIndex;
  59826. });
  59827. // Custom render function.
  59828. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59829. // Blur if required afer render.
  59830. this._shadowMap.onAfterUnbindObservable.add(function () {
  59831. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59832. return;
  59833. }
  59834. var shadowMap = _this.getShadowMapForRendering();
  59835. if (shadowMap) {
  59836. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59837. }
  59838. });
  59839. // Clear according to the chosen filter.
  59840. var zero = new BABYLON.Color4(0, 0, 0, 0);
  59841. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59842. this._shadowMap.onClearObservable.add(function (engine) {
  59843. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59844. engine.clear(zero, true, true, true);
  59845. }
  59846. else {
  59847. engine.clear(one, true, true, true);
  59848. }
  59849. });
  59850. };
  59851. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59852. var _this = this;
  59853. var engine = this._scene.getEngine();
  59854. var targetSize = this._mapSize / this.blurScale;
  59855. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59856. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59857. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59858. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59859. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59860. }
  59861. if (this.useKernelBlur) {
  59862. 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);
  59863. this._kernelBlurXPostprocess.width = targetSize;
  59864. this._kernelBlurXPostprocess.height = targetSize;
  59865. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59866. effect.setTexture("textureSampler", _this._shadowMap);
  59867. });
  59868. 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);
  59869. this._kernelBlurXPostprocess.autoClear = false;
  59870. this._kernelBlurYPostprocess.autoClear = false;
  59871. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59872. this._kernelBlurXPostprocess.packedFloat = true;
  59873. this._kernelBlurYPostprocess.packedFloat = true;
  59874. }
  59875. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59876. }
  59877. else {
  59878. 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);
  59879. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59880. effect.setFloat2("screenSize", targetSize, targetSize);
  59881. effect.setTexture("textureSampler", _this._shadowMap);
  59882. });
  59883. this._boxBlurPostprocess.autoClear = false;
  59884. this._blurPostProcesses = [this._boxBlurPostprocess];
  59885. }
  59886. };
  59887. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59888. var index;
  59889. var engine = this._scene.getEngine();
  59890. if (depthOnlySubMeshes.length) {
  59891. engine.setColorWrite(false);
  59892. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59893. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59894. }
  59895. engine.setColorWrite(true);
  59896. }
  59897. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59898. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59899. }
  59900. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59901. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59902. }
  59903. if (this._transparencyShadow) {
  59904. for (index = 0; index < transparentSubMeshes.length; index++) {
  59905. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59906. }
  59907. }
  59908. };
  59909. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59910. var _this = this;
  59911. var mesh = subMesh.getRenderingMesh();
  59912. var scene = this._scene;
  59913. var engine = scene.getEngine();
  59914. var material = subMesh.getMaterial();
  59915. if (!material) {
  59916. return;
  59917. }
  59918. // Culling
  59919. engine.setState(material.backFaceCulling);
  59920. // Managing instances
  59921. var batch = mesh._getInstancesRenderList(subMesh._id);
  59922. if (batch.mustReturn) {
  59923. return;
  59924. }
  59925. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59926. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59927. engine.enableEffect(this._effect);
  59928. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59929. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59930. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59931. this._effect.setVector3("lightPosition", this.getLight().position);
  59932. if (scene.activeCamera) {
  59933. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59934. }
  59935. // Alpha test
  59936. if (material && material.needAlphaTesting()) {
  59937. var alphaTexture = material.getAlphaTestTexture();
  59938. if (alphaTexture) {
  59939. this._effect.setTexture("diffuseSampler", alphaTexture);
  59940. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59941. }
  59942. }
  59943. // Bones
  59944. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59945. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59946. }
  59947. if (this.forceBackFacesOnly) {
  59948. engine.setState(true, 0, false, true);
  59949. }
  59950. // Draw
  59951. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59952. if (this.forceBackFacesOnly) {
  59953. engine.setState(true, 0, false, false);
  59954. }
  59955. }
  59956. else {
  59957. // Need to reset refresh rate of the shadowMap
  59958. if (this._shadowMap) {
  59959. this._shadowMap.resetRefreshCounter();
  59960. }
  59961. }
  59962. };
  59963. ShadowGenerator.prototype._applyFilterValues = function () {
  59964. if (!this._shadowMap) {
  59965. return;
  59966. }
  59967. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59968. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59969. }
  59970. else {
  59971. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59972. }
  59973. };
  59974. /**
  59975. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59976. * @param onCompiled Callback triggered at the and of the effects compilation
  59977. * @param options Sets of optional options forcing the compilation with different modes
  59978. */
  59979. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59980. var _this = this;
  59981. var localOptions = __assign({ useInstances: false }, options);
  59982. var shadowMap = this.getShadowMap();
  59983. if (!shadowMap) {
  59984. if (onCompiled) {
  59985. onCompiled(this);
  59986. }
  59987. return;
  59988. }
  59989. var renderList = shadowMap.renderList;
  59990. if (!renderList) {
  59991. if (onCompiled) {
  59992. onCompiled(this);
  59993. }
  59994. return;
  59995. }
  59996. var subMeshes = new Array();
  59997. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59998. var mesh = renderList_1[_i];
  59999. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60000. }
  60001. if (subMeshes.length === 0) {
  60002. if (onCompiled) {
  60003. onCompiled(this);
  60004. }
  60005. return;
  60006. }
  60007. var currentIndex = 0;
  60008. var checkReady = function () {
  60009. if (!_this._scene || !_this._scene.getEngine()) {
  60010. return;
  60011. }
  60012. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60013. currentIndex++;
  60014. if (currentIndex >= subMeshes.length) {
  60015. if (onCompiled) {
  60016. onCompiled(_this);
  60017. }
  60018. return;
  60019. }
  60020. }
  60021. setTimeout(checkReady, 16);
  60022. };
  60023. checkReady();
  60024. };
  60025. /**
  60026. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60027. * @param options Sets of optional options forcing the compilation with different modes
  60028. * @returns A promise that resolves when the compilation completes
  60029. */
  60030. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60031. var _this = this;
  60032. return new Promise(function (resolve) {
  60033. _this.forceCompilation(function () {
  60034. resolve();
  60035. }, options);
  60036. });
  60037. };
  60038. /**
  60039. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60040. * @param subMesh The submesh we want to render in the shadow map
  60041. * @param useInstances Defines wether will draw in the map using instances
  60042. * @returns true if ready otherwise, false
  60043. */
  60044. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60045. var defines = [];
  60046. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60047. defines.push("#define FLOAT");
  60048. }
  60049. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60050. defines.push("#define ESM");
  60051. }
  60052. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60053. var mesh = subMesh.getMesh();
  60054. var material = subMesh.getMaterial();
  60055. // Alpha test
  60056. if (material && material.needAlphaTesting()) {
  60057. var alphaTexture = material.getAlphaTestTexture();
  60058. if (alphaTexture) {
  60059. defines.push("#define ALPHATEST");
  60060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60061. attribs.push(BABYLON.VertexBuffer.UVKind);
  60062. defines.push("#define UV1");
  60063. }
  60064. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60065. if (alphaTexture.coordinatesIndex === 1) {
  60066. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60067. defines.push("#define UV2");
  60068. }
  60069. }
  60070. }
  60071. }
  60072. // Bones
  60073. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60074. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60075. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60076. if (mesh.numBoneInfluencers > 4) {
  60077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60079. }
  60080. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60081. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60082. }
  60083. else {
  60084. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60085. }
  60086. // Instances
  60087. if (useInstances) {
  60088. defines.push("#define INSTANCES");
  60089. attribs.push("world0");
  60090. attribs.push("world1");
  60091. attribs.push("world2");
  60092. attribs.push("world3");
  60093. }
  60094. // Get correct effect
  60095. var join = defines.join("\n");
  60096. if (this._cachedDefines !== join) {
  60097. this._cachedDefines = join;
  60098. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60099. }
  60100. if (!this._effect.isReady()) {
  60101. return false;
  60102. }
  60103. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60104. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60105. this._initializeBlurRTTAndPostProcesses();
  60106. }
  60107. }
  60108. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60109. return false;
  60110. }
  60111. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60112. return false;
  60113. }
  60114. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60115. return false;
  60116. }
  60117. return true;
  60118. };
  60119. /**
  60120. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60121. * @param defines Defines of the material we want to update
  60122. * @param lightIndex Index of the light in the enabled light list of the material
  60123. */
  60124. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60125. var scene = this._scene;
  60126. var light = this._light;
  60127. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60128. return;
  60129. }
  60130. defines["SHADOW" + lightIndex] = true;
  60131. if (this.usePoissonSampling) {
  60132. defines["SHADOWPCF" + lightIndex] = true;
  60133. }
  60134. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60135. defines["SHADOWESM" + lightIndex] = true;
  60136. }
  60137. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60138. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60139. }
  60140. if (light.needCube()) {
  60141. defines["SHADOWCUBE" + lightIndex] = true;
  60142. }
  60143. };
  60144. /**
  60145. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60146. * defined in the generator but impacting the effect).
  60147. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60148. * @param effect The effect we are binfing the information for
  60149. */
  60150. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60151. var light = this._light;
  60152. var scene = this._scene;
  60153. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60154. return;
  60155. }
  60156. var camera = scene.activeCamera;
  60157. if (!camera) {
  60158. return;
  60159. }
  60160. var shadowMap = this.getShadowMap();
  60161. if (!shadowMap) {
  60162. return;
  60163. }
  60164. if (!light.needCube()) {
  60165. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60166. }
  60167. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60168. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60169. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60170. };
  60171. /**
  60172. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60173. * (eq to shadow prjection matrix * light transform matrix)
  60174. * @returns The transform matrix used to create the shadow map
  60175. */
  60176. ShadowGenerator.prototype.getTransformMatrix = function () {
  60177. var scene = this._scene;
  60178. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60179. return this._transformMatrix;
  60180. }
  60181. this._currentRenderID = scene.getRenderId();
  60182. this._currentFaceIndexCache = this._currentFaceIndex;
  60183. var lightPosition = this._light.position;
  60184. if (this._light.computeTransformedInformation()) {
  60185. lightPosition = this._light.transformedPosition;
  60186. }
  60187. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60188. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60189. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60190. }
  60191. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60192. this._cachedPosition.copyFrom(lightPosition);
  60193. this._cachedDirection.copyFrom(this._lightDirection);
  60194. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60195. var shadowMap = this.getShadowMap();
  60196. if (shadowMap) {
  60197. var renderList = shadowMap.renderList;
  60198. if (renderList) {
  60199. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60200. }
  60201. }
  60202. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60203. }
  60204. return this._transformMatrix;
  60205. };
  60206. /**
  60207. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60208. * Cube and 2D textures for instance.
  60209. */
  60210. ShadowGenerator.prototype.recreateShadowMap = function () {
  60211. var shadowMap = this._shadowMap;
  60212. if (!shadowMap) {
  60213. return;
  60214. }
  60215. // Track render list.
  60216. var renderList = shadowMap.renderList;
  60217. // Clean up existing data.
  60218. this._disposeRTTandPostProcesses();
  60219. // Reinitializes.
  60220. this._initializeGenerator();
  60221. // Reaffect the filter to ensure a correct fallback if necessary.
  60222. this.filter = this.filter;
  60223. // Reaffect the filter.
  60224. this._applyFilterValues();
  60225. // Reaffect Render List.
  60226. this._shadowMap.renderList = renderList;
  60227. };
  60228. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60229. if (this._shadowMap2) {
  60230. this._shadowMap2.dispose();
  60231. this._shadowMap2 = null;
  60232. }
  60233. if (this._boxBlurPostprocess) {
  60234. this._boxBlurPostprocess.dispose();
  60235. this._boxBlurPostprocess = null;
  60236. }
  60237. if (this._kernelBlurXPostprocess) {
  60238. this._kernelBlurXPostprocess.dispose();
  60239. this._kernelBlurXPostprocess = null;
  60240. }
  60241. if (this._kernelBlurYPostprocess) {
  60242. this._kernelBlurYPostprocess.dispose();
  60243. this._kernelBlurYPostprocess = null;
  60244. }
  60245. this._blurPostProcesses = [];
  60246. };
  60247. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60248. if (this._shadowMap) {
  60249. this._shadowMap.dispose();
  60250. this._shadowMap = null;
  60251. }
  60252. this._disposeBlurPostProcesses();
  60253. };
  60254. /**
  60255. * Disposes the ShadowGenerator.
  60256. * Returns nothing.
  60257. */
  60258. ShadowGenerator.prototype.dispose = function () {
  60259. this._disposeRTTandPostProcesses();
  60260. if (this._light) {
  60261. this._light._shadowGenerator = null;
  60262. this._light._markMeshesAsLightDirty();
  60263. }
  60264. };
  60265. /**
  60266. * Serializes the shadow generator setup to a json object.
  60267. * @returns The serialized JSON object
  60268. */
  60269. ShadowGenerator.prototype.serialize = function () {
  60270. var serializationObject = {};
  60271. var shadowMap = this.getShadowMap();
  60272. if (!shadowMap) {
  60273. return serializationObject;
  60274. }
  60275. serializationObject.lightId = this._light.id;
  60276. serializationObject.mapSize = shadowMap.getRenderSize();
  60277. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60278. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60279. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60280. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60281. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60282. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60283. serializationObject.depthScale = this.depthScale;
  60284. serializationObject.darkness = this.getDarkness();
  60285. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60286. serializationObject.blurKernel = this.blurKernel;
  60287. serializationObject.blurScale = this.blurScale;
  60288. serializationObject.useKernelBlur = this.useKernelBlur;
  60289. serializationObject.transparencyShadow = this._transparencyShadow;
  60290. serializationObject.renderList = [];
  60291. if (shadowMap.renderList) {
  60292. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60293. var mesh = shadowMap.renderList[meshIndex];
  60294. serializationObject.renderList.push(mesh.id);
  60295. }
  60296. }
  60297. return serializationObject;
  60298. };
  60299. /**
  60300. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60301. * @param parsedShadowGenerator The JSON object to parse
  60302. * @param scene The scene to create the shadow map for
  60303. * @returns The parsed shadow generator
  60304. */
  60305. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60306. //casting to point light, as light is missing the position attr and typescript complains.
  60307. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60308. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60309. var shadowMap = shadowGenerator.getShadowMap();
  60310. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60311. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60312. meshes.forEach(function (mesh) {
  60313. if (!shadowMap) {
  60314. return;
  60315. }
  60316. if (!shadowMap.renderList) {
  60317. shadowMap.renderList = [];
  60318. }
  60319. shadowMap.renderList.push(mesh);
  60320. });
  60321. }
  60322. if (parsedShadowGenerator.usePoissonSampling) {
  60323. shadowGenerator.usePoissonSampling = true;
  60324. }
  60325. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60326. shadowGenerator.useExponentialShadowMap = true;
  60327. }
  60328. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60329. shadowGenerator.useBlurExponentialShadowMap = true;
  60330. }
  60331. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60332. shadowGenerator.useCloseExponentialShadowMap = true;
  60333. }
  60334. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60335. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60336. }
  60337. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60338. shadowGenerator.useExponentialShadowMap = true;
  60339. }
  60340. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60341. shadowGenerator.useBlurExponentialShadowMap = true;
  60342. }
  60343. if (parsedShadowGenerator.depthScale) {
  60344. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60345. }
  60346. if (parsedShadowGenerator.blurScale) {
  60347. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60348. }
  60349. if (parsedShadowGenerator.blurBoxOffset) {
  60350. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60351. }
  60352. if (parsedShadowGenerator.useKernelBlur) {
  60353. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60354. }
  60355. if (parsedShadowGenerator.blurKernel) {
  60356. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60357. }
  60358. if (parsedShadowGenerator.bias !== undefined) {
  60359. shadowGenerator.bias = parsedShadowGenerator.bias;
  60360. }
  60361. if (parsedShadowGenerator.darkness) {
  60362. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60363. }
  60364. if (parsedShadowGenerator.transparencyShadow) {
  60365. shadowGenerator.setTransparencyShadow(true);
  60366. }
  60367. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60368. return shadowGenerator;
  60369. };
  60370. ShadowGenerator._FILTER_NONE = 0;
  60371. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60372. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60373. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60374. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60375. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60376. return ShadowGenerator;
  60377. }());
  60378. BABYLON.ShadowGenerator = ShadowGenerator;
  60379. })(BABYLON || (BABYLON = {}));
  60380. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60381. var BABYLON;
  60382. (function (BABYLON) {
  60383. var DefaultLoadingScreen = /** @class */ (function () {
  60384. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60385. if (_loadingText === void 0) { _loadingText = ""; }
  60386. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60387. var _this = this;
  60388. this._renderingCanvas = _renderingCanvas;
  60389. this._loadingText = _loadingText;
  60390. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60391. // Resize
  60392. this._resizeLoadingUI = function () {
  60393. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60394. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60395. if (!_this._loadingDiv) {
  60396. return;
  60397. }
  60398. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60399. _this._loadingDiv.style.left = canvasRect.left + "px";
  60400. _this._loadingDiv.style.top = canvasRect.top + "px";
  60401. _this._loadingDiv.style.width = canvasRect.width + "px";
  60402. _this._loadingDiv.style.height = canvasRect.height + "px";
  60403. };
  60404. }
  60405. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60406. if (this._loadingDiv) {
  60407. // Do not add a loading screen if there is already one
  60408. return;
  60409. }
  60410. this._loadingDiv = document.createElement("div");
  60411. this._loadingDiv.id = "babylonjsLoadingDiv";
  60412. this._loadingDiv.style.opacity = "0";
  60413. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60414. this._loadingDiv.style.pointerEvents = "none";
  60415. // Loading text
  60416. this._loadingTextDiv = document.createElement("div");
  60417. this._loadingTextDiv.style.position = "absolute";
  60418. this._loadingTextDiv.style.left = "0";
  60419. this._loadingTextDiv.style.top = "50%";
  60420. this._loadingTextDiv.style.marginTop = "80px";
  60421. this._loadingTextDiv.style.width = "100%";
  60422. this._loadingTextDiv.style.height = "20px";
  60423. this._loadingTextDiv.style.fontFamily = "Arial";
  60424. this._loadingTextDiv.style.fontSize = "14px";
  60425. this._loadingTextDiv.style.color = "white";
  60426. this._loadingTextDiv.style.textAlign = "center";
  60427. this._loadingTextDiv.innerHTML = "Loading";
  60428. this._loadingDiv.appendChild(this._loadingTextDiv);
  60429. //set the predefined text
  60430. this._loadingTextDiv.innerHTML = this._loadingText;
  60431. // Generating keyframes
  60432. var style = document.createElement('style');
  60433. style.type = 'text/css';
  60434. 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 }";
  60435. style.innerHTML = keyFrames;
  60436. document.getElementsByTagName('head')[0].appendChild(style);
  60437. // Loading img
  60438. var imgBack = new Image();
  60439. 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";
  60440. imgBack.style.position = "absolute";
  60441. imgBack.style.left = "50%";
  60442. imgBack.style.top = "50%";
  60443. imgBack.style.marginLeft = "-60px";
  60444. imgBack.style.marginTop = "-60px";
  60445. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60446. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60447. imgBack.style.transformOrigin = "50% 50%";
  60448. imgBack.style.webkitTransformOrigin = "50% 50%";
  60449. this._loadingDiv.appendChild(imgBack);
  60450. this._resizeLoadingUI();
  60451. window.addEventListener("resize", this._resizeLoadingUI);
  60452. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60453. document.body.appendChild(this._loadingDiv);
  60454. this._loadingDiv.style.opacity = "1";
  60455. };
  60456. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60457. var _this = this;
  60458. if (!this._loadingDiv) {
  60459. return;
  60460. }
  60461. var onTransitionEnd = function () {
  60462. if (!_this._loadingDiv) {
  60463. return;
  60464. }
  60465. document.body.removeChild(_this._loadingDiv);
  60466. window.removeEventListener("resize", _this._resizeLoadingUI);
  60467. _this._loadingDiv = null;
  60468. };
  60469. this._loadingDiv.style.opacity = "0";
  60470. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60471. };
  60472. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60473. set: function (text) {
  60474. this._loadingText = text;
  60475. if (this._loadingTextDiv) {
  60476. this._loadingTextDiv.innerHTML = this._loadingText;
  60477. }
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60483. get: function () {
  60484. return this._loadingDivBackgroundColor;
  60485. },
  60486. set: function (color) {
  60487. this._loadingDivBackgroundColor = color;
  60488. if (!this._loadingDiv) {
  60489. return;
  60490. }
  60491. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60492. },
  60493. enumerable: true,
  60494. configurable: true
  60495. });
  60496. return DefaultLoadingScreen;
  60497. }());
  60498. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60499. })(BABYLON || (BABYLON = {}));
  60500. //# sourceMappingURL=babylon.loadingScreen.js.map
  60501. var BABYLON;
  60502. (function (BABYLON) {
  60503. var SceneLoaderProgressEvent = /** @class */ (function () {
  60504. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60505. this.lengthComputable = lengthComputable;
  60506. this.loaded = loaded;
  60507. this.total = total;
  60508. }
  60509. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60510. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60511. };
  60512. return SceneLoaderProgressEvent;
  60513. }());
  60514. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60515. var SceneLoader = /** @class */ (function () {
  60516. function SceneLoader() {
  60517. }
  60518. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60519. get: function () {
  60520. return 0;
  60521. },
  60522. enumerable: true,
  60523. configurable: true
  60524. });
  60525. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60526. get: function () {
  60527. return 1;
  60528. },
  60529. enumerable: true,
  60530. configurable: true
  60531. });
  60532. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60533. get: function () {
  60534. return 2;
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60540. get: function () {
  60541. return 3;
  60542. },
  60543. enumerable: true,
  60544. configurable: true
  60545. });
  60546. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60547. get: function () {
  60548. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60549. },
  60550. set: function (value) {
  60551. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60552. },
  60553. enumerable: true,
  60554. configurable: true
  60555. });
  60556. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60557. get: function () {
  60558. return SceneLoader._ShowLoadingScreen;
  60559. },
  60560. set: function (value) {
  60561. SceneLoader._ShowLoadingScreen = value;
  60562. },
  60563. enumerable: true,
  60564. configurable: true
  60565. });
  60566. Object.defineProperty(SceneLoader, "loggingLevel", {
  60567. get: function () {
  60568. return SceneLoader._loggingLevel;
  60569. },
  60570. set: function (value) {
  60571. SceneLoader._loggingLevel = value;
  60572. },
  60573. enumerable: true,
  60574. configurable: true
  60575. });
  60576. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60577. get: function () {
  60578. return SceneLoader._CleanBoneMatrixWeights;
  60579. },
  60580. set: function (value) {
  60581. SceneLoader._CleanBoneMatrixWeights = value;
  60582. },
  60583. enumerable: true,
  60584. configurable: true
  60585. });
  60586. SceneLoader._getDefaultPlugin = function () {
  60587. return SceneLoader._registeredPlugins[".babylon"];
  60588. };
  60589. SceneLoader._getPluginForExtension = function (extension) {
  60590. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60591. if (registeredPlugin) {
  60592. return registeredPlugin;
  60593. }
  60594. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60595. return SceneLoader._getDefaultPlugin();
  60596. };
  60597. SceneLoader._getPluginForDirectLoad = function (data) {
  60598. for (var extension in SceneLoader._registeredPlugins) {
  60599. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60600. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60601. return SceneLoader._registeredPlugins[extension];
  60602. }
  60603. }
  60604. return SceneLoader._getDefaultPlugin();
  60605. };
  60606. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60607. if (sceneFilename.name) {
  60608. sceneFilename = sceneFilename.name;
  60609. }
  60610. var queryStringPosition = sceneFilename.indexOf("?");
  60611. if (queryStringPosition !== -1) {
  60612. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60613. }
  60614. var dotPosition = sceneFilename.lastIndexOf(".");
  60615. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60616. return SceneLoader._getPluginForExtension(extension);
  60617. };
  60618. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60619. SceneLoader._getDirectLoad = function (sceneFilename) {
  60620. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60621. return sceneFilename.substr(5);
  60622. }
  60623. return null;
  60624. };
  60625. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60626. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60627. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60628. var plugin;
  60629. if (registeredPlugin.plugin.createPlugin) {
  60630. plugin = registeredPlugin.plugin.createPlugin();
  60631. }
  60632. else {
  60633. plugin = registeredPlugin.plugin;
  60634. }
  60635. var useArrayBuffer = registeredPlugin.isBinary;
  60636. var database;
  60637. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60638. var dataCallback = function (data, responseURL) {
  60639. if (scene.isDisposed) {
  60640. onError("Scene has been disposed");
  60641. return;
  60642. }
  60643. scene.database = database;
  60644. onSuccess(plugin, data, responseURL);
  60645. };
  60646. var request = null;
  60647. var pluginDisposed = false;
  60648. var onDisposeObservable = plugin.onDisposeObservable;
  60649. if (onDisposeObservable) {
  60650. onDisposeObservable.add(function () {
  60651. pluginDisposed = true;
  60652. if (request) {
  60653. request.abort();
  60654. request = null;
  60655. }
  60656. onDispose();
  60657. });
  60658. }
  60659. var manifestChecked = function () {
  60660. if (pluginDisposed) {
  60661. return;
  60662. }
  60663. var url = rootUrl + sceneFilename;
  60664. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60665. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60666. } : undefined, database, useArrayBuffer, function (request, exception) {
  60667. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60668. });
  60669. };
  60670. if (directLoad) {
  60671. dataCallback(directLoad);
  60672. return plugin;
  60673. }
  60674. if (rootUrl.indexOf("file:") === -1) {
  60675. if (scene.getEngine().enableOfflineSupport) {
  60676. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60677. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60678. }
  60679. else {
  60680. manifestChecked();
  60681. }
  60682. }
  60683. else {
  60684. var fileOrString = sceneFilename;
  60685. if (fileOrString.name) {
  60686. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60687. }
  60688. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60689. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60690. }
  60691. else {
  60692. onError("Unable to find file named " + sceneFilename);
  60693. }
  60694. }
  60695. return plugin;
  60696. };
  60697. // Public functions
  60698. SceneLoader.GetPluginForExtension = function (extension) {
  60699. return SceneLoader._getPluginForExtension(extension).plugin;
  60700. };
  60701. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60702. return !!SceneLoader._registeredPlugins[extension];
  60703. };
  60704. SceneLoader.RegisterPlugin = function (plugin) {
  60705. if (typeof plugin.extensions === "string") {
  60706. var extension = plugin.extensions;
  60707. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60708. plugin: plugin,
  60709. isBinary: false
  60710. };
  60711. }
  60712. else {
  60713. var extensions = plugin.extensions;
  60714. Object.keys(extensions).forEach(function (extension) {
  60715. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60716. plugin: plugin,
  60717. isBinary: extensions[extension].isBinary
  60718. };
  60719. });
  60720. }
  60721. };
  60722. /**
  60723. * Import meshes into a scene
  60724. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60725. * @param rootUrl a string that defines the root url for scene and resources
  60726. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60727. * @param scene the instance of BABYLON.Scene to append to
  60728. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60729. * @param onProgress a callback with a progress event for each file being loaded
  60730. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60731. * @param pluginExtension the extension used to determine the plugin
  60732. * @returns The loaded plugin
  60733. */
  60734. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60735. if (onSuccess === void 0) { onSuccess = null; }
  60736. if (onProgress === void 0) { onProgress = null; }
  60737. if (onError === void 0) { onError = null; }
  60738. if (pluginExtension === void 0) { pluginExtension = null; }
  60739. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60740. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60741. return null;
  60742. }
  60743. var loadingToken = {};
  60744. scene._addPendingData(loadingToken);
  60745. var disposeHandler = function () {
  60746. scene._removePendingData(loadingToken);
  60747. };
  60748. var errorHandler = function (message, exception) {
  60749. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60750. if (onError) {
  60751. onError(scene, errorMessage, exception);
  60752. }
  60753. else {
  60754. BABYLON.Tools.Error(errorMessage);
  60755. // should the exception be thrown?
  60756. }
  60757. disposeHandler();
  60758. };
  60759. var progressHandler = onProgress ? function (event) {
  60760. try {
  60761. onProgress(event);
  60762. }
  60763. catch (e) {
  60764. errorHandler("Error in onProgress callback", e);
  60765. }
  60766. } : undefined;
  60767. var successHandler = function (meshes, particleSystems, skeletons) {
  60768. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60769. if (onSuccess) {
  60770. try {
  60771. onSuccess(meshes, particleSystems, skeletons);
  60772. }
  60773. catch (e) {
  60774. errorHandler("Error in onSuccess callback", e);
  60775. }
  60776. }
  60777. scene._removePendingData(loadingToken);
  60778. };
  60779. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60780. if (plugin.rewriteRootURL) {
  60781. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60782. }
  60783. if (sceneFilename === "") {
  60784. if (sceneFilename === "") {
  60785. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60786. }
  60787. }
  60788. if (plugin.importMesh) {
  60789. var syncedPlugin = plugin;
  60790. var meshes = new Array();
  60791. var particleSystems = new Array();
  60792. var skeletons = new Array();
  60793. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60794. return;
  60795. }
  60796. scene.loadingPluginName = plugin.name;
  60797. successHandler(meshes, particleSystems, skeletons);
  60798. }
  60799. else {
  60800. var asyncedPlugin = plugin;
  60801. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60802. scene.loadingPluginName = plugin.name;
  60803. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60804. }).catch(function (error) {
  60805. errorHandler(error.message, error);
  60806. });
  60807. }
  60808. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60809. };
  60810. /**
  60811. * Import meshes into a scene
  60812. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60813. * @param rootUrl a string that defines the root url for scene and resources
  60814. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60815. * @param scene the instance of BABYLON.Scene to append to
  60816. * @param onProgress a callback with a progress event for each file being loaded
  60817. * @param pluginExtension the extension used to determine the plugin
  60818. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60819. */
  60820. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60821. if (onProgress === void 0) { onProgress = null; }
  60822. if (pluginExtension === void 0) { pluginExtension = null; }
  60823. return new Promise(function (resolve, reject) {
  60824. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60825. resolve({
  60826. meshes: meshes,
  60827. particleSystems: particleSystems,
  60828. skeletons: skeletons
  60829. });
  60830. }, onProgress, function (scene, message, exception) {
  60831. reject(exception || new Error(message));
  60832. });
  60833. });
  60834. };
  60835. /**
  60836. * Load a scene
  60837. * @param rootUrl a string that defines the root url for scene and resources
  60838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60839. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60840. * @param onSuccess a callback with the scene when import succeeds
  60841. * @param onProgress a callback with a progress event for each file being loaded
  60842. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60843. * @param pluginExtension the extension used to determine the plugin
  60844. * @returns The loaded plugin
  60845. */
  60846. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60847. if (onSuccess === void 0) { onSuccess = null; }
  60848. if (onProgress === void 0) { onProgress = null; }
  60849. if (onError === void 0) { onError = null; }
  60850. if (pluginExtension === void 0) { pluginExtension = null; }
  60851. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60852. };
  60853. /**
  60854. * Load a scene
  60855. * @param rootUrl a string that defines the root url for scene and resources
  60856. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60857. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60858. * @param onProgress a callback with a progress event for each file being loaded
  60859. * @param pluginExtension the extension used to determine the plugin
  60860. * @returns The loaded scene
  60861. */
  60862. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60863. if (onProgress === void 0) { onProgress = null; }
  60864. if (pluginExtension === void 0) { pluginExtension = null; }
  60865. return new Promise(function (resolve, reject) {
  60866. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60867. resolve(scene);
  60868. }, onProgress, function (scene, message, exception) {
  60869. reject(exception || new Error(message));
  60870. }, pluginExtension);
  60871. });
  60872. };
  60873. /**
  60874. * Append a scene
  60875. * @param rootUrl a string that defines the root url for scene and resources
  60876. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60877. * @param scene is the instance of BABYLON.Scene to append to
  60878. * @param onSuccess a callback with the scene when import succeeds
  60879. * @param onProgress a callback with a progress event for each file being loaded
  60880. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60881. * @param pluginExtension the extension used to determine the plugin
  60882. * @returns The loaded plugin
  60883. */
  60884. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60885. if (onSuccess === void 0) { onSuccess = null; }
  60886. if (onProgress === void 0) { onProgress = null; }
  60887. if (onError === void 0) { onError = null; }
  60888. if (pluginExtension === void 0) { pluginExtension = null; }
  60889. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60890. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60891. return null;
  60892. }
  60893. if (SceneLoader.ShowLoadingScreen) {
  60894. scene.getEngine().displayLoadingUI();
  60895. }
  60896. var loadingToken = {};
  60897. scene._addPendingData(loadingToken);
  60898. var disposeHandler = function () {
  60899. scene._removePendingData(loadingToken);
  60900. scene.getEngine().hideLoadingUI();
  60901. };
  60902. var errorHandler = function (message, exception) {
  60903. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60904. if (onError) {
  60905. onError(scene, errorMessage, exception);
  60906. }
  60907. else {
  60908. BABYLON.Tools.Error(errorMessage);
  60909. // should the exception be thrown?
  60910. }
  60911. disposeHandler();
  60912. };
  60913. var progressHandler = onProgress ? function (event) {
  60914. try {
  60915. onProgress(event);
  60916. }
  60917. catch (e) {
  60918. errorHandler("Error in onProgress callback", e);
  60919. }
  60920. } : undefined;
  60921. var successHandler = function () {
  60922. if (onSuccess) {
  60923. try {
  60924. onSuccess(scene);
  60925. }
  60926. catch (e) {
  60927. errorHandler("Error in onSuccess callback", e);
  60928. }
  60929. }
  60930. scene._removePendingData(loadingToken);
  60931. };
  60932. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60933. if (sceneFilename === "") {
  60934. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60935. }
  60936. if (plugin.load) {
  60937. var syncedPlugin = plugin;
  60938. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60939. return;
  60940. }
  60941. scene.loadingPluginName = plugin.name;
  60942. successHandler();
  60943. }
  60944. else {
  60945. var asyncedPlugin = plugin;
  60946. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60947. scene.loadingPluginName = plugin.name;
  60948. successHandler();
  60949. }).catch(function (error) {
  60950. errorHandler(error.message, error);
  60951. });
  60952. }
  60953. if (SceneLoader.ShowLoadingScreen) {
  60954. scene.executeWhenReady(function () {
  60955. scene.getEngine().hideLoadingUI();
  60956. });
  60957. }
  60958. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60959. };
  60960. /**
  60961. * Append a scene
  60962. * @param rootUrl a string that defines the root url for scene and resources
  60963. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60964. * @param scene is the instance of BABYLON.Scene to append to
  60965. * @param onProgress a callback with a progress event for each file being loaded
  60966. * @param pluginExtension the extension used to determine the plugin
  60967. * @returns The given scene
  60968. */
  60969. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60970. if (onProgress === void 0) { onProgress = null; }
  60971. if (pluginExtension === void 0) { pluginExtension = null; }
  60972. return new Promise(function (resolve, reject) {
  60973. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60974. resolve(scene);
  60975. }, onProgress, function (scene, message, exception) {
  60976. reject(exception || new Error(message));
  60977. }, pluginExtension);
  60978. });
  60979. };
  60980. /**
  60981. * Load a scene into an asset container
  60982. * @param rootUrl a string that defines the root url for scene and resources
  60983. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60984. * @param scene is the instance of BABYLON.Scene to append to
  60985. * @param onSuccess a callback with the scene when import succeeds
  60986. * @param onProgress a callback with a progress event for each file being loaded
  60987. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60988. * @param pluginExtension the extension used to determine the plugin
  60989. * @returns The loaded plugin
  60990. */
  60991. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60992. if (onSuccess === void 0) { onSuccess = null; }
  60993. if (onProgress === void 0) { onProgress = null; }
  60994. if (onError === void 0) { onError = null; }
  60995. if (pluginExtension === void 0) { pluginExtension = null; }
  60996. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60997. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60998. return null;
  60999. }
  61000. var loadingToken = {};
  61001. scene._addPendingData(loadingToken);
  61002. var disposeHandler = function () {
  61003. scene._removePendingData(loadingToken);
  61004. };
  61005. var errorHandler = function (message, exception) {
  61006. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61007. if (onError) {
  61008. onError(scene, errorMessage, exception);
  61009. }
  61010. else {
  61011. BABYLON.Tools.Error(errorMessage);
  61012. // should the exception be thrown?
  61013. }
  61014. disposeHandler();
  61015. };
  61016. var progressHandler = onProgress ? function (event) {
  61017. try {
  61018. onProgress(event);
  61019. }
  61020. catch (e) {
  61021. errorHandler("Error in onProgress callback", e);
  61022. }
  61023. } : undefined;
  61024. var successHandler = function (assets) {
  61025. if (onSuccess) {
  61026. try {
  61027. onSuccess(assets);
  61028. }
  61029. catch (e) {
  61030. errorHandler("Error in onSuccess callback", e);
  61031. }
  61032. }
  61033. scene._removePendingData(loadingToken);
  61034. };
  61035. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61036. if (plugin.loadAssetContainer) {
  61037. var syncedPlugin = plugin;
  61038. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61039. if (!assetContainer) {
  61040. return;
  61041. }
  61042. scene.loadingPluginName = plugin.name;
  61043. successHandler(assetContainer);
  61044. }
  61045. else if (plugin.loadAssetContainerAsync) {
  61046. var asyncedPlugin = plugin;
  61047. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61048. scene.loadingPluginName = plugin.name;
  61049. successHandler(assetContainer);
  61050. }).catch(function (error) {
  61051. errorHandler(error.message, error);
  61052. });
  61053. }
  61054. else {
  61055. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61056. }
  61057. if (SceneLoader.ShowLoadingScreen) {
  61058. scene.executeWhenReady(function () {
  61059. scene.getEngine().hideLoadingUI();
  61060. });
  61061. }
  61062. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61063. };
  61064. /**
  61065. * Load a scene into an asset container
  61066. * @param rootUrl a string that defines the root url for scene and resources
  61067. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61068. * @param scene is the instance of BABYLON.Scene to append to
  61069. * @param onProgress a callback with a progress event for each file being loaded
  61070. * @param pluginExtension the extension used to determine the plugin
  61071. * @returns The loaded asset container
  61072. */
  61073. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61074. if (onProgress === void 0) { onProgress = null; }
  61075. if (pluginExtension === void 0) { pluginExtension = null; }
  61076. return new Promise(function (resolve, reject) {
  61077. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61078. resolve(assetContainer);
  61079. }, onProgress, function (scene, message, exception) {
  61080. reject(exception || new Error(message));
  61081. }, pluginExtension);
  61082. });
  61083. };
  61084. // Flags
  61085. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61086. SceneLoader._ShowLoadingScreen = true;
  61087. SceneLoader._CleanBoneMatrixWeights = false;
  61088. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61089. // Members
  61090. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61091. SceneLoader._registeredPlugins = {};
  61092. return SceneLoader;
  61093. }());
  61094. BABYLON.SceneLoader = SceneLoader;
  61095. ;
  61096. })(BABYLON || (BABYLON = {}));
  61097. //# sourceMappingURL=babylon.sceneLoader.js.map
  61098. var BABYLON;
  61099. (function (BABYLON) {
  61100. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61101. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61102. var parsedMaterial = parsedData.materials[index];
  61103. if (parsedMaterial.id === id) {
  61104. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61105. }
  61106. }
  61107. return null;
  61108. };
  61109. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61110. for (var i in names) {
  61111. if (mesh.name === names[i]) {
  61112. hierarchyIds.push(mesh.id);
  61113. return true;
  61114. }
  61115. }
  61116. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61117. hierarchyIds.push(mesh.id);
  61118. return true;
  61119. }
  61120. return false;
  61121. };
  61122. var logOperation = function (operation, producer) {
  61123. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61124. };
  61125. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61126. if (addToScene === void 0) { addToScene = false; }
  61127. var container = new BABYLON.AssetContainer(scene);
  61128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61131. // and avoid problems with multiple concurrent .babylon loads.
  61132. var log = "importScene has failed JSON parse";
  61133. try {
  61134. var parsedData = JSON.parse(data);
  61135. log = "";
  61136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61137. var index;
  61138. var cache;
  61139. // Lights
  61140. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61141. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61142. var parsedLight = parsedData.lights[index];
  61143. var light = BABYLON.Light.Parse(parsedLight, scene);
  61144. if (light) {
  61145. container.lights.push(light);
  61146. log += (index === 0 ? "\n\tLights:" : "");
  61147. log += "\n\t\t" + light.toString(fullDetails);
  61148. }
  61149. }
  61150. }
  61151. // Animations
  61152. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61153. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61154. var parsedAnimation = parsedData.animations[index];
  61155. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61156. scene.animations.push(animation);
  61157. container.animations.push(animation);
  61158. log += (index === 0 ? "\n\tAnimations:" : "");
  61159. log += "\n\t\t" + animation.toString(fullDetails);
  61160. }
  61161. }
  61162. // Materials
  61163. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61164. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61165. var parsedMaterial = parsedData.materials[index];
  61166. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61167. container.materials.push(mat);
  61168. log += (index === 0 ? "\n\tMaterials:" : "");
  61169. log += "\n\t\t" + mat.toString(fullDetails);
  61170. }
  61171. }
  61172. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61173. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61174. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61175. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61176. container.multiMaterials.push(mmat);
  61177. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61178. log += "\n\t\t" + mmat.toString(fullDetails);
  61179. }
  61180. }
  61181. // Morph targets
  61182. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61183. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61184. var managerData = _a[_i];
  61185. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61186. }
  61187. }
  61188. // Skeletons
  61189. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61190. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61191. var parsedSkeleton = parsedData.skeletons[index];
  61192. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61193. container.skeletons.push(skeleton);
  61194. log += (index === 0 ? "\n\tSkeletons:" : "");
  61195. log += "\n\t\t" + skeleton.toString(fullDetails);
  61196. }
  61197. }
  61198. // Geometries
  61199. var geometries = parsedData.geometries;
  61200. if (geometries !== undefined && geometries !== null) {
  61201. var addedGeometry = new Array();
  61202. // Boxes
  61203. var boxes = geometries.boxes;
  61204. if (boxes !== undefined && boxes !== null) {
  61205. for (index = 0, cache = boxes.length; index < cache; index++) {
  61206. var parsedBox = boxes[index];
  61207. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61208. }
  61209. }
  61210. // Spheres
  61211. var spheres = geometries.spheres;
  61212. if (spheres !== undefined && spheres !== null) {
  61213. for (index = 0, cache = spheres.length; index < cache; index++) {
  61214. var parsedSphere = spheres[index];
  61215. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61216. }
  61217. }
  61218. // Cylinders
  61219. var cylinders = geometries.cylinders;
  61220. if (cylinders !== undefined && cylinders !== null) {
  61221. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61222. var parsedCylinder = cylinders[index];
  61223. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61224. }
  61225. }
  61226. // Toruses
  61227. var toruses = geometries.toruses;
  61228. if (toruses !== undefined && toruses !== null) {
  61229. for (index = 0, cache = toruses.length; index < cache; index++) {
  61230. var parsedTorus = toruses[index];
  61231. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61232. }
  61233. }
  61234. // Grounds
  61235. var grounds = geometries.grounds;
  61236. if (grounds !== undefined && grounds !== null) {
  61237. for (index = 0, cache = grounds.length; index < cache; index++) {
  61238. var parsedGround = grounds[index];
  61239. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61240. }
  61241. }
  61242. // Planes
  61243. var planes = geometries.planes;
  61244. if (planes !== undefined && planes !== null) {
  61245. for (index = 0, cache = planes.length; index < cache; index++) {
  61246. var parsedPlane = planes[index];
  61247. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61248. }
  61249. }
  61250. // TorusKnots
  61251. var torusKnots = geometries.torusKnots;
  61252. if (torusKnots !== undefined && torusKnots !== null) {
  61253. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61254. var parsedTorusKnot = torusKnots[index];
  61255. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61256. }
  61257. }
  61258. // VertexData
  61259. var vertexData = geometries.vertexData;
  61260. if (vertexData !== undefined && vertexData !== null) {
  61261. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61262. var parsedVertexData = vertexData[index];
  61263. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61264. }
  61265. }
  61266. addedGeometry.forEach(function (g) {
  61267. if (g) {
  61268. container.geometries.push(g);
  61269. }
  61270. });
  61271. }
  61272. // Transform nodes
  61273. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61274. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61275. var parsedTransformNode = parsedData.transformNodes[index];
  61276. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61277. container.transformNodes.push(node);
  61278. }
  61279. }
  61280. // Meshes
  61281. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61282. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61283. var parsedMesh = parsedData.meshes[index];
  61284. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61285. container.meshes.push(mesh);
  61286. log += (index === 0 ? "\n\tMeshes:" : "");
  61287. log += "\n\t\t" + mesh.toString(fullDetails);
  61288. }
  61289. }
  61290. // Cameras
  61291. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61292. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61293. var parsedCamera = parsedData.cameras[index];
  61294. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61295. container.cameras.push(camera);
  61296. log += (index === 0 ? "\n\tCameras:" : "");
  61297. log += "\n\t\t" + camera.toString(fullDetails);
  61298. }
  61299. }
  61300. // Browsing all the graph to connect the dots
  61301. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61302. var camera = scene.cameras[index];
  61303. if (camera._waitingParentId) {
  61304. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61305. camera._waitingParentId = null;
  61306. }
  61307. }
  61308. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61309. var light_1 = scene.lights[index];
  61310. if (light_1 && light_1._waitingParentId) {
  61311. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61312. light_1._waitingParentId = null;
  61313. }
  61314. }
  61315. // Sounds
  61316. // TODO: add sound
  61317. var loadedSounds = [];
  61318. var loadedSound;
  61319. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61320. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61321. var parsedSound = parsedData.sounds[index];
  61322. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61323. if (!parsedSound.url)
  61324. parsedSound.url = parsedSound.name;
  61325. if (!loadedSounds[parsedSound.url]) {
  61326. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61327. loadedSounds[parsedSound.url] = loadedSound;
  61328. container.sounds.push(loadedSound);
  61329. }
  61330. else {
  61331. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61332. }
  61333. }
  61334. else {
  61335. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61336. }
  61337. }
  61338. }
  61339. loadedSounds = [];
  61340. // Connect parents & children and parse actions
  61341. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61342. var transformNode = scene.transformNodes[index];
  61343. if (transformNode._waitingParentId) {
  61344. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61345. transformNode._waitingParentId = null;
  61346. }
  61347. }
  61348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61349. var mesh = scene.meshes[index];
  61350. if (mesh._waitingParentId) {
  61351. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61352. mesh._waitingParentId = null;
  61353. }
  61354. if (mesh._waitingActions) {
  61355. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61356. mesh._waitingActions = null;
  61357. }
  61358. }
  61359. // freeze world matrix application
  61360. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61361. var currentMesh = scene.meshes[index];
  61362. if (currentMesh._waitingFreezeWorldMatrix) {
  61363. currentMesh.freezeWorldMatrix();
  61364. currentMesh._waitingFreezeWorldMatrix = null;
  61365. }
  61366. else {
  61367. currentMesh.computeWorldMatrix(true);
  61368. }
  61369. }
  61370. // Particles Systems
  61371. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61372. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61373. var parsedParticleSystem = parsedData.particleSystems[index];
  61374. if (parsedParticleSystem.activeParticleCount) {
  61375. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61376. container.particleSystems.push(ps);
  61377. }
  61378. else {
  61379. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61380. container.particleSystems.push(ps);
  61381. }
  61382. }
  61383. }
  61384. // Lens flares
  61385. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61386. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61387. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61388. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61389. container.lensFlareSystems.push(lf);
  61390. }
  61391. }
  61392. // Shadows
  61393. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61394. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61395. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61396. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61397. container.shadowGenerators.push(sg);
  61398. }
  61399. }
  61400. // Lights exclusions / inclusions
  61401. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61402. var light_2 = scene.lights[index];
  61403. // Excluded check
  61404. if (light_2._excludedMeshesIds.length > 0) {
  61405. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61406. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61407. if (excludedMesh) {
  61408. light_2.excludedMeshes.push(excludedMesh);
  61409. }
  61410. }
  61411. light_2._excludedMeshesIds = [];
  61412. }
  61413. // Included check
  61414. if (light_2._includedOnlyMeshesIds.length > 0) {
  61415. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61416. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61417. if (includedOnlyMesh) {
  61418. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61419. }
  61420. }
  61421. light_2._includedOnlyMeshesIds = [];
  61422. }
  61423. }
  61424. // Actions (scene)
  61425. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61426. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61427. }
  61428. if (!addToScene) {
  61429. container.removeAllFromScene();
  61430. }
  61431. }
  61432. catch (err) {
  61433. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61434. if (onError) {
  61435. onError(msg, err);
  61436. }
  61437. else {
  61438. BABYLON.Tools.Log(msg);
  61439. throw err;
  61440. }
  61441. }
  61442. finally {
  61443. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61444. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61445. }
  61446. }
  61447. return container;
  61448. };
  61449. BABYLON.SceneLoader.RegisterPlugin({
  61450. name: "babylon.js",
  61451. extensions: ".babylon",
  61452. canDirectLoad: function (data) {
  61453. if (data.indexOf("babylon") !== -1) {
  61454. return true;
  61455. }
  61456. return false;
  61457. },
  61458. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61459. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61460. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61461. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61462. // and avoid problems with multiple concurrent .babylon loads.
  61463. var log = "importMesh has failed JSON parse";
  61464. try {
  61465. var parsedData = JSON.parse(data);
  61466. log = "";
  61467. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61468. if (!meshesNames) {
  61469. meshesNames = null;
  61470. }
  61471. else if (!Array.isArray(meshesNames)) {
  61472. meshesNames = [meshesNames];
  61473. }
  61474. var hierarchyIds = new Array();
  61475. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61476. var loadedSkeletonsIds = [];
  61477. var loadedMaterialsIds = [];
  61478. var index;
  61479. var cache;
  61480. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61481. var parsedMesh = parsedData.meshes[index];
  61482. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61483. if (meshesNames !== null) {
  61484. // Remove found mesh name from list.
  61485. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61486. }
  61487. //Geometry?
  61488. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61489. //does the file contain geometries?
  61490. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61491. //find the correct geometry and add it to the scene
  61492. var found = false;
  61493. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61494. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61495. return;
  61496. }
  61497. else {
  61498. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61499. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61500. switch (geometryType) {
  61501. case "boxes":
  61502. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61503. break;
  61504. case "spheres":
  61505. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61506. break;
  61507. case "cylinders":
  61508. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61509. break;
  61510. case "toruses":
  61511. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61512. break;
  61513. case "grounds":
  61514. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61515. break;
  61516. case "planes":
  61517. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61518. break;
  61519. case "torusKnots":
  61520. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61521. break;
  61522. case "vertexData":
  61523. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61524. break;
  61525. }
  61526. found = true;
  61527. }
  61528. });
  61529. }
  61530. });
  61531. if (found === false) {
  61532. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61533. }
  61534. }
  61535. }
  61536. // Material ?
  61537. if (parsedMesh.materialId) {
  61538. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61539. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61540. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61541. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61542. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61543. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61544. var subMatId = parsedMultiMaterial.materials[matIndex];
  61545. loadedMaterialsIds.push(subMatId);
  61546. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61547. if (mat) {
  61548. log += "\n\tMaterial " + mat.toString(fullDetails);
  61549. }
  61550. }
  61551. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61552. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61553. if (mmat) {
  61554. materialFound = true;
  61555. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61556. }
  61557. break;
  61558. }
  61559. }
  61560. }
  61561. if (materialFound === false) {
  61562. loadedMaterialsIds.push(parsedMesh.materialId);
  61563. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61564. if (!mat) {
  61565. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61566. }
  61567. else {
  61568. log += "\n\tMaterial " + mat.toString(fullDetails);
  61569. }
  61570. }
  61571. }
  61572. // Skeleton ?
  61573. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61574. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61575. if (skeletonAlreadyLoaded === false) {
  61576. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61577. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61578. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61579. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61580. skeletons.push(skeleton);
  61581. loadedSkeletonsIds.push(parsedSkeleton.id);
  61582. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61583. }
  61584. }
  61585. }
  61586. }
  61587. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61588. meshes.push(mesh);
  61589. log += "\n\tMesh " + mesh.toString(fullDetails);
  61590. }
  61591. }
  61592. // Connecting parents
  61593. var currentMesh;
  61594. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61595. currentMesh = scene.meshes[index];
  61596. if (currentMesh._waitingParentId) {
  61597. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61598. currentMesh._waitingParentId = null;
  61599. }
  61600. }
  61601. // freeze and compute world matrix application
  61602. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61603. currentMesh = scene.meshes[index];
  61604. if (currentMesh._waitingFreezeWorldMatrix) {
  61605. currentMesh.freezeWorldMatrix();
  61606. currentMesh._waitingFreezeWorldMatrix = null;
  61607. }
  61608. else {
  61609. currentMesh.computeWorldMatrix(true);
  61610. }
  61611. }
  61612. }
  61613. // Particles
  61614. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61615. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61616. var parsedParticleSystem = parsedData.particleSystems[index];
  61617. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61618. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61619. }
  61620. }
  61621. }
  61622. return true;
  61623. }
  61624. catch (err) {
  61625. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61626. if (onError) {
  61627. onError(msg, err);
  61628. }
  61629. else {
  61630. BABYLON.Tools.Log(msg);
  61631. throw err;
  61632. }
  61633. }
  61634. finally {
  61635. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61636. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61637. }
  61638. }
  61639. return false;
  61640. },
  61641. load: function (scene, data, rootUrl, onError) {
  61642. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61643. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61644. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61645. // and avoid problems with multiple concurrent .babylon loads.
  61646. var log = "importScene has failed JSON parse";
  61647. try {
  61648. var parsedData = JSON.parse(data);
  61649. log = "";
  61650. // Scene
  61651. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61652. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61653. }
  61654. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61655. scene.autoClear = parsedData.autoClear;
  61656. }
  61657. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61658. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61659. }
  61660. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61661. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61662. }
  61663. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61664. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61665. }
  61666. // Fog
  61667. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61668. scene.fogMode = parsedData.fogMode;
  61669. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61670. scene.fogStart = parsedData.fogStart;
  61671. scene.fogEnd = parsedData.fogEnd;
  61672. scene.fogDensity = parsedData.fogDensity;
  61673. log += "\tFog mode for scene: ";
  61674. switch (scene.fogMode) {
  61675. // getters not compiling, so using hardcoded
  61676. case 1:
  61677. log += "exp\n";
  61678. break;
  61679. case 2:
  61680. log += "exp2\n";
  61681. break;
  61682. case 3:
  61683. log += "linear\n";
  61684. break;
  61685. }
  61686. }
  61687. //Physics
  61688. if (parsedData.physicsEnabled) {
  61689. var physicsPlugin;
  61690. if (parsedData.physicsEngine === "cannon") {
  61691. physicsPlugin = new BABYLON.CannonJSPlugin();
  61692. }
  61693. else if (parsedData.physicsEngine === "oimo") {
  61694. physicsPlugin = new BABYLON.OimoJSPlugin();
  61695. }
  61696. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61697. //else - default engine, which is currently oimo
  61698. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61699. scene.enablePhysics(physicsGravity, physicsPlugin);
  61700. }
  61701. // Metadata
  61702. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61703. scene.metadata = parsedData.metadata;
  61704. }
  61705. //collisions, if defined. otherwise, default is true
  61706. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61707. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61708. }
  61709. scene.workerCollisions = !!parsedData.workerCollisions;
  61710. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61711. if (!container) {
  61712. return false;
  61713. }
  61714. if (parsedData.autoAnimate) {
  61715. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61716. }
  61717. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61718. scene.setActiveCameraByID(parsedData.activeCameraID);
  61719. }
  61720. // Environment texture
  61721. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61722. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61723. if (parsedData.createDefaultSkybox === true) {
  61724. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61725. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61726. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61727. }
  61728. }
  61729. // Finish
  61730. return true;
  61731. }
  61732. catch (err) {
  61733. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61734. if (onError) {
  61735. onError(msg, err);
  61736. }
  61737. else {
  61738. BABYLON.Tools.Log(msg);
  61739. throw err;
  61740. }
  61741. }
  61742. finally {
  61743. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61744. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61745. }
  61746. }
  61747. return false;
  61748. },
  61749. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61750. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61751. return container;
  61752. }
  61753. });
  61754. })(BABYLON || (BABYLON = {}));
  61755. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61756. var BABYLON;
  61757. (function (BABYLON) {
  61758. var FilesInput = /** @class */ (function () {
  61759. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61760. this.onProcessFileCallback = function () { return true; };
  61761. this._engine = engine;
  61762. this._currentScene = scene;
  61763. this._sceneLoadedCallback = sceneLoadedCallback;
  61764. this._progressCallback = progressCallback;
  61765. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61766. this._textureLoadingCallback = textureLoadingCallback;
  61767. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61768. this._onReloadCallback = onReloadCallback;
  61769. this._errorCallback = errorCallback;
  61770. }
  61771. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61772. var _this = this;
  61773. if (elementToMonitor) {
  61774. this._elementToMonitor = elementToMonitor;
  61775. this._dragEnterHandler = function (e) { _this.drag(e); };
  61776. this._dragOverHandler = function (e) { _this.drag(e); };
  61777. this._dropHandler = function (e) { _this.drop(e); };
  61778. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61779. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61780. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61781. }
  61782. };
  61783. FilesInput.prototype.dispose = function () {
  61784. if (!this._elementToMonitor) {
  61785. return;
  61786. }
  61787. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61788. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61789. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61790. };
  61791. FilesInput.prototype.renderFunction = function () {
  61792. if (this._additionalRenderLoopLogicCallback) {
  61793. this._additionalRenderLoopLogicCallback();
  61794. }
  61795. if (this._currentScene) {
  61796. if (this._textureLoadingCallback) {
  61797. var remaining = this._currentScene.getWaitingItemsCount();
  61798. if (remaining > 0) {
  61799. this._textureLoadingCallback(remaining);
  61800. }
  61801. }
  61802. this._currentScene.render();
  61803. }
  61804. };
  61805. FilesInput.prototype.drag = function (e) {
  61806. e.stopPropagation();
  61807. e.preventDefault();
  61808. };
  61809. FilesInput.prototype.drop = function (eventDrop) {
  61810. eventDrop.stopPropagation();
  61811. eventDrop.preventDefault();
  61812. this.loadFiles(eventDrop);
  61813. };
  61814. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61815. var _this = this;
  61816. var reader = folder.createReader();
  61817. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61818. reader.readEntries(function (entries) {
  61819. remaining.count += entries.length;
  61820. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61821. var entry = entries_1[_i];
  61822. if (entry.isFile) {
  61823. entry.file(function (file) {
  61824. file.correctName = relativePath + file.name;
  61825. files.push(file);
  61826. if (--remaining.count === 0) {
  61827. callback();
  61828. }
  61829. });
  61830. }
  61831. else if (entry.isDirectory) {
  61832. _this._traverseFolder(entry, files, remaining, callback);
  61833. }
  61834. }
  61835. if (--remaining.count) {
  61836. callback();
  61837. }
  61838. });
  61839. };
  61840. FilesInput.prototype._processFiles = function (files) {
  61841. for (var i = 0; i < files.length; i++) {
  61842. var name = files[i].correctName.toLowerCase();
  61843. var extension = name.split('.').pop();
  61844. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61845. continue;
  61846. }
  61847. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61848. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61849. this._sceneFileToLoad = files[i];
  61850. }
  61851. else {
  61852. FilesInput.FilesToLoad[name] = files[i];
  61853. }
  61854. }
  61855. };
  61856. FilesInput.prototype.loadFiles = function (event) {
  61857. var _this = this;
  61858. if (this._startingProcessingFilesCallback)
  61859. this._startingProcessingFilesCallback();
  61860. // Handling data transfer via drag'n'drop
  61861. if (event && event.dataTransfer && event.dataTransfer.files) {
  61862. this._filesToLoad = event.dataTransfer.files;
  61863. }
  61864. // Handling files from input files
  61865. if (event && event.target && event.target.files) {
  61866. this._filesToLoad = event.target.files;
  61867. }
  61868. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61869. var files_1 = new Array();
  61870. var folders = [];
  61871. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61872. for (var i = 0; i < this._filesToLoad.length; i++) {
  61873. var fileToLoad = this._filesToLoad[i];
  61874. var name_1 = fileToLoad.name.toLowerCase();
  61875. var entry = void 0;
  61876. fileToLoad.correctName = name_1;
  61877. if (items) {
  61878. var item = items[i];
  61879. if (item.getAsEntry) {
  61880. entry = item.getAsEntry();
  61881. }
  61882. else if (item.webkitGetAsEntry) {
  61883. entry = item.webkitGetAsEntry();
  61884. }
  61885. }
  61886. if (!entry) {
  61887. files_1.push(fileToLoad);
  61888. }
  61889. else {
  61890. if (entry.isDirectory) {
  61891. folders.push(entry);
  61892. }
  61893. else {
  61894. files_1.push(fileToLoad);
  61895. }
  61896. }
  61897. }
  61898. if (folders.length === 0) {
  61899. this._processFiles(files_1);
  61900. this._processReload();
  61901. }
  61902. else {
  61903. var remaining = { count: folders.length };
  61904. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61905. var folder = folders_1[_i];
  61906. this._traverseFolder(folder, files_1, remaining, function () {
  61907. _this._processFiles(files_1);
  61908. if (remaining.count === 0) {
  61909. _this._processReload();
  61910. }
  61911. });
  61912. }
  61913. }
  61914. }
  61915. };
  61916. FilesInput.prototype._processReload = function () {
  61917. if (this._onReloadCallback) {
  61918. this._onReloadCallback(this._sceneFileToLoad);
  61919. }
  61920. else {
  61921. this.reload();
  61922. }
  61923. };
  61924. FilesInput.prototype.reload = function () {
  61925. var _this = this;
  61926. // If a scene file has been provided
  61927. if (this._sceneFileToLoad) {
  61928. if (this._currentScene) {
  61929. if (BABYLON.Tools.errorsCount > 0) {
  61930. BABYLON.Tools.ClearLogCache();
  61931. }
  61932. this._engine.stopRenderLoop();
  61933. this._currentScene.dispose();
  61934. }
  61935. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61936. if (_this._progressCallback) {
  61937. _this._progressCallback(progress);
  61938. }
  61939. }).then(function (scene) {
  61940. _this._currentScene = scene;
  61941. if (_this._sceneLoadedCallback) {
  61942. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61943. }
  61944. // Wait for textures and shaders to be ready
  61945. _this._currentScene.executeWhenReady(function () {
  61946. _this._engine.runRenderLoop(function () {
  61947. _this.renderFunction();
  61948. });
  61949. });
  61950. }).catch(function (error) {
  61951. if (_this._errorCallback) {
  61952. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61953. }
  61954. });
  61955. }
  61956. else {
  61957. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61958. }
  61959. };
  61960. FilesInput.FilesToLoad = {};
  61961. return FilesInput;
  61962. }());
  61963. BABYLON.FilesInput = FilesInput;
  61964. })(BABYLON || (BABYLON = {}));
  61965. //# sourceMappingURL=babylon.filesInput.js.map
  61966. var BABYLON;
  61967. (function (BABYLON) {
  61968. /**
  61969. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61970. * The underlying implementation relies on an associative array to ensure the best performances.
  61971. * The value can be anything including 'null' but except 'undefined'
  61972. */
  61973. var StringDictionary = /** @class */ (function () {
  61974. function StringDictionary() {
  61975. this._count = 0;
  61976. this._data = {};
  61977. }
  61978. /**
  61979. * This will clear this dictionary and copy the content from the 'source' one.
  61980. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61981. * @param source the dictionary to take the content from and copy to this dictionary
  61982. */
  61983. StringDictionary.prototype.copyFrom = function (source) {
  61984. var _this = this;
  61985. this.clear();
  61986. source.forEach(function (t, v) { return _this.add(t, v); });
  61987. };
  61988. /**
  61989. * Get a value based from its key
  61990. * @param key the given key to get the matching value from
  61991. * @return the value if found, otherwise undefined is returned
  61992. */
  61993. StringDictionary.prototype.get = function (key) {
  61994. var val = this._data[key];
  61995. if (val !== undefined) {
  61996. return val;
  61997. }
  61998. return undefined;
  61999. };
  62000. /**
  62001. * Get a value from its key or add it if it doesn't exist.
  62002. * This method will ensure you that a given key/data will be present in the dictionary.
  62003. * @param key the given key to get the matching value from
  62004. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62005. * The factory will only be invoked if there's no data for the given key.
  62006. * @return the value corresponding to the key.
  62007. */
  62008. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62009. var val = this.get(key);
  62010. if (val !== undefined) {
  62011. return val;
  62012. }
  62013. val = factory(key);
  62014. if (val) {
  62015. this.add(key, val);
  62016. }
  62017. return val;
  62018. };
  62019. /**
  62020. * Get a value from its key if present in the dictionary otherwise add it
  62021. * @param key the key to get the value from
  62022. * @param val if there's no such key/value pair in the dictionary add it with this value
  62023. * @return the value corresponding to the key
  62024. */
  62025. StringDictionary.prototype.getOrAdd = function (key, val) {
  62026. var curVal = this.get(key);
  62027. if (curVal !== undefined) {
  62028. return curVal;
  62029. }
  62030. this.add(key, val);
  62031. return val;
  62032. };
  62033. /**
  62034. * Check if there's a given key in the dictionary
  62035. * @param key the key to check for
  62036. * @return true if the key is present, false otherwise
  62037. */
  62038. StringDictionary.prototype.contains = function (key) {
  62039. return this._data[key] !== undefined;
  62040. };
  62041. /**
  62042. * Add a new key and its corresponding value
  62043. * @param key the key to add
  62044. * @param value the value corresponding to the key
  62045. * @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
  62046. */
  62047. StringDictionary.prototype.add = function (key, value) {
  62048. if (this._data[key] !== undefined) {
  62049. return false;
  62050. }
  62051. this._data[key] = value;
  62052. ++this._count;
  62053. return true;
  62054. };
  62055. StringDictionary.prototype.set = function (key, value) {
  62056. if (this._data[key] === undefined) {
  62057. return false;
  62058. }
  62059. this._data[key] = value;
  62060. return true;
  62061. };
  62062. /**
  62063. * Get the element of the given key and remove it from the dictionary
  62064. * @param key
  62065. */
  62066. StringDictionary.prototype.getAndRemove = function (key) {
  62067. var val = this.get(key);
  62068. if (val !== undefined) {
  62069. delete this._data[key];
  62070. --this._count;
  62071. return val;
  62072. }
  62073. return null;
  62074. };
  62075. /**
  62076. * Remove a key/value from the dictionary.
  62077. * @param key the key to remove
  62078. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62079. */
  62080. StringDictionary.prototype.remove = function (key) {
  62081. if (this.contains(key)) {
  62082. delete this._data[key];
  62083. --this._count;
  62084. return true;
  62085. }
  62086. return false;
  62087. };
  62088. /**
  62089. * Clear the whole content of the dictionary
  62090. */
  62091. StringDictionary.prototype.clear = function () {
  62092. this._data = {};
  62093. this._count = 0;
  62094. };
  62095. Object.defineProperty(StringDictionary.prototype, "count", {
  62096. get: function () {
  62097. return this._count;
  62098. },
  62099. enumerable: true,
  62100. configurable: true
  62101. });
  62102. /**
  62103. * Execute a callback on each key/val of the dictionary.
  62104. * Note that you can remove any element in this dictionary in the callback implementation
  62105. * @param callback the callback to execute on a given key/value pair
  62106. */
  62107. StringDictionary.prototype.forEach = function (callback) {
  62108. for (var cur in this._data) {
  62109. var val = this._data[cur];
  62110. callback(cur, val);
  62111. }
  62112. };
  62113. /**
  62114. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62115. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62116. * Note that you can remove any element in this dictionary in the callback implementation
  62117. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62118. */
  62119. StringDictionary.prototype.first = function (callback) {
  62120. for (var cur in this._data) {
  62121. var val = this._data[cur];
  62122. var res = callback(cur, val);
  62123. if (res) {
  62124. return res;
  62125. }
  62126. }
  62127. return null;
  62128. };
  62129. return StringDictionary;
  62130. }());
  62131. BABYLON.StringDictionary = StringDictionary;
  62132. })(BABYLON || (BABYLON = {}));
  62133. //# sourceMappingURL=babylon.stringDictionary.js.map
  62134. var BABYLON;
  62135. (function (BABYLON) {
  62136. var Tags = /** @class */ (function () {
  62137. function Tags() {
  62138. }
  62139. Tags.EnableFor = function (obj) {
  62140. obj._tags = obj._tags || {};
  62141. obj.hasTags = function () {
  62142. return Tags.HasTags(obj);
  62143. };
  62144. obj.addTags = function (tagsString) {
  62145. return Tags.AddTagsTo(obj, tagsString);
  62146. };
  62147. obj.removeTags = function (tagsString) {
  62148. return Tags.RemoveTagsFrom(obj, tagsString);
  62149. };
  62150. obj.matchesTagsQuery = function (tagsQuery) {
  62151. return Tags.MatchesQuery(obj, tagsQuery);
  62152. };
  62153. };
  62154. Tags.DisableFor = function (obj) {
  62155. delete obj._tags;
  62156. delete obj.hasTags;
  62157. delete obj.addTags;
  62158. delete obj.removeTags;
  62159. delete obj.matchesTagsQuery;
  62160. };
  62161. Tags.HasTags = function (obj) {
  62162. if (!obj._tags) {
  62163. return false;
  62164. }
  62165. return !BABYLON.Tools.IsEmpty(obj._tags);
  62166. };
  62167. Tags.GetTags = function (obj, asString) {
  62168. if (asString === void 0) { asString = true; }
  62169. if (!obj._tags) {
  62170. return null;
  62171. }
  62172. if (asString) {
  62173. var tagsArray = [];
  62174. for (var tag in obj._tags) {
  62175. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62176. tagsArray.push(tag);
  62177. }
  62178. }
  62179. return tagsArray.join(" ");
  62180. }
  62181. else {
  62182. return obj._tags;
  62183. }
  62184. };
  62185. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62186. // a tag cannot start with '||', '&&', and '!'
  62187. // it cannot contain whitespaces
  62188. Tags.AddTagsTo = function (obj, tagsString) {
  62189. if (!tagsString) {
  62190. return;
  62191. }
  62192. if (typeof tagsString !== "string") {
  62193. return;
  62194. }
  62195. var tags = tagsString.split(" ");
  62196. tags.forEach(function (tag, index, array) {
  62197. Tags._AddTagTo(obj, tag);
  62198. });
  62199. };
  62200. Tags._AddTagTo = function (obj, tag) {
  62201. tag = tag.trim();
  62202. if (tag === "" || tag === "true" || tag === "false") {
  62203. return;
  62204. }
  62205. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62206. return;
  62207. }
  62208. Tags.EnableFor(obj);
  62209. obj._tags[tag] = true;
  62210. };
  62211. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62212. if (!Tags.HasTags(obj)) {
  62213. return;
  62214. }
  62215. var tags = tagsString.split(" ");
  62216. for (var t in tags) {
  62217. Tags._RemoveTagFrom(obj, tags[t]);
  62218. }
  62219. };
  62220. Tags._RemoveTagFrom = function (obj, tag) {
  62221. delete obj._tags[tag];
  62222. };
  62223. Tags.MatchesQuery = function (obj, tagsQuery) {
  62224. if (tagsQuery === undefined) {
  62225. return true;
  62226. }
  62227. if (tagsQuery === "") {
  62228. return Tags.HasTags(obj);
  62229. }
  62230. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62231. };
  62232. return Tags;
  62233. }());
  62234. BABYLON.Tags = Tags;
  62235. })(BABYLON || (BABYLON = {}));
  62236. //# sourceMappingURL=babylon.tags.js.map
  62237. var BABYLON;
  62238. (function (BABYLON) {
  62239. var AndOrNotEvaluator = /** @class */ (function () {
  62240. function AndOrNotEvaluator() {
  62241. }
  62242. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62243. if (!query.match(/\([^\(\)]*\)/g)) {
  62244. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62245. }
  62246. else {
  62247. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62248. // remove parenthesis
  62249. r = r.slice(1, r.length - 1);
  62250. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62251. });
  62252. }
  62253. if (query === "true") {
  62254. return true;
  62255. }
  62256. if (query === "false") {
  62257. return false;
  62258. }
  62259. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62260. };
  62261. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62262. evaluateCallback = evaluateCallback || (function (r) {
  62263. return r === "true" ? true : false;
  62264. });
  62265. var result;
  62266. var or = parenthesisContent.split("||");
  62267. for (var i in or) {
  62268. if (or.hasOwnProperty(i)) {
  62269. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62270. var and = ori.split("&&");
  62271. if (and.length > 1) {
  62272. for (var j = 0; j < and.length; ++j) {
  62273. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62274. if (andj !== "true" && andj !== "false") {
  62275. if (andj[0] === "!") {
  62276. result = !evaluateCallback(andj.substring(1));
  62277. }
  62278. else {
  62279. result = evaluateCallback(andj);
  62280. }
  62281. }
  62282. else {
  62283. result = andj === "true" ? true : false;
  62284. }
  62285. if (!result) {
  62286. ori = "false";
  62287. break;
  62288. }
  62289. }
  62290. }
  62291. if (result || ori === "true") {
  62292. result = true;
  62293. break;
  62294. }
  62295. // result equals false (or undefined)
  62296. if (ori !== "true" && ori !== "false") {
  62297. if (ori[0] === "!") {
  62298. result = !evaluateCallback(ori.substring(1));
  62299. }
  62300. else {
  62301. result = evaluateCallback(ori);
  62302. }
  62303. }
  62304. else {
  62305. result = ori === "true" ? true : false;
  62306. }
  62307. }
  62308. }
  62309. // the whole parenthesis scope is replaced by 'true' or 'false'
  62310. return result ? "true" : "false";
  62311. };
  62312. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62313. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62314. // remove whitespaces
  62315. r = r.replace(/[\s]/g, function () { return ""; });
  62316. return r.length % 2 ? "!" : "";
  62317. });
  62318. booleanString = booleanString.trim();
  62319. if (booleanString === "!true") {
  62320. booleanString = "false";
  62321. }
  62322. else if (booleanString === "!false") {
  62323. booleanString = "true";
  62324. }
  62325. return booleanString;
  62326. };
  62327. return AndOrNotEvaluator;
  62328. }());
  62329. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62330. })(BABYLON || (BABYLON = {}));
  62331. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62332. var BABYLON;
  62333. (function (BABYLON) {
  62334. var Database = /** @class */ (function () {
  62335. function Database(urlToScene, callbackManifestChecked) {
  62336. // Handling various flavors of prefixed version of IndexedDB
  62337. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62338. this.callbackManifestChecked = callbackManifestChecked;
  62339. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62340. this.db = null;
  62341. this._enableSceneOffline = false;
  62342. this._enableTexturesOffline = false;
  62343. this.manifestVersionFound = 0;
  62344. this.mustUpdateRessources = false;
  62345. this.hasReachedQuota = false;
  62346. if (!Database.IDBStorageEnabled) {
  62347. this.callbackManifestChecked(true);
  62348. }
  62349. else {
  62350. this.checkManifestFile();
  62351. }
  62352. }
  62353. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62354. get: function () {
  62355. return this._enableSceneOffline;
  62356. },
  62357. enumerable: true,
  62358. configurable: true
  62359. });
  62360. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62361. get: function () {
  62362. return this._enableTexturesOffline;
  62363. },
  62364. enumerable: true,
  62365. configurable: true
  62366. });
  62367. Database.prototype.checkManifestFile = function () {
  62368. var _this = this;
  62369. var noManifestFile = function () {
  62370. _this._enableSceneOffline = false;
  62371. _this._enableTexturesOffline = false;
  62372. _this.callbackManifestChecked(false);
  62373. };
  62374. var timeStampUsed = false;
  62375. var manifestURL = this.currentSceneUrl + ".manifest";
  62376. var xhr = new XMLHttpRequest();
  62377. if (navigator.onLine) {
  62378. // Adding a timestamp to by-pass browsers' cache
  62379. timeStampUsed = true;
  62380. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62381. }
  62382. xhr.open("GET", manifestURL, true);
  62383. xhr.addEventListener("load", function () {
  62384. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62385. try {
  62386. var manifestFile = JSON.parse(xhr.response);
  62387. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62388. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62389. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62390. _this.manifestVersionFound = manifestFile.version;
  62391. }
  62392. if (_this.callbackManifestChecked) {
  62393. _this.callbackManifestChecked(true);
  62394. }
  62395. }
  62396. catch (ex) {
  62397. noManifestFile();
  62398. }
  62399. }
  62400. else {
  62401. noManifestFile();
  62402. }
  62403. }, false);
  62404. xhr.addEventListener("error", function (event) {
  62405. if (timeStampUsed) {
  62406. timeStampUsed = false;
  62407. // Let's retry without the timeStamp
  62408. // It could fail when coupled with HTML5 Offline API
  62409. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62410. xhr.open("GET", retryManifestURL, true);
  62411. xhr.send();
  62412. }
  62413. else {
  62414. noManifestFile();
  62415. }
  62416. }, false);
  62417. try {
  62418. xhr.send();
  62419. }
  62420. catch (ex) {
  62421. BABYLON.Tools.Error("Error on XHR send request.");
  62422. this.callbackManifestChecked(false);
  62423. }
  62424. };
  62425. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62426. var _this = this;
  62427. var handleError = function () {
  62428. _this.isSupported = false;
  62429. if (errorCallback)
  62430. errorCallback();
  62431. };
  62432. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62433. // Your browser doesn't support IndexedDB
  62434. this.isSupported = false;
  62435. if (errorCallback)
  62436. errorCallback();
  62437. }
  62438. else {
  62439. // If the DB hasn't been opened or created yet
  62440. if (!this.db) {
  62441. this.hasReachedQuota = false;
  62442. this.isSupported = true;
  62443. var request = this.idbFactory.open("babylonjs", 1);
  62444. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62445. request.onerror = function (event) {
  62446. handleError();
  62447. };
  62448. // executes when a version change transaction cannot complete due to other active transactions
  62449. request.onblocked = function (event) {
  62450. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62451. handleError();
  62452. };
  62453. // DB has been opened successfully
  62454. request.onsuccess = function (event) {
  62455. _this.db = request.result;
  62456. successCallback();
  62457. };
  62458. // Initialization of the DB. Creating Scenes & Textures stores
  62459. request.onupgradeneeded = function (event) {
  62460. _this.db = (event.target).result;
  62461. if (_this.db) {
  62462. try {
  62463. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62464. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62465. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62466. }
  62467. catch (ex) {
  62468. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62469. handleError();
  62470. }
  62471. }
  62472. };
  62473. }
  62474. else {
  62475. if (successCallback)
  62476. successCallback();
  62477. }
  62478. }
  62479. };
  62480. Database.prototype.loadImageFromDB = function (url, image) {
  62481. var _this = this;
  62482. var completeURL = Database.ReturnFullUrlLocation(url);
  62483. var saveAndLoadImage = function () {
  62484. if (!_this.hasReachedQuota && _this.db !== null) {
  62485. // the texture is not yet in the DB, let's try to save it
  62486. _this._saveImageIntoDBAsync(completeURL, image);
  62487. }
  62488. else {
  62489. image.src = url;
  62490. }
  62491. };
  62492. if (!this.mustUpdateRessources) {
  62493. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62494. }
  62495. else {
  62496. saveAndLoadImage();
  62497. }
  62498. };
  62499. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62500. if (this.isSupported && this.db !== null) {
  62501. var texture;
  62502. var transaction = this.db.transaction(["textures"]);
  62503. transaction.onabort = function (event) {
  62504. image.src = url;
  62505. };
  62506. transaction.oncomplete = function (event) {
  62507. var blobTextureURL;
  62508. if (texture) {
  62509. var URL = window.URL || window.webkitURL;
  62510. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62511. image.onerror = function () {
  62512. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62513. image.src = url;
  62514. };
  62515. image.src = blobTextureURL;
  62516. }
  62517. else {
  62518. notInDBCallback();
  62519. }
  62520. };
  62521. var getRequest = transaction.objectStore("textures").get(url);
  62522. getRequest.onsuccess = function (event) {
  62523. texture = (event.target).result;
  62524. };
  62525. getRequest.onerror = function (event) {
  62526. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62527. image.src = url;
  62528. };
  62529. }
  62530. else {
  62531. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62532. image.src = url;
  62533. }
  62534. };
  62535. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62536. var _this = this;
  62537. if (this.isSupported) {
  62538. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62539. var generateBlobUrl = function () {
  62540. var blobTextureURL;
  62541. if (blob) {
  62542. var URL = window.URL || window.webkitURL;
  62543. try {
  62544. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62545. }
  62546. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62547. catch (ex) {
  62548. blobTextureURL = URL.createObjectURL(blob);
  62549. }
  62550. }
  62551. if (blobTextureURL) {
  62552. image.src = blobTextureURL;
  62553. }
  62554. };
  62555. if (Database.IsUASupportingBlobStorage) {
  62556. var xhr = new XMLHttpRequest(), blob;
  62557. xhr.open("GET", url, true);
  62558. xhr.responseType = "blob";
  62559. xhr.addEventListener("load", function () {
  62560. if (xhr.status === 200 && _this.db) {
  62561. // Blob as response (XHR2)
  62562. blob = xhr.response;
  62563. var transaction = _this.db.transaction(["textures"], "readwrite");
  62564. // the transaction could abort because of a QuotaExceededError error
  62565. transaction.onabort = function (event) {
  62566. try {
  62567. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62568. var srcElement = (event.srcElement || event.target);
  62569. var error = srcElement.error;
  62570. if (error && error.name === "QuotaExceededError") {
  62571. _this.hasReachedQuota = true;
  62572. }
  62573. }
  62574. catch (ex) { }
  62575. generateBlobUrl();
  62576. };
  62577. transaction.oncomplete = function (event) {
  62578. generateBlobUrl();
  62579. };
  62580. var newTexture = { textureUrl: url, data: blob };
  62581. try {
  62582. // Put the blob into the dabase
  62583. var addRequest = transaction.objectStore("textures").put(newTexture);
  62584. addRequest.onsuccess = function (event) {
  62585. };
  62586. addRequest.onerror = function (event) {
  62587. generateBlobUrl();
  62588. };
  62589. }
  62590. catch (ex) {
  62591. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62592. if (ex.code === 25) {
  62593. Database.IsUASupportingBlobStorage = false;
  62594. }
  62595. image.src = url;
  62596. }
  62597. }
  62598. else {
  62599. image.src = url;
  62600. }
  62601. }, false);
  62602. xhr.addEventListener("error", function (event) {
  62603. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62604. image.src = url;
  62605. }, false);
  62606. xhr.send();
  62607. }
  62608. else {
  62609. image.src = url;
  62610. }
  62611. }
  62612. else {
  62613. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62614. image.src = url;
  62615. }
  62616. };
  62617. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62618. var _this = this;
  62619. var updateVersion = function () {
  62620. // the version is not yet in the DB or we need to update it
  62621. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62622. };
  62623. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62624. };
  62625. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62626. var _this = this;
  62627. if (this.isSupported && this.db) {
  62628. var version;
  62629. try {
  62630. var transaction = this.db.transaction(["versions"]);
  62631. transaction.oncomplete = function (event) {
  62632. if (version) {
  62633. // If the version in the JSON file is > than the version in DB
  62634. if (_this.manifestVersionFound > version.data) {
  62635. _this.mustUpdateRessources = true;
  62636. updateInDBCallback();
  62637. }
  62638. else {
  62639. callback(version.data);
  62640. }
  62641. }
  62642. else {
  62643. _this.mustUpdateRessources = true;
  62644. updateInDBCallback();
  62645. }
  62646. };
  62647. transaction.onabort = function (event) {
  62648. callback(-1);
  62649. };
  62650. var getRequest = transaction.objectStore("versions").get(url);
  62651. getRequest.onsuccess = function (event) {
  62652. version = (event.target).result;
  62653. };
  62654. getRequest.onerror = function (event) {
  62655. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62656. callback(-1);
  62657. };
  62658. }
  62659. catch (ex) {
  62660. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62661. callback(-1);
  62662. }
  62663. }
  62664. else {
  62665. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62666. callback(-1);
  62667. }
  62668. };
  62669. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62670. var _this = this;
  62671. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62672. try {
  62673. // Open a transaction to the database
  62674. var transaction = this.db.transaction(["versions"], "readwrite");
  62675. // the transaction could abort because of a QuotaExceededError error
  62676. transaction.onabort = function (event) {
  62677. try {
  62678. var error = event.srcElement['error'];
  62679. if (error && error.name === "QuotaExceededError") {
  62680. _this.hasReachedQuota = true;
  62681. }
  62682. }
  62683. catch (ex) { }
  62684. callback(-1);
  62685. };
  62686. transaction.oncomplete = function (event) {
  62687. callback(_this.manifestVersionFound);
  62688. };
  62689. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62690. // Put the scene into the database
  62691. var addRequest = transaction.objectStore("versions").put(newVersion);
  62692. addRequest.onsuccess = function (event) {
  62693. };
  62694. addRequest.onerror = function (event) {
  62695. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62696. };
  62697. }
  62698. catch (ex) {
  62699. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62700. callback(-1);
  62701. }
  62702. }
  62703. else {
  62704. callback(-1);
  62705. }
  62706. };
  62707. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62708. var _this = this;
  62709. var completeUrl = Database.ReturnFullUrlLocation(url);
  62710. var saveAndLoadFile = function () {
  62711. // the scene is not yet in the DB, let's try to save it
  62712. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62713. };
  62714. this._checkVersionFromDB(completeUrl, function (version) {
  62715. if (version !== -1) {
  62716. if (!_this.mustUpdateRessources) {
  62717. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62718. }
  62719. else {
  62720. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62721. }
  62722. }
  62723. else {
  62724. if (errorCallback) {
  62725. errorCallback();
  62726. }
  62727. }
  62728. });
  62729. };
  62730. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62731. if (this.isSupported && this.db) {
  62732. var targetStore;
  62733. if (url.indexOf(".babylon") !== -1) {
  62734. targetStore = "scenes";
  62735. }
  62736. else {
  62737. targetStore = "textures";
  62738. }
  62739. var file;
  62740. var transaction = this.db.transaction([targetStore]);
  62741. transaction.oncomplete = function (event) {
  62742. if (file) {
  62743. callback(file.data);
  62744. }
  62745. else {
  62746. notInDBCallback();
  62747. }
  62748. };
  62749. transaction.onabort = function (event) {
  62750. notInDBCallback();
  62751. };
  62752. var getRequest = transaction.objectStore(targetStore).get(url);
  62753. getRequest.onsuccess = function (event) {
  62754. file = (event.target).result;
  62755. };
  62756. getRequest.onerror = function (event) {
  62757. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62758. notInDBCallback();
  62759. };
  62760. }
  62761. else {
  62762. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62763. callback();
  62764. }
  62765. };
  62766. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62767. var _this = this;
  62768. if (this.isSupported) {
  62769. var targetStore;
  62770. if (url.indexOf(".babylon") !== -1) {
  62771. targetStore = "scenes";
  62772. }
  62773. else {
  62774. targetStore = "textures";
  62775. }
  62776. // Create XHR
  62777. var xhr = new XMLHttpRequest();
  62778. var fileData;
  62779. xhr.open("GET", url, true);
  62780. if (useArrayBuffer) {
  62781. xhr.responseType = "arraybuffer";
  62782. }
  62783. if (progressCallback) {
  62784. xhr.onprogress = progressCallback;
  62785. }
  62786. xhr.addEventListener("load", function () {
  62787. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62788. // Blob as response (XHR2)
  62789. //fileData = xhr.responseText;
  62790. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62791. if (!_this.hasReachedQuota && _this.db) {
  62792. // Open a transaction to the database
  62793. var transaction = _this.db.transaction([targetStore], "readwrite");
  62794. // the transaction could abort because of a QuotaExceededError error
  62795. transaction.onabort = function (event) {
  62796. try {
  62797. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62798. var error = event.srcElement['error'];
  62799. if (error && error.name === "QuotaExceededError") {
  62800. _this.hasReachedQuota = true;
  62801. }
  62802. }
  62803. catch (ex) { }
  62804. callback(fileData);
  62805. };
  62806. transaction.oncomplete = function (event) {
  62807. callback(fileData);
  62808. };
  62809. var newFile;
  62810. if (targetStore === "scenes") {
  62811. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62812. }
  62813. else {
  62814. newFile = { textureUrl: url, data: fileData };
  62815. }
  62816. try {
  62817. // Put the scene into the database
  62818. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62819. addRequest.onsuccess = function (event) {
  62820. };
  62821. addRequest.onerror = function (event) {
  62822. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62823. };
  62824. }
  62825. catch (ex) {
  62826. callback(fileData);
  62827. }
  62828. }
  62829. else {
  62830. callback(fileData);
  62831. }
  62832. }
  62833. else {
  62834. callback();
  62835. }
  62836. }, false);
  62837. xhr.addEventListener("error", function (event) {
  62838. BABYLON.Tools.Error("error on XHR request.");
  62839. callback();
  62840. }, false);
  62841. xhr.send();
  62842. }
  62843. else {
  62844. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62845. callback();
  62846. }
  62847. };
  62848. Database.IsUASupportingBlobStorage = true;
  62849. Database.IDBStorageEnabled = true;
  62850. Database.parseURL = function (url) {
  62851. var a = document.createElement('a');
  62852. a.href = url;
  62853. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62854. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62855. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62856. return absLocation;
  62857. };
  62858. Database.ReturnFullUrlLocation = function (url) {
  62859. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62860. return (Database.parseURL(window.location.href) + url);
  62861. }
  62862. else {
  62863. return url;
  62864. }
  62865. };
  62866. return Database;
  62867. }());
  62868. BABYLON.Database = Database;
  62869. })(BABYLON || (BABYLON = {}));
  62870. //# sourceMappingURL=babylon.database.js.map
  62871. var BABYLON;
  62872. (function (BABYLON) {
  62873. var FresnelParameters = /** @class */ (function () {
  62874. function FresnelParameters() {
  62875. this._isEnabled = true;
  62876. this.leftColor = BABYLON.Color3.White();
  62877. this.rightColor = BABYLON.Color3.Black();
  62878. this.bias = 0;
  62879. this.power = 1;
  62880. }
  62881. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62882. get: function () {
  62883. return this._isEnabled;
  62884. },
  62885. set: function (value) {
  62886. if (this._isEnabled === value) {
  62887. return;
  62888. }
  62889. this._isEnabled = value;
  62890. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62891. },
  62892. enumerable: true,
  62893. configurable: true
  62894. });
  62895. FresnelParameters.prototype.clone = function () {
  62896. var newFresnelParameters = new FresnelParameters();
  62897. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62898. return newFresnelParameters;
  62899. };
  62900. FresnelParameters.prototype.serialize = function () {
  62901. var serializationObject = {};
  62902. serializationObject.isEnabled = this.isEnabled;
  62903. serializationObject.leftColor = this.leftColor;
  62904. serializationObject.rightColor = this.rightColor;
  62905. serializationObject.bias = this.bias;
  62906. serializationObject.power = this.power;
  62907. return serializationObject;
  62908. };
  62909. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62910. var fresnelParameters = new FresnelParameters();
  62911. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62912. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62913. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62914. fresnelParameters.bias = parsedFresnelParameters.bias;
  62915. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62916. return fresnelParameters;
  62917. };
  62918. return FresnelParameters;
  62919. }());
  62920. BABYLON.FresnelParameters = FresnelParameters;
  62921. })(BABYLON || (BABYLON = {}));
  62922. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62923. var BABYLON;
  62924. (function (BABYLON) {
  62925. var MultiMaterial = /** @class */ (function (_super) {
  62926. __extends(MultiMaterial, _super);
  62927. function MultiMaterial(name, scene) {
  62928. var _this = _super.call(this, name, scene, true) || this;
  62929. scene.multiMaterials.push(_this);
  62930. _this.subMaterials = new Array();
  62931. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62932. return _this;
  62933. }
  62934. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62935. get: function () {
  62936. return this._subMaterials;
  62937. },
  62938. set: function (value) {
  62939. this._subMaterials = value;
  62940. this._hookArray(value);
  62941. },
  62942. enumerable: true,
  62943. configurable: true
  62944. });
  62945. MultiMaterial.prototype._hookArray = function (array) {
  62946. var _this = this;
  62947. var oldPush = array.push;
  62948. array.push = function () {
  62949. var items = [];
  62950. for (var _i = 0; _i < arguments.length; _i++) {
  62951. items[_i] = arguments[_i];
  62952. }
  62953. var result = oldPush.apply(array, items);
  62954. _this._markAllSubMeshesAsTexturesDirty();
  62955. return result;
  62956. };
  62957. var oldSplice = array.splice;
  62958. array.splice = function (index, deleteCount) {
  62959. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62960. _this._markAllSubMeshesAsTexturesDirty();
  62961. return deleted;
  62962. };
  62963. };
  62964. // Properties
  62965. MultiMaterial.prototype.getSubMaterial = function (index) {
  62966. if (index < 0 || index >= this.subMaterials.length) {
  62967. return this.getScene().defaultMaterial;
  62968. }
  62969. return this.subMaterials[index];
  62970. };
  62971. MultiMaterial.prototype.getActiveTextures = function () {
  62972. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62973. if (subMaterial) {
  62974. return subMaterial.getActiveTextures();
  62975. }
  62976. else {
  62977. return [];
  62978. }
  62979. }));
  62980. var _a;
  62981. };
  62982. // Methods
  62983. MultiMaterial.prototype.getClassName = function () {
  62984. return "MultiMaterial";
  62985. };
  62986. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62987. for (var index = 0; index < this.subMaterials.length; index++) {
  62988. var subMaterial = this.subMaterials[index];
  62989. if (subMaterial) {
  62990. if (subMaterial.storeEffectOnSubMeshes) {
  62991. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62992. return false;
  62993. }
  62994. continue;
  62995. }
  62996. if (!subMaterial.isReady(mesh)) {
  62997. return false;
  62998. }
  62999. }
  63000. }
  63001. return true;
  63002. };
  63003. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63004. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63005. for (var index = 0; index < this.subMaterials.length; index++) {
  63006. var subMaterial = null;
  63007. var current = this.subMaterials[index];
  63008. if (cloneChildren && current) {
  63009. subMaterial = current.clone(name + "-" + current.name);
  63010. }
  63011. else {
  63012. subMaterial = this.subMaterials[index];
  63013. }
  63014. newMultiMaterial.subMaterials.push(subMaterial);
  63015. }
  63016. return newMultiMaterial;
  63017. };
  63018. MultiMaterial.prototype.serialize = function () {
  63019. var serializationObject = {};
  63020. serializationObject.name = this.name;
  63021. serializationObject.id = this.id;
  63022. if (BABYLON.Tags) {
  63023. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63024. }
  63025. serializationObject.materials = [];
  63026. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63027. var subMat = this.subMaterials[matIndex];
  63028. if (subMat) {
  63029. serializationObject.materials.push(subMat.id);
  63030. }
  63031. else {
  63032. serializationObject.materials.push(null);
  63033. }
  63034. }
  63035. return serializationObject;
  63036. };
  63037. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63038. var scene = this.getScene();
  63039. if (!scene) {
  63040. return;
  63041. }
  63042. var index = scene.multiMaterials.indexOf(this);
  63043. if (index >= 0) {
  63044. scene.multiMaterials.splice(index, 1);
  63045. }
  63046. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63047. };
  63048. return MultiMaterial;
  63049. }(BABYLON.Material));
  63050. BABYLON.MultiMaterial = MultiMaterial;
  63051. })(BABYLON || (BABYLON = {}));
  63052. //# sourceMappingURL=babylon.multiMaterial.js.map
  63053. var BABYLON;
  63054. (function (BABYLON) {
  63055. var FreeCameraTouchInput = /** @class */ (function () {
  63056. function FreeCameraTouchInput() {
  63057. this._offsetX = null;
  63058. this._offsetY = null;
  63059. this._pointerPressed = new Array();
  63060. this.touchAngularSensibility = 200000.0;
  63061. this.touchMoveSensibility = 250.0;
  63062. }
  63063. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63064. var _this = this;
  63065. var previousPosition = null;
  63066. if (this._pointerInput === undefined) {
  63067. this._onLostFocus = function (evt) {
  63068. _this._offsetX = null;
  63069. _this._offsetY = null;
  63070. };
  63071. this._pointerInput = function (p, s) {
  63072. var evt = p.event;
  63073. if (evt.pointerType === "mouse") {
  63074. return;
  63075. }
  63076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63077. if (!noPreventDefault) {
  63078. evt.preventDefault();
  63079. }
  63080. _this._pointerPressed.push(evt.pointerId);
  63081. if (_this._pointerPressed.length !== 1) {
  63082. return;
  63083. }
  63084. previousPosition = {
  63085. x: evt.clientX,
  63086. y: evt.clientY
  63087. };
  63088. }
  63089. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63090. if (!noPreventDefault) {
  63091. evt.preventDefault();
  63092. }
  63093. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63094. if (index === -1) {
  63095. return;
  63096. }
  63097. _this._pointerPressed.splice(index, 1);
  63098. if (index != 0) {
  63099. return;
  63100. }
  63101. previousPosition = null;
  63102. _this._offsetX = null;
  63103. _this._offsetY = null;
  63104. }
  63105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63106. if (!noPreventDefault) {
  63107. evt.preventDefault();
  63108. }
  63109. if (!previousPosition) {
  63110. return;
  63111. }
  63112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63113. if (index != 0) {
  63114. return;
  63115. }
  63116. _this._offsetX = evt.clientX - previousPosition.x;
  63117. _this._offsetY = -(evt.clientY - previousPosition.y);
  63118. }
  63119. };
  63120. }
  63121. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63122. if (this._onLostFocus) {
  63123. element.addEventListener("blur", this._onLostFocus);
  63124. }
  63125. };
  63126. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63127. if (this._pointerInput && element) {
  63128. if (this._observer) {
  63129. this.camera.getScene().onPointerObservable.remove(this._observer);
  63130. this._observer = null;
  63131. }
  63132. if (this._onLostFocus) {
  63133. element.removeEventListener("blur", this._onLostFocus);
  63134. this._onLostFocus = null;
  63135. }
  63136. this._pointerPressed = [];
  63137. this._offsetX = null;
  63138. this._offsetY = null;
  63139. }
  63140. };
  63141. FreeCameraTouchInput.prototype.checkInputs = function () {
  63142. if (this._offsetX && this._offsetY) {
  63143. var camera = this.camera;
  63144. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63145. if (this._pointerPressed.length > 1) {
  63146. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63147. }
  63148. else {
  63149. var speed = camera._computeLocalCameraSpeed();
  63150. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63151. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63152. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63153. }
  63154. }
  63155. };
  63156. FreeCameraTouchInput.prototype.getClassName = function () {
  63157. return "FreeCameraTouchInput";
  63158. };
  63159. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63160. return "touch";
  63161. };
  63162. __decorate([
  63163. BABYLON.serialize()
  63164. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63165. __decorate([
  63166. BABYLON.serialize()
  63167. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63168. return FreeCameraTouchInput;
  63169. }());
  63170. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63171. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63172. })(BABYLON || (BABYLON = {}));
  63173. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63174. var BABYLON;
  63175. (function (BABYLON) {
  63176. // We're mainly based on the logic defined into the FreeCamera code
  63177. var TouchCamera = /** @class */ (function (_super) {
  63178. __extends(TouchCamera, _super);
  63179. //-- end properties for backward compatibility for inputs
  63180. function TouchCamera(name, position, scene) {
  63181. var _this = _super.call(this, name, position, scene) || this;
  63182. _this.inputs.addTouch();
  63183. _this._setupInputs();
  63184. return _this;
  63185. }
  63186. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63187. //-- Begin properties for backward compatibility for inputs
  63188. get: function () {
  63189. var touch = this.inputs.attached["touch"];
  63190. if (touch)
  63191. return touch.touchAngularSensibility;
  63192. return 0;
  63193. },
  63194. set: function (value) {
  63195. var touch = this.inputs.attached["touch"];
  63196. if (touch)
  63197. touch.touchAngularSensibility = value;
  63198. },
  63199. enumerable: true,
  63200. configurable: true
  63201. });
  63202. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63203. get: function () {
  63204. var touch = this.inputs.attached["touch"];
  63205. if (touch)
  63206. return touch.touchMoveSensibility;
  63207. return 0;
  63208. },
  63209. set: function (value) {
  63210. var touch = this.inputs.attached["touch"];
  63211. if (touch)
  63212. touch.touchMoveSensibility = value;
  63213. },
  63214. enumerable: true,
  63215. configurable: true
  63216. });
  63217. TouchCamera.prototype.getClassName = function () {
  63218. return "TouchCamera";
  63219. };
  63220. TouchCamera.prototype._setupInputs = function () {
  63221. var mouse = this.inputs.attached["mouse"];
  63222. if (mouse) {
  63223. mouse.touchEnabled = false;
  63224. }
  63225. };
  63226. return TouchCamera;
  63227. }(BABYLON.FreeCamera));
  63228. BABYLON.TouchCamera = TouchCamera;
  63229. })(BABYLON || (BABYLON = {}));
  63230. //# sourceMappingURL=babylon.touchCamera.js.map
  63231. var BABYLON;
  63232. (function (BABYLON) {
  63233. var ProceduralTexture = /** @class */ (function (_super) {
  63234. __extends(ProceduralTexture, _super);
  63235. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63236. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63238. if (isCube === void 0) { isCube = false; }
  63239. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63240. _this.isCube = isCube;
  63241. _this.isEnabled = true;
  63242. _this._currentRefreshId = -1;
  63243. _this._refreshRate = 1;
  63244. _this._vertexBuffers = {};
  63245. _this._uniforms = new Array();
  63246. _this._samplers = new Array();
  63247. _this._textures = {};
  63248. _this._floats = {};
  63249. _this._floatsArrays = {};
  63250. _this._colors3 = {};
  63251. _this._colors4 = {};
  63252. _this._vectors2 = {};
  63253. _this._vectors3 = {};
  63254. _this._matrices = {};
  63255. _this._fallbackTextureUsed = false;
  63256. scene._proceduralTextures.push(_this);
  63257. _this._engine = scene.getEngine();
  63258. _this.name = name;
  63259. _this.isRenderTarget = true;
  63260. _this._size = size;
  63261. _this._generateMipMaps = generateMipMaps;
  63262. _this.setFragment(fragment);
  63263. _this._fallbackTexture = fallbackTexture;
  63264. if (isCube) {
  63265. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63266. _this.setFloat("face", 0);
  63267. }
  63268. else {
  63269. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63270. }
  63271. // VBO
  63272. var vertices = [];
  63273. vertices.push(1, 1);
  63274. vertices.push(-1, 1);
  63275. vertices.push(-1, -1);
  63276. vertices.push(1, -1);
  63277. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63278. _this._createIndexBuffer();
  63279. return _this;
  63280. }
  63281. ProceduralTexture.prototype._createIndexBuffer = function () {
  63282. var engine = this._engine;
  63283. // Indices
  63284. var indices = [];
  63285. indices.push(0);
  63286. indices.push(1);
  63287. indices.push(2);
  63288. indices.push(0);
  63289. indices.push(2);
  63290. indices.push(3);
  63291. this._indexBuffer = engine.createIndexBuffer(indices);
  63292. };
  63293. ProceduralTexture.prototype._rebuild = function () {
  63294. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63295. if (vb) {
  63296. vb._rebuild();
  63297. }
  63298. this._createIndexBuffer();
  63299. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63300. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63301. }
  63302. };
  63303. ProceduralTexture.prototype.reset = function () {
  63304. if (this._effect === undefined) {
  63305. return;
  63306. }
  63307. var engine = this._engine;
  63308. engine._releaseEffect(this._effect);
  63309. };
  63310. ProceduralTexture.prototype.isReady = function () {
  63311. var _this = this;
  63312. var engine = this._engine;
  63313. var shaders;
  63314. if (!this._fragment) {
  63315. return false;
  63316. }
  63317. if (this._fallbackTextureUsed) {
  63318. return true;
  63319. }
  63320. if (this._fragment.fragmentElement !== undefined) {
  63321. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63322. }
  63323. else {
  63324. shaders = { vertex: "procedural", fragment: this._fragment };
  63325. }
  63326. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63327. _this.releaseInternalTexture();
  63328. if (_this._fallbackTexture) {
  63329. _this._texture = _this._fallbackTexture._texture;
  63330. if (_this._texture) {
  63331. _this._texture.incrementReferences();
  63332. }
  63333. }
  63334. _this._fallbackTextureUsed = true;
  63335. });
  63336. return this._effect.isReady();
  63337. };
  63338. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63339. this._currentRefreshId = -1;
  63340. };
  63341. ProceduralTexture.prototype.setFragment = function (fragment) {
  63342. this._fragment = fragment;
  63343. };
  63344. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63345. get: function () {
  63346. return this._refreshRate;
  63347. },
  63348. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63349. set: function (value) {
  63350. this._refreshRate = value;
  63351. this.resetRefreshCounter();
  63352. },
  63353. enumerable: true,
  63354. configurable: true
  63355. });
  63356. ProceduralTexture.prototype._shouldRender = function () {
  63357. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63358. return false;
  63359. }
  63360. if (this._fallbackTextureUsed) {
  63361. return false;
  63362. }
  63363. if (this._currentRefreshId === -1) {
  63364. this._currentRefreshId = 1;
  63365. return true;
  63366. }
  63367. if (this.refreshRate === this._currentRefreshId) {
  63368. this._currentRefreshId = 1;
  63369. return true;
  63370. }
  63371. this._currentRefreshId++;
  63372. return false;
  63373. };
  63374. ProceduralTexture.prototype.getRenderSize = function () {
  63375. return this._size;
  63376. };
  63377. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63378. if (this._fallbackTextureUsed) {
  63379. return;
  63380. }
  63381. this.releaseInternalTexture();
  63382. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63383. };
  63384. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63385. if (this._uniforms.indexOf(uniformName) === -1) {
  63386. this._uniforms.push(uniformName);
  63387. }
  63388. };
  63389. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63390. if (this._samplers.indexOf(name) === -1) {
  63391. this._samplers.push(name);
  63392. }
  63393. this._textures[name] = texture;
  63394. return this;
  63395. };
  63396. ProceduralTexture.prototype.setFloat = function (name, value) {
  63397. this._checkUniform(name);
  63398. this._floats[name] = value;
  63399. return this;
  63400. };
  63401. ProceduralTexture.prototype.setFloats = function (name, value) {
  63402. this._checkUniform(name);
  63403. this._floatsArrays[name] = value;
  63404. return this;
  63405. };
  63406. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63407. this._checkUniform(name);
  63408. this._colors3[name] = value;
  63409. return this;
  63410. };
  63411. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63412. this._checkUniform(name);
  63413. this._colors4[name] = value;
  63414. return this;
  63415. };
  63416. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63417. this._checkUniform(name);
  63418. this._vectors2[name] = value;
  63419. return this;
  63420. };
  63421. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63422. this._checkUniform(name);
  63423. this._vectors3[name] = value;
  63424. return this;
  63425. };
  63426. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63427. this._checkUniform(name);
  63428. this._matrices[name] = value;
  63429. return this;
  63430. };
  63431. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63432. var scene = this.getScene();
  63433. if (!scene) {
  63434. return;
  63435. }
  63436. var engine = this._engine;
  63437. // Render
  63438. engine.enableEffect(this._effect);
  63439. engine.setState(false);
  63440. // Texture
  63441. for (var name in this._textures) {
  63442. this._effect.setTexture(name, this._textures[name]);
  63443. }
  63444. // Float
  63445. for (name in this._floats) {
  63446. this._effect.setFloat(name, this._floats[name]);
  63447. }
  63448. // Floats
  63449. for (name in this._floatsArrays) {
  63450. this._effect.setArray(name, this._floatsArrays[name]);
  63451. }
  63452. // Color3
  63453. for (name in this._colors3) {
  63454. this._effect.setColor3(name, this._colors3[name]);
  63455. }
  63456. // Color4
  63457. for (name in this._colors4) {
  63458. var color = this._colors4[name];
  63459. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63460. }
  63461. // Vector2
  63462. for (name in this._vectors2) {
  63463. this._effect.setVector2(name, this._vectors2[name]);
  63464. }
  63465. // Vector3
  63466. for (name in this._vectors3) {
  63467. this._effect.setVector3(name, this._vectors3[name]);
  63468. }
  63469. // Matrix
  63470. for (name in this._matrices) {
  63471. this._effect.setMatrix(name, this._matrices[name]);
  63472. }
  63473. if (!this._texture) {
  63474. return;
  63475. }
  63476. if (this.isCube) {
  63477. for (var face = 0; face < 6; face++) {
  63478. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63479. // VBOs
  63480. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63481. this._effect.setFloat("face", face);
  63482. // Clear
  63483. engine.clear(scene.clearColor, true, true, true);
  63484. // Draw order
  63485. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63486. // Mipmaps
  63487. if (face === 5) {
  63488. engine.generateMipMapsForCubemap(this._texture);
  63489. }
  63490. }
  63491. }
  63492. else {
  63493. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63494. // VBOs
  63495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63496. // Clear
  63497. engine.clear(scene.clearColor, true, true, true);
  63498. // Draw order
  63499. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63500. }
  63501. // Unbind
  63502. engine.unBindFramebuffer(this._texture, this.isCube);
  63503. if (this.onGenerated) {
  63504. this.onGenerated();
  63505. }
  63506. };
  63507. ProceduralTexture.prototype.clone = function () {
  63508. var textureSize = this.getSize();
  63509. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63510. // Base texture
  63511. newTexture.hasAlpha = this.hasAlpha;
  63512. newTexture.level = this.level;
  63513. // RenderTarget Texture
  63514. newTexture.coordinatesMode = this.coordinatesMode;
  63515. return newTexture;
  63516. };
  63517. ProceduralTexture.prototype.dispose = function () {
  63518. var scene = this.getScene();
  63519. if (!scene) {
  63520. return;
  63521. }
  63522. var index = scene._proceduralTextures.indexOf(this);
  63523. if (index >= 0) {
  63524. scene._proceduralTextures.splice(index, 1);
  63525. }
  63526. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63527. if (vertexBuffer) {
  63528. vertexBuffer.dispose();
  63529. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63530. }
  63531. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63532. this._indexBuffer = null;
  63533. }
  63534. _super.prototype.dispose.call(this);
  63535. };
  63536. return ProceduralTexture;
  63537. }(BABYLON.Texture));
  63538. BABYLON.ProceduralTexture = ProceduralTexture;
  63539. })(BABYLON || (BABYLON = {}));
  63540. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63541. var BABYLON;
  63542. (function (BABYLON) {
  63543. var CustomProceduralTexture = /** @class */ (function (_super) {
  63544. __extends(CustomProceduralTexture, _super);
  63545. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63546. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63547. _this._animate = true;
  63548. _this._time = 0;
  63549. _this._texturePath = texturePath;
  63550. //Try to load json
  63551. _this.loadJson(texturePath);
  63552. _this.refreshRate = 1;
  63553. return _this;
  63554. }
  63555. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63556. var _this = this;
  63557. var noConfigFile = function () {
  63558. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63559. try {
  63560. _this.setFragment(_this._texturePath);
  63561. }
  63562. catch (ex) {
  63563. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63564. }
  63565. };
  63566. var configFileUrl = jsonUrl + "/config.json";
  63567. var xhr = new XMLHttpRequest();
  63568. xhr.open("GET", configFileUrl, true);
  63569. xhr.addEventListener("load", function () {
  63570. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63571. try {
  63572. _this._config = JSON.parse(xhr.response);
  63573. _this.updateShaderUniforms();
  63574. _this.updateTextures();
  63575. _this.setFragment(_this._texturePath + "/custom");
  63576. _this._animate = _this._config.animate;
  63577. _this.refreshRate = _this._config.refreshrate;
  63578. }
  63579. catch (ex) {
  63580. noConfigFile();
  63581. }
  63582. }
  63583. else {
  63584. noConfigFile();
  63585. }
  63586. }, false);
  63587. xhr.addEventListener("error", function () {
  63588. noConfigFile();
  63589. }, false);
  63590. try {
  63591. xhr.send();
  63592. }
  63593. catch (ex) {
  63594. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63595. }
  63596. };
  63597. CustomProceduralTexture.prototype.isReady = function () {
  63598. if (!_super.prototype.isReady.call(this)) {
  63599. return false;
  63600. }
  63601. for (var name in this._textures) {
  63602. var texture = this._textures[name];
  63603. if (!texture.isReady()) {
  63604. return false;
  63605. }
  63606. }
  63607. return true;
  63608. };
  63609. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63610. var scene = this.getScene();
  63611. if (this._animate && scene) {
  63612. this._time += scene.getAnimationRatio() * 0.03;
  63613. this.updateShaderUniforms();
  63614. }
  63615. _super.prototype.render.call(this, useCameraPostProcess);
  63616. };
  63617. CustomProceduralTexture.prototype.updateTextures = function () {
  63618. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63619. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63620. }
  63621. };
  63622. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63623. if (this._config) {
  63624. for (var j = 0; j < this._config.uniforms.length; j++) {
  63625. var uniform = this._config.uniforms[j];
  63626. switch (uniform.type) {
  63627. case "float":
  63628. this.setFloat(uniform.name, uniform.value);
  63629. break;
  63630. case "color3":
  63631. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63632. break;
  63633. case "color4":
  63634. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63635. break;
  63636. case "vector2":
  63637. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63638. break;
  63639. case "vector3":
  63640. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63641. break;
  63642. }
  63643. }
  63644. }
  63645. this.setFloat("time", this._time);
  63646. };
  63647. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63648. get: function () {
  63649. return this._animate;
  63650. },
  63651. set: function (value) {
  63652. this._animate = value;
  63653. },
  63654. enumerable: true,
  63655. configurable: true
  63656. });
  63657. return CustomProceduralTexture;
  63658. }(BABYLON.ProceduralTexture));
  63659. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63660. })(BABYLON || (BABYLON = {}));
  63661. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63662. var BABYLON;
  63663. (function (BABYLON) {
  63664. var FreeCameraGamepadInput = /** @class */ (function () {
  63665. function FreeCameraGamepadInput() {
  63666. this.gamepadAngularSensibility = 200;
  63667. this.gamepadMoveSensibility = 40;
  63668. // private members
  63669. this._cameraTransform = BABYLON.Matrix.Identity();
  63670. this._deltaTransform = BABYLON.Vector3.Zero();
  63671. this._vector3 = BABYLON.Vector3.Zero();
  63672. this._vector2 = BABYLON.Vector2.Zero();
  63673. }
  63674. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63675. var _this = this;
  63676. var manager = this.camera.getScene().gamepadManager;
  63677. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63678. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63679. // prioritize XBOX gamepads.
  63680. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63681. _this.gamepad = gamepad;
  63682. }
  63683. }
  63684. });
  63685. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63686. if (_this.gamepad === gamepad) {
  63687. _this.gamepad = null;
  63688. }
  63689. });
  63690. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63691. };
  63692. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63693. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63694. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63695. this.gamepad = null;
  63696. };
  63697. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63698. if (this.gamepad && this.gamepad.leftStick) {
  63699. var camera = this.camera;
  63700. var LSValues = this.gamepad.leftStick;
  63701. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63702. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63703. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63704. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63705. var RSValues = this.gamepad.rightStick;
  63706. if (RSValues) {
  63707. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63708. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63709. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63710. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63711. }
  63712. else {
  63713. RSValues = { x: 0, y: 0 };
  63714. }
  63715. if (!camera.rotationQuaternion) {
  63716. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63717. }
  63718. else {
  63719. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63720. }
  63721. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63722. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63723. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63724. camera.cameraDirection.addInPlace(this._deltaTransform);
  63725. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63726. camera.cameraRotation.addInPlace(this._vector2);
  63727. }
  63728. };
  63729. FreeCameraGamepadInput.prototype.getClassName = function () {
  63730. return "FreeCameraGamepadInput";
  63731. };
  63732. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63733. return "gamepad";
  63734. };
  63735. __decorate([
  63736. BABYLON.serialize()
  63737. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63738. __decorate([
  63739. BABYLON.serialize()
  63740. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63741. return FreeCameraGamepadInput;
  63742. }());
  63743. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63744. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63745. })(BABYLON || (BABYLON = {}));
  63746. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63747. var BABYLON;
  63748. (function (BABYLON) {
  63749. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63750. function ArcRotateCameraGamepadInput() {
  63751. this.gamepadRotationSensibility = 80;
  63752. this.gamepadMoveSensibility = 40;
  63753. }
  63754. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63755. var _this = this;
  63756. var manager = this.camera.getScene().gamepadManager;
  63757. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63758. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63759. // prioritize XBOX gamepads.
  63760. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63761. _this.gamepad = gamepad;
  63762. }
  63763. }
  63764. });
  63765. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63766. if (_this.gamepad === gamepad) {
  63767. _this.gamepad = null;
  63768. }
  63769. });
  63770. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63771. };
  63772. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63773. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63774. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63775. this.gamepad = null;
  63776. };
  63777. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63778. if (this.gamepad) {
  63779. var camera = this.camera;
  63780. var RSValues = this.gamepad.rightStick;
  63781. if (RSValues) {
  63782. if (RSValues.x != 0) {
  63783. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63784. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63785. camera.inertialAlphaOffset += normalizedRX;
  63786. }
  63787. }
  63788. if (RSValues.y != 0) {
  63789. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63790. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63791. camera.inertialBetaOffset += normalizedRY;
  63792. }
  63793. }
  63794. }
  63795. var LSValues = this.gamepad.leftStick;
  63796. if (LSValues && LSValues.y != 0) {
  63797. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63798. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63799. this.camera.inertialRadiusOffset -= normalizedLY;
  63800. }
  63801. }
  63802. }
  63803. };
  63804. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63805. return "ArcRotateCameraGamepadInput";
  63806. };
  63807. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63808. return "gamepad";
  63809. };
  63810. __decorate([
  63811. BABYLON.serialize()
  63812. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63813. __decorate([
  63814. BABYLON.serialize()
  63815. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63816. return ArcRotateCameraGamepadInput;
  63817. }());
  63818. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63819. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63820. })(BABYLON || (BABYLON = {}));
  63821. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63822. var BABYLON;
  63823. (function (BABYLON) {
  63824. var GamepadManager = /** @class */ (function () {
  63825. function GamepadManager(_scene) {
  63826. var _this = this;
  63827. this._scene = _scene;
  63828. this._babylonGamepads = [];
  63829. this._oneGamepadConnected = false;
  63830. this._isMonitoring = false;
  63831. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63832. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63833. this._gamepadEventSupported = false;
  63834. }
  63835. else {
  63836. this._gamepadEventSupported = 'GamepadEvent' in window;
  63837. this._gamepadSupport = (navigator.getGamepads ||
  63838. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63839. }
  63840. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63841. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63842. for (var i in _this._babylonGamepads) {
  63843. var gamepad = _this._babylonGamepads[i];
  63844. if (gamepad && gamepad._isConnected) {
  63845. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63846. }
  63847. }
  63848. });
  63849. this._onGamepadConnectedEvent = function (evt) {
  63850. var gamepad = evt.gamepad;
  63851. if (gamepad.index in _this._babylonGamepads) {
  63852. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63853. return;
  63854. }
  63855. }
  63856. var newGamepad;
  63857. if (_this._babylonGamepads[gamepad.index]) {
  63858. newGamepad = _this._babylonGamepads[gamepad.index];
  63859. newGamepad.browserGamepad = gamepad;
  63860. newGamepad._isConnected = true;
  63861. }
  63862. else {
  63863. newGamepad = _this._addNewGamepad(gamepad);
  63864. }
  63865. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63866. _this._startMonitoringGamepads();
  63867. };
  63868. this._onGamepadDisconnectedEvent = function (evt) {
  63869. var gamepad = evt.gamepad;
  63870. // Remove the gamepad from the list of gamepads to monitor.
  63871. for (var i in _this._babylonGamepads) {
  63872. if (_this._babylonGamepads[i].index === gamepad.index) {
  63873. var disconnectedGamepad = _this._babylonGamepads[i];
  63874. disconnectedGamepad._isConnected = false;
  63875. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63876. break;
  63877. }
  63878. }
  63879. };
  63880. if (this._gamepadSupport) {
  63881. //first add already-connected gamepads
  63882. this._updateGamepadObjects();
  63883. if (this._babylonGamepads.length) {
  63884. this._startMonitoringGamepads();
  63885. }
  63886. // Checking if the gamepad connected event is supported (like in Firefox)
  63887. if (this._gamepadEventSupported) {
  63888. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63889. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63890. }
  63891. else {
  63892. this._startMonitoringGamepads();
  63893. }
  63894. }
  63895. }
  63896. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63897. get: function () {
  63898. return this._babylonGamepads;
  63899. },
  63900. enumerable: true,
  63901. configurable: true
  63902. });
  63903. GamepadManager.prototype.getGamepadByType = function (type) {
  63904. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63905. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63906. var gamepad = _a[_i];
  63907. if (gamepad && gamepad.type === type) {
  63908. return gamepad;
  63909. }
  63910. }
  63911. return null;
  63912. };
  63913. GamepadManager.prototype.dispose = function () {
  63914. if (this._gamepadEventSupported) {
  63915. if (this._onGamepadConnectedEvent) {
  63916. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63917. }
  63918. if (this._onGamepadDisconnectedEvent) {
  63919. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63920. }
  63921. this._onGamepadConnectedEvent = null;
  63922. this._onGamepadDisconnectedEvent = null;
  63923. }
  63924. this._babylonGamepads.forEach(function (gamepad) {
  63925. gamepad.dispose();
  63926. });
  63927. this.onGamepadConnectedObservable.clear();
  63928. this.onGamepadDisconnectedObservable.clear();
  63929. this._oneGamepadConnected = false;
  63930. this._stopMonitoringGamepads();
  63931. this._babylonGamepads = [];
  63932. };
  63933. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63934. if (!this._oneGamepadConnected) {
  63935. this._oneGamepadConnected = true;
  63936. }
  63937. var newGamepad;
  63938. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63939. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63940. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63941. }
  63942. else if (gamepad.pose) {
  63943. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63944. }
  63945. else {
  63946. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63947. }
  63948. this._babylonGamepads[newGamepad.index] = newGamepad;
  63949. return newGamepad;
  63950. };
  63951. GamepadManager.prototype._startMonitoringGamepads = function () {
  63952. if (!this._isMonitoring) {
  63953. this._isMonitoring = true;
  63954. //back-comp
  63955. if (!this._scene) {
  63956. this._checkGamepadsStatus();
  63957. }
  63958. }
  63959. };
  63960. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63961. this._isMonitoring = false;
  63962. };
  63963. GamepadManager.prototype._checkGamepadsStatus = function () {
  63964. var _this = this;
  63965. // Hack to be compatible Chrome
  63966. this._updateGamepadObjects();
  63967. for (var i in this._babylonGamepads) {
  63968. var gamepad = this._babylonGamepads[i];
  63969. if (!gamepad || !gamepad.isConnected) {
  63970. continue;
  63971. }
  63972. gamepad.update();
  63973. }
  63974. if (this._isMonitoring && !this._scene) {
  63975. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63976. }
  63977. };
  63978. // This function is called only on Chrome, which does not properly support
  63979. // connection/disconnection events and forces you to recopy again the gamepad object
  63980. GamepadManager.prototype._updateGamepadObjects = function () {
  63981. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63982. for (var i = 0; i < gamepads.length; i++) {
  63983. if (gamepads[i]) {
  63984. if (!this._babylonGamepads[gamepads[i].index]) {
  63985. var newGamepad = this._addNewGamepad(gamepads[i]);
  63986. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63987. }
  63988. else {
  63989. // Forced to copy again this object for Chrome for unknown reason
  63990. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63991. if (!this._babylonGamepads[i].isConnected) {
  63992. this._babylonGamepads[i]._isConnected = true;
  63993. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63994. }
  63995. }
  63996. }
  63997. }
  63998. };
  63999. return GamepadManager;
  64000. }());
  64001. BABYLON.GamepadManager = GamepadManager;
  64002. })(BABYLON || (BABYLON = {}));
  64003. //# sourceMappingURL=babylon.gamepadManager.js.map
  64004. var BABYLON;
  64005. (function (BABYLON) {
  64006. var StickValues = /** @class */ (function () {
  64007. function StickValues(x, y) {
  64008. this.x = x;
  64009. this.y = y;
  64010. }
  64011. return StickValues;
  64012. }());
  64013. BABYLON.StickValues = StickValues;
  64014. var Gamepad = /** @class */ (function () {
  64015. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64016. if (leftStickX === void 0) { leftStickX = 0; }
  64017. if (leftStickY === void 0) { leftStickY = 1; }
  64018. if (rightStickX === void 0) { rightStickX = 2; }
  64019. if (rightStickY === void 0) { rightStickY = 3; }
  64020. this.id = id;
  64021. this.index = index;
  64022. this.browserGamepad = browserGamepad;
  64023. this._isConnected = true;
  64024. this._invertLeftStickY = false;
  64025. this.type = Gamepad.GAMEPAD;
  64026. this._leftStickAxisX = leftStickX;
  64027. this._leftStickAxisY = leftStickY;
  64028. this._rightStickAxisX = rightStickX;
  64029. this._rightStickAxisY = rightStickY;
  64030. if (this.browserGamepad.axes.length >= 2) {
  64031. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64032. }
  64033. if (this.browserGamepad.axes.length >= 4) {
  64034. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64035. }
  64036. }
  64037. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64038. get: function () {
  64039. return this._isConnected;
  64040. },
  64041. enumerable: true,
  64042. configurable: true
  64043. });
  64044. Gamepad.prototype.onleftstickchanged = function (callback) {
  64045. this._onleftstickchanged = callback;
  64046. };
  64047. Gamepad.prototype.onrightstickchanged = function (callback) {
  64048. this._onrightstickchanged = callback;
  64049. };
  64050. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64051. get: function () {
  64052. return this._leftStick;
  64053. },
  64054. set: function (newValues) {
  64055. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64056. this._onleftstickchanged(newValues);
  64057. }
  64058. this._leftStick = newValues;
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64064. get: function () {
  64065. return this._rightStick;
  64066. },
  64067. set: function (newValues) {
  64068. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64069. this._onrightstickchanged(newValues);
  64070. }
  64071. this._rightStick = newValues;
  64072. },
  64073. enumerable: true,
  64074. configurable: true
  64075. });
  64076. Gamepad.prototype.update = function () {
  64077. if (this._leftStick) {
  64078. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64079. if (this._invertLeftStickY) {
  64080. this.leftStick.y *= -1;
  64081. }
  64082. }
  64083. if (this._rightStick) {
  64084. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64085. }
  64086. };
  64087. Gamepad.prototype.dispose = function () {
  64088. };
  64089. Gamepad.GAMEPAD = 0;
  64090. Gamepad.GENERIC = 1;
  64091. Gamepad.XBOX = 2;
  64092. Gamepad.POSE_ENABLED = 3;
  64093. return Gamepad;
  64094. }());
  64095. BABYLON.Gamepad = Gamepad;
  64096. var GenericPad = /** @class */ (function (_super) {
  64097. __extends(GenericPad, _super);
  64098. function GenericPad(id, index, browserGamepad) {
  64099. var _this = _super.call(this, id, index, browserGamepad) || this;
  64100. _this.onButtonDownObservable = new BABYLON.Observable();
  64101. _this.onButtonUpObservable = new BABYLON.Observable();
  64102. _this.type = Gamepad.GENERIC;
  64103. _this._buttons = new Array(browserGamepad.buttons.length);
  64104. return _this;
  64105. }
  64106. GenericPad.prototype.onbuttondown = function (callback) {
  64107. this._onbuttondown = callback;
  64108. };
  64109. GenericPad.prototype.onbuttonup = function (callback) {
  64110. this._onbuttonup = callback;
  64111. };
  64112. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64113. if (newValue !== currentValue) {
  64114. if (newValue === 1) {
  64115. if (this._onbuttondown) {
  64116. this._onbuttondown(buttonIndex);
  64117. }
  64118. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64119. }
  64120. if (newValue === 0) {
  64121. if (this._onbuttonup) {
  64122. this._onbuttonup(buttonIndex);
  64123. }
  64124. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64125. }
  64126. }
  64127. return newValue;
  64128. };
  64129. GenericPad.prototype.update = function () {
  64130. _super.prototype.update.call(this);
  64131. for (var index = 0; index < this._buttons.length; index++) {
  64132. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64133. }
  64134. };
  64135. GenericPad.prototype.dispose = function () {
  64136. _super.prototype.dispose.call(this);
  64137. this.onButtonDownObservable.clear();
  64138. this.onButtonUpObservable.clear();
  64139. };
  64140. return GenericPad;
  64141. }(Gamepad));
  64142. BABYLON.GenericPad = GenericPad;
  64143. })(BABYLON || (BABYLON = {}));
  64144. //# sourceMappingURL=babylon.gamepad.js.map
  64145. var BABYLON;
  64146. (function (BABYLON) {
  64147. var Xbox360Button;
  64148. (function (Xbox360Button) {
  64149. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64150. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64151. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64152. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64153. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64154. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64155. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64156. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64157. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64158. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64159. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64160. var Xbox360Dpad;
  64161. (function (Xbox360Dpad) {
  64162. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64163. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64164. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64165. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64166. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64167. var Xbox360Pad = /** @class */ (function (_super) {
  64168. __extends(Xbox360Pad, _super);
  64169. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64170. if (xboxOne === void 0) { xboxOne = false; }
  64171. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64172. _this._leftTrigger = 0;
  64173. _this._rightTrigger = 0;
  64174. _this.onButtonDownObservable = new BABYLON.Observable();
  64175. _this.onButtonUpObservable = new BABYLON.Observable();
  64176. _this.onPadDownObservable = new BABYLON.Observable();
  64177. _this.onPadUpObservable = new BABYLON.Observable();
  64178. _this._buttonA = 0;
  64179. _this._buttonB = 0;
  64180. _this._buttonX = 0;
  64181. _this._buttonY = 0;
  64182. _this._buttonBack = 0;
  64183. _this._buttonStart = 0;
  64184. _this._buttonLB = 0;
  64185. _this._buttonRB = 0;
  64186. _this._buttonLeftStick = 0;
  64187. _this._buttonRightStick = 0;
  64188. _this._dPadUp = 0;
  64189. _this._dPadDown = 0;
  64190. _this._dPadLeft = 0;
  64191. _this._dPadRight = 0;
  64192. _this._isXboxOnePad = false;
  64193. _this.type = BABYLON.Gamepad.XBOX;
  64194. _this._isXboxOnePad = xboxOne;
  64195. return _this;
  64196. }
  64197. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64198. this._onlefttriggerchanged = callback;
  64199. };
  64200. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64201. this._onrighttriggerchanged = callback;
  64202. };
  64203. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64204. get: function () {
  64205. return this._leftTrigger;
  64206. },
  64207. set: function (newValue) {
  64208. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64209. this._onlefttriggerchanged(newValue);
  64210. }
  64211. this._leftTrigger = newValue;
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64217. get: function () {
  64218. return this._rightTrigger;
  64219. },
  64220. set: function (newValue) {
  64221. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64222. this._onrighttriggerchanged(newValue);
  64223. }
  64224. this._rightTrigger = newValue;
  64225. },
  64226. enumerable: true,
  64227. configurable: true
  64228. });
  64229. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64230. this._onbuttondown = callback;
  64231. };
  64232. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64233. this._onbuttonup = callback;
  64234. };
  64235. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64236. this._ondpaddown = callback;
  64237. };
  64238. Xbox360Pad.prototype.ondpadup = function (callback) {
  64239. this._ondpadup = callback;
  64240. };
  64241. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64242. if (newValue !== currentValue) {
  64243. if (newValue === 1) {
  64244. if (this._onbuttondown) {
  64245. this._onbuttondown(buttonType);
  64246. }
  64247. this.onButtonDownObservable.notifyObservers(buttonType);
  64248. }
  64249. if (newValue === 0) {
  64250. if (this._onbuttonup) {
  64251. this._onbuttonup(buttonType);
  64252. }
  64253. this.onButtonUpObservable.notifyObservers(buttonType);
  64254. }
  64255. }
  64256. return newValue;
  64257. };
  64258. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64259. if (newValue !== currentValue) {
  64260. if (newValue === 1) {
  64261. if (this._ondpaddown) {
  64262. this._ondpaddown(buttonType);
  64263. }
  64264. this.onPadDownObservable.notifyObservers(buttonType);
  64265. }
  64266. if (newValue === 0) {
  64267. if (this._ondpadup) {
  64268. this._ondpadup(buttonType);
  64269. }
  64270. this.onPadUpObservable.notifyObservers(buttonType);
  64271. }
  64272. }
  64273. return newValue;
  64274. };
  64275. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64276. get: function () {
  64277. return this._buttonA;
  64278. },
  64279. set: function (value) {
  64280. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64281. },
  64282. enumerable: true,
  64283. configurable: true
  64284. });
  64285. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64286. get: function () {
  64287. return this._buttonB;
  64288. },
  64289. set: function (value) {
  64290. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64291. },
  64292. enumerable: true,
  64293. configurable: true
  64294. });
  64295. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64296. get: function () {
  64297. return this._buttonX;
  64298. },
  64299. set: function (value) {
  64300. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64301. },
  64302. enumerable: true,
  64303. configurable: true
  64304. });
  64305. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64306. get: function () {
  64307. return this._buttonY;
  64308. },
  64309. set: function (value) {
  64310. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64311. },
  64312. enumerable: true,
  64313. configurable: true
  64314. });
  64315. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64316. get: function () {
  64317. return this._buttonStart;
  64318. },
  64319. set: function (value) {
  64320. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64321. },
  64322. enumerable: true,
  64323. configurable: true
  64324. });
  64325. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64326. get: function () {
  64327. return this._buttonBack;
  64328. },
  64329. set: function (value) {
  64330. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64331. },
  64332. enumerable: true,
  64333. configurable: true
  64334. });
  64335. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64336. get: function () {
  64337. return this._buttonLB;
  64338. },
  64339. set: function (value) {
  64340. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64341. },
  64342. enumerable: true,
  64343. configurable: true
  64344. });
  64345. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64346. get: function () {
  64347. return this._buttonRB;
  64348. },
  64349. set: function (value) {
  64350. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64351. },
  64352. enumerable: true,
  64353. configurable: true
  64354. });
  64355. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64356. get: function () {
  64357. return this._buttonLeftStick;
  64358. },
  64359. set: function (value) {
  64360. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64361. },
  64362. enumerable: true,
  64363. configurable: true
  64364. });
  64365. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64366. get: function () {
  64367. return this._buttonRightStick;
  64368. },
  64369. set: function (value) {
  64370. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64371. },
  64372. enumerable: true,
  64373. configurable: true
  64374. });
  64375. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64376. get: function () {
  64377. return this._dPadUp;
  64378. },
  64379. set: function (value) {
  64380. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64381. },
  64382. enumerable: true,
  64383. configurable: true
  64384. });
  64385. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64386. get: function () {
  64387. return this._dPadDown;
  64388. },
  64389. set: function (value) {
  64390. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64391. },
  64392. enumerable: true,
  64393. configurable: true
  64394. });
  64395. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64396. get: function () {
  64397. return this._dPadLeft;
  64398. },
  64399. set: function (value) {
  64400. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64401. },
  64402. enumerable: true,
  64403. configurable: true
  64404. });
  64405. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64406. get: function () {
  64407. return this._dPadRight;
  64408. },
  64409. set: function (value) {
  64410. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64411. },
  64412. enumerable: true,
  64413. configurable: true
  64414. });
  64415. Xbox360Pad.prototype.update = function () {
  64416. _super.prototype.update.call(this);
  64417. if (this._isXboxOnePad) {
  64418. this.buttonA = this.browserGamepad.buttons[0].value;
  64419. this.buttonB = this.browserGamepad.buttons[1].value;
  64420. this.buttonX = this.browserGamepad.buttons[2].value;
  64421. this.buttonY = this.browserGamepad.buttons[3].value;
  64422. this.buttonLB = this.browserGamepad.buttons[4].value;
  64423. this.buttonRB = this.browserGamepad.buttons[5].value;
  64424. this.leftTrigger = this.browserGamepad.axes[2];
  64425. this.rightTrigger = this.browserGamepad.axes[5];
  64426. this.buttonBack = this.browserGamepad.buttons[9].value;
  64427. this.buttonStart = this.browserGamepad.buttons[8].value;
  64428. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64429. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64430. this.dPadUp = this.browserGamepad.buttons[11].value;
  64431. this.dPadDown = this.browserGamepad.buttons[12].value;
  64432. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64433. this.dPadRight = this.browserGamepad.buttons[14].value;
  64434. }
  64435. else {
  64436. this.buttonA = this.browserGamepad.buttons[0].value;
  64437. this.buttonB = this.browserGamepad.buttons[1].value;
  64438. this.buttonX = this.browserGamepad.buttons[2].value;
  64439. this.buttonY = this.browserGamepad.buttons[3].value;
  64440. this.buttonLB = this.browserGamepad.buttons[4].value;
  64441. this.buttonRB = this.browserGamepad.buttons[5].value;
  64442. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64443. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64444. this.buttonBack = this.browserGamepad.buttons[8].value;
  64445. this.buttonStart = this.browserGamepad.buttons[9].value;
  64446. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64447. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64448. this.dPadUp = this.browserGamepad.buttons[12].value;
  64449. this.dPadDown = this.browserGamepad.buttons[13].value;
  64450. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64451. this.dPadRight = this.browserGamepad.buttons[15].value;
  64452. }
  64453. };
  64454. Xbox360Pad.prototype.dispose = function () {
  64455. _super.prototype.dispose.call(this);
  64456. this.onButtonDownObservable.clear();
  64457. this.onButtonUpObservable.clear();
  64458. this.onPadDownObservable.clear();
  64459. this.onPadUpObservable.clear();
  64460. };
  64461. return Xbox360Pad;
  64462. }(BABYLON.Gamepad));
  64463. BABYLON.Xbox360Pad = Xbox360Pad;
  64464. })(BABYLON || (BABYLON = {}));
  64465. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64466. var BABYLON;
  64467. (function (BABYLON) {
  64468. var PoseEnabledControllerType;
  64469. (function (PoseEnabledControllerType) {
  64470. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64471. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64472. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64473. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64474. /**
  64475. * Google Daydream
  64476. */
  64477. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64478. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64479. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64480. var PoseEnabledControllerHelper = /** @class */ (function () {
  64481. function PoseEnabledControllerHelper() {
  64482. }
  64483. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64484. // Oculus Touch
  64485. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64486. return new BABYLON.OculusTouchController(vrGamepad);
  64487. }
  64488. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64489. return new BABYLON.WindowsMotionController(vrGamepad);
  64490. }
  64491. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64492. return new BABYLON.ViveController(vrGamepad);
  64493. }
  64494. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64495. return new BABYLON.GearVRController(vrGamepad);
  64496. }
  64497. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64498. return new BABYLON.DaydreamController(vrGamepad);
  64499. }
  64500. else {
  64501. return new BABYLON.GenericController(vrGamepad);
  64502. }
  64503. };
  64504. return PoseEnabledControllerHelper;
  64505. }());
  64506. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64507. var PoseEnabledController = /** @class */ (function (_super) {
  64508. __extends(PoseEnabledController, _super);
  64509. function PoseEnabledController(browserGamepad) {
  64510. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64511. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64512. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64513. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64514. // Represents device position and rotation in babylon space
  64515. _this.devicePosition = BABYLON.Vector3.Zero();
  64516. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64517. _this.deviceScaleFactor = 1;
  64518. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64519. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64520. /**
  64521. * Node to be used when casting a ray from the controller
  64522. */
  64523. _this._pointingPoseNode = null;
  64524. _this._workingMatrix = BABYLON.Matrix.Identity();
  64525. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64526. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64527. _this.position = BABYLON.Vector3.Zero();
  64528. _this.rotationQuaternion = new BABYLON.Quaternion();
  64529. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64530. _this._calculatedRotation = new BABYLON.Quaternion();
  64531. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64532. return _this;
  64533. }
  64534. PoseEnabledController.prototype.update = function () {
  64535. _super.prototype.update.call(this);
  64536. var pose = this.browserGamepad.pose;
  64537. this.updateFromDevice(pose);
  64538. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64539. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64540. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64541. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64542. if (this._mesh) {
  64543. this._mesh.position.copyFrom(this.devicePosition);
  64544. if (this._mesh.rotationQuaternion) {
  64545. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64546. }
  64547. }
  64548. };
  64549. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64550. if (poseData) {
  64551. this.rawPose = poseData;
  64552. if (poseData.position) {
  64553. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64554. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64555. this._deviceRoomPosition.z *= -1;
  64556. }
  64557. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64558. this._calculatedPosition.addInPlace(this.position);
  64559. }
  64560. var pose = this.rawPose;
  64561. if (poseData.orientation && pose.orientation) {
  64562. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64563. if (this._mesh) {
  64564. if (this._mesh.getScene().useRightHandedSystem) {
  64565. this._deviceRoomRotationQuaternion.z *= -1;
  64566. this._deviceRoomRotationQuaternion.w *= -1;
  64567. }
  64568. else {
  64569. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64570. }
  64571. }
  64572. // if the camera is set, rotate to the camera's rotation
  64573. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64574. }
  64575. }
  64576. };
  64577. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64578. if (this._mesh) {
  64579. this._mesh.parent = null;
  64580. }
  64581. this._mesh = mesh;
  64582. if (this._poseControlledCamera) {
  64583. this._mesh.parent = this._poseControlledCamera;
  64584. }
  64585. if (!this._mesh.rotationQuaternion) {
  64586. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64587. }
  64588. };
  64589. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64590. this._poseControlledCamera = camera;
  64591. if (this._mesh) {
  64592. this._mesh.parent = this._poseControlledCamera;
  64593. }
  64594. };
  64595. PoseEnabledController.prototype.dispose = function () {
  64596. if (this._mesh) {
  64597. this._mesh.dispose();
  64598. }
  64599. this._mesh = null;
  64600. _super.prototype.dispose.call(this);
  64601. };
  64602. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64603. get: function () {
  64604. return this._mesh;
  64605. },
  64606. enumerable: true,
  64607. configurable: true
  64608. });
  64609. PoseEnabledController.prototype.getForwardRay = function (length) {
  64610. if (length === void 0) { length = 100; }
  64611. if (!this.mesh) {
  64612. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64613. }
  64614. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64615. var origin = m.getTranslation();
  64616. var forward = new BABYLON.Vector3(0, 0, -1);
  64617. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64618. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64619. return new BABYLON.Ray(origin, direction, length);
  64620. };
  64621. /**
  64622. * Name of the child mesh that can be used to cast a ray from the controller
  64623. */
  64624. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64625. return PoseEnabledController;
  64626. }(BABYLON.Gamepad));
  64627. BABYLON.PoseEnabledController = PoseEnabledController;
  64628. })(BABYLON || (BABYLON = {}));
  64629. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64630. var BABYLON;
  64631. (function (BABYLON) {
  64632. var WebVRController = /** @class */ (function (_super) {
  64633. __extends(WebVRController, _super);
  64634. function WebVRController(vrGamepad) {
  64635. var _this = _super.call(this, vrGamepad) || this;
  64636. // Observables
  64637. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64638. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64639. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64640. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64641. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64642. _this.pad = { x: 0, y: 0 };
  64643. // avoid GC, store state in a tmp object
  64644. _this._changes = {
  64645. pressChanged: false,
  64646. touchChanged: false,
  64647. valueChanged: false,
  64648. changed: false
  64649. };
  64650. _this._buttons = new Array(vrGamepad.buttons.length);
  64651. _this.hand = vrGamepad.hand;
  64652. return _this;
  64653. }
  64654. WebVRController.prototype.onButtonStateChange = function (callback) {
  64655. this._onButtonStateChange = callback;
  64656. };
  64657. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64658. get: function () {
  64659. return this._defaultModel;
  64660. },
  64661. enumerable: true,
  64662. configurable: true
  64663. });
  64664. WebVRController.prototype.update = function () {
  64665. _super.prototype.update.call(this);
  64666. for (var index = 0; index < this._buttons.length; index++) {
  64667. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64668. }
  64669. ;
  64670. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64671. this.pad.x = this.leftStick.x;
  64672. this.pad.y = this.leftStick.y;
  64673. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64674. }
  64675. };
  64676. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64677. if (!newState) {
  64678. newState = {
  64679. pressed: false,
  64680. touched: false,
  64681. value: 0
  64682. };
  64683. }
  64684. if (!currentState) {
  64685. this._buttons[buttonIndex] = {
  64686. pressed: newState.pressed,
  64687. touched: newState.touched,
  64688. value: newState.value
  64689. };
  64690. return;
  64691. }
  64692. this._checkChanges(newState, currentState);
  64693. if (this._changes.changed) {
  64694. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64695. this._handleButtonChange(buttonIndex, newState, this._changes);
  64696. }
  64697. this._buttons[buttonIndex].pressed = newState.pressed;
  64698. this._buttons[buttonIndex].touched = newState.touched;
  64699. // oculus triggers are never 0, thou not touched.
  64700. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64701. };
  64702. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64703. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64704. this._changes.touchChanged = newState.touched !== currentState.touched;
  64705. this._changes.valueChanged = newState.value !== currentState.value;
  64706. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64707. return this._changes;
  64708. };
  64709. WebVRController.prototype.dispose = function () {
  64710. _super.prototype.dispose.call(this);
  64711. this.onTriggerStateChangedObservable.clear();
  64712. this.onMainButtonStateChangedObservable.clear();
  64713. this.onSecondaryButtonStateChangedObservable.clear();
  64714. this.onPadStateChangedObservable.clear();
  64715. this.onPadValuesChangedObservable.clear();
  64716. };
  64717. return WebVRController;
  64718. }(BABYLON.PoseEnabledController));
  64719. BABYLON.WebVRController = WebVRController;
  64720. })(BABYLON || (BABYLON = {}));
  64721. //# sourceMappingURL=babylon.webVRController.js.map
  64722. var BABYLON;
  64723. (function (BABYLON) {
  64724. var OculusTouchController = /** @class */ (function (_super) {
  64725. __extends(OculusTouchController, _super);
  64726. function OculusTouchController(vrGamepad) {
  64727. var _this = _super.call(this, vrGamepad) || this;
  64728. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64729. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64730. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64731. return _this;
  64732. }
  64733. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64734. var _this = this;
  64735. var meshName;
  64736. // Hand
  64737. if (this.hand === 'left') {
  64738. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64739. }
  64740. else {
  64741. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64742. }
  64743. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64744. /*
  64745. Parent Mesh name: oculus_touch_left
  64746. - body
  64747. - trigger
  64748. - thumbstick
  64749. - grip
  64750. - button_y
  64751. - button_x
  64752. - button_enter
  64753. */
  64754. _this._defaultModel = newMeshes[1];
  64755. _this.attachToMesh(_this._defaultModel);
  64756. if (meshLoaded) {
  64757. meshLoaded(_this._defaultModel);
  64758. }
  64759. });
  64760. };
  64761. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64762. // helper getters for left and right hand.
  64763. get: function () {
  64764. if (this.hand === 'right') {
  64765. return this.onMainButtonStateChangedObservable;
  64766. }
  64767. else {
  64768. throw new Error('No A button on left hand');
  64769. }
  64770. },
  64771. enumerable: true,
  64772. configurable: true
  64773. });
  64774. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64775. get: function () {
  64776. if (this.hand === 'right') {
  64777. return this.onSecondaryButtonStateChangedObservable;
  64778. }
  64779. else {
  64780. throw new Error('No B button on left hand');
  64781. }
  64782. },
  64783. enumerable: true,
  64784. configurable: true
  64785. });
  64786. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64787. get: function () {
  64788. if (this.hand === 'left') {
  64789. return this.onMainButtonStateChangedObservable;
  64790. }
  64791. else {
  64792. throw new Error('No X button on right hand');
  64793. }
  64794. },
  64795. enumerable: true,
  64796. configurable: true
  64797. });
  64798. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64799. get: function () {
  64800. if (this.hand === 'left') {
  64801. return this.onSecondaryButtonStateChangedObservable;
  64802. }
  64803. else {
  64804. throw new Error('No Y button on right hand');
  64805. }
  64806. },
  64807. enumerable: true,
  64808. configurable: true
  64809. });
  64810. /*
  64811. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64812. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64813. 2) secondary trigger (same)
  64814. 3) A (right) X (left), touch, pressed = value
  64815. 4) B / Y
  64816. 5) thumb rest
  64817. */
  64818. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64819. var notifyObject = state; //{ state: state, changes: changes };
  64820. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64821. switch (buttonIdx) {
  64822. case 0:
  64823. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64824. return;
  64825. case 1:// index trigger
  64826. if (this._defaultModel) {
  64827. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64828. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64829. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64830. }
  64831. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64832. return;
  64833. case 2:// secondary trigger
  64834. if (this._defaultModel) {
  64835. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64836. }
  64837. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64838. return;
  64839. case 3:
  64840. if (this._defaultModel) {
  64841. if (notifyObject.pressed) {
  64842. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64843. }
  64844. else {
  64845. (this._defaultModel.getChildren()[1]).position.y = 0;
  64846. }
  64847. }
  64848. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64849. return;
  64850. case 4:
  64851. if (this._defaultModel) {
  64852. if (notifyObject.pressed) {
  64853. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64854. }
  64855. else {
  64856. (this._defaultModel.getChildren()[2]).position.y = 0;
  64857. }
  64858. }
  64859. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64860. return;
  64861. case 5:
  64862. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64863. return;
  64864. }
  64865. };
  64866. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64867. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64868. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64869. return OculusTouchController;
  64870. }(BABYLON.WebVRController));
  64871. BABYLON.OculusTouchController = OculusTouchController;
  64872. })(BABYLON || (BABYLON = {}));
  64873. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64874. var BABYLON;
  64875. (function (BABYLON) {
  64876. var ViveController = /** @class */ (function (_super) {
  64877. __extends(ViveController, _super);
  64878. function ViveController(vrGamepad) {
  64879. var _this = _super.call(this, vrGamepad) || this;
  64880. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64881. _this._invertLeftStickY = true;
  64882. return _this;
  64883. }
  64884. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64885. var _this = this;
  64886. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64887. /*
  64888. Parent Mesh name: ViveWand
  64889. - body
  64890. - r_gripper
  64891. - l_gripper
  64892. - menu_button
  64893. - system_button
  64894. - trackpad
  64895. - trigger
  64896. - LED
  64897. */
  64898. _this._defaultModel = newMeshes[1];
  64899. _this.attachToMesh(_this._defaultModel);
  64900. if (meshLoaded) {
  64901. meshLoaded(_this._defaultModel);
  64902. }
  64903. });
  64904. };
  64905. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64906. get: function () {
  64907. return this.onMainButtonStateChangedObservable;
  64908. },
  64909. enumerable: true,
  64910. configurable: true
  64911. });
  64912. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64913. get: function () {
  64914. return this.onMainButtonStateChangedObservable;
  64915. },
  64916. enumerable: true,
  64917. configurable: true
  64918. });
  64919. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64920. get: function () {
  64921. return this.onSecondaryButtonStateChangedObservable;
  64922. },
  64923. enumerable: true,
  64924. configurable: true
  64925. });
  64926. /**
  64927. * Vive mapping:
  64928. * 0: touchpad
  64929. * 1: trigger
  64930. * 2: left AND right buttons
  64931. * 3: menu button
  64932. */
  64933. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64934. var notifyObject = state; //{ state: state, changes: changes };
  64935. switch (buttonIdx) {
  64936. case 0:
  64937. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64938. return;
  64939. case 1:// index trigger
  64940. if (this._defaultModel) {
  64941. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64942. }
  64943. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64944. return;
  64945. case 2:// left AND right button
  64946. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64947. return;
  64948. case 3:
  64949. if (this._defaultModel) {
  64950. if (notifyObject.pressed) {
  64951. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64952. }
  64953. else {
  64954. (this._defaultModel.getChildren()[2]).position.y = 0;
  64955. }
  64956. }
  64957. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64958. return;
  64959. }
  64960. };
  64961. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64962. ViveController.MODEL_FILENAME = 'wand.babylon';
  64963. return ViveController;
  64964. }(BABYLON.WebVRController));
  64965. BABYLON.ViveController = ViveController;
  64966. })(BABYLON || (BABYLON = {}));
  64967. //# sourceMappingURL=babylon.viveController.js.map
  64968. var BABYLON;
  64969. (function (BABYLON) {
  64970. var GenericController = /** @class */ (function (_super) {
  64971. __extends(GenericController, _super);
  64972. function GenericController(vrGamepad) {
  64973. return _super.call(this, vrGamepad) || this;
  64974. }
  64975. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64976. var _this = this;
  64977. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64978. _this._defaultModel = newMeshes[1];
  64979. _this.attachToMesh(_this._defaultModel);
  64980. if (meshLoaded) {
  64981. meshLoaded(_this._defaultModel);
  64982. }
  64983. });
  64984. };
  64985. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64986. console.log("Button id: " + buttonIdx + "state: ");
  64987. console.dir(state);
  64988. };
  64989. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64990. GenericController.MODEL_FILENAME = 'generic.babylon';
  64991. return GenericController;
  64992. }(BABYLON.WebVRController));
  64993. BABYLON.GenericController = GenericController;
  64994. })(BABYLON || (BABYLON = {}));
  64995. //# sourceMappingURL=babylon.genericController.js.map
  64996. var BABYLON;
  64997. (function (BABYLON) {
  64998. var LoadedMeshInfo = /** @class */ (function () {
  64999. function LoadedMeshInfo() {
  65000. this.buttonMeshes = {};
  65001. this.axisMeshes = {};
  65002. }
  65003. return LoadedMeshInfo;
  65004. }());
  65005. var WindowsMotionController = /** @class */ (function (_super) {
  65006. __extends(WindowsMotionController, _super);
  65007. function WindowsMotionController(vrGamepad) {
  65008. var _this = _super.call(this, vrGamepad) || this;
  65009. _this._mapping = {
  65010. // Semantic button names
  65011. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65012. // A mapping of the button name to glTF model node name
  65013. // that should be transformed by button value.
  65014. buttonMeshNames: {
  65015. 'trigger': 'SELECT',
  65016. 'menu': 'MENU',
  65017. 'grip': 'GRASP',
  65018. 'thumbstick': 'THUMBSTICK_PRESS',
  65019. 'trackpad': 'TOUCHPAD_PRESS'
  65020. },
  65021. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65022. buttonObservableNames: {
  65023. 'trigger': 'onTriggerStateChangedObservable',
  65024. 'menu': 'onSecondaryButtonStateChangedObservable',
  65025. 'grip': 'onMainButtonStateChangedObservable',
  65026. 'thumbstick': 'onPadStateChangedObservable',
  65027. 'trackpad': 'onTrackpadChangedObservable'
  65028. },
  65029. // A mapping of the axis name to glTF model node name
  65030. // that should be transformed by axis value.
  65031. // This array mirrors the browserGamepad.axes array, such that
  65032. // the mesh corresponding to axis 0 is in this array index 0.
  65033. axisMeshNames: [
  65034. 'THUMBSTICK_X',
  65035. 'THUMBSTICK_Y',
  65036. 'TOUCHPAD_TOUCH_X',
  65037. 'TOUCHPAD_TOUCH_Y'
  65038. ],
  65039. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65040. };
  65041. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65042. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65043. _this.trackpad = { x: 0, y: 0 };
  65044. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65045. _this._loadedMeshInfo = null;
  65046. return _this;
  65047. }
  65048. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65049. get: function () {
  65050. return this.onTriggerStateChangedObservable;
  65051. },
  65052. enumerable: true,
  65053. configurable: true
  65054. });
  65055. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65056. get: function () {
  65057. return this.onSecondaryButtonStateChangedObservable;
  65058. },
  65059. enumerable: true,
  65060. configurable: true
  65061. });
  65062. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65063. get: function () {
  65064. return this.onMainButtonStateChangedObservable;
  65065. },
  65066. enumerable: true,
  65067. configurable: true
  65068. });
  65069. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65070. get: function () {
  65071. return this.onPadStateChangedObservable;
  65072. },
  65073. enumerable: true,
  65074. configurable: true
  65075. });
  65076. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65077. get: function () {
  65078. return this.onTrackpadChangedObservable;
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65084. get: function () {
  65085. return this.onTrackpadValuesChangedObservable;
  65086. },
  65087. enumerable: true,
  65088. configurable: true
  65089. });
  65090. /**
  65091. * Called once per frame by the engine.
  65092. */
  65093. WindowsMotionController.prototype.update = function () {
  65094. _super.prototype.update.call(this);
  65095. if (this.browserGamepad.axes) {
  65096. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65097. this.trackpad.x = this.browserGamepad["axes"][2];
  65098. this.trackpad.y = this.browserGamepad["axes"][3];
  65099. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65100. }
  65101. // Only need to animate axes if there is a loaded mesh
  65102. if (this._loadedMeshInfo) {
  65103. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65104. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65105. }
  65106. }
  65107. }
  65108. };
  65109. /**
  65110. * Called once for each button that changed state since the last frame
  65111. * @param buttonIdx Which button index changed
  65112. * @param state New state of the button
  65113. * @param changes Which properties on the state changed since last frame
  65114. */
  65115. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65116. var buttonName = this._mapping.buttons[buttonIdx];
  65117. if (!buttonName) {
  65118. return;
  65119. }
  65120. // Only emit events for buttons that we know how to map from index to name
  65121. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65122. if (observable) {
  65123. observable.notifyObservers(state);
  65124. }
  65125. this.lerpButtonTransform(buttonName, state.value);
  65126. };
  65127. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65128. // If there is no loaded mesh, there is nothing to transform.
  65129. if (!this._loadedMeshInfo) {
  65130. return;
  65131. }
  65132. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65133. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65134. return;
  65135. }
  65136. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65137. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65138. };
  65139. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65140. if (!this._loadedMeshInfo) {
  65141. return;
  65142. }
  65143. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65144. if (!meshInfo) {
  65145. return;
  65146. }
  65147. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65148. return;
  65149. }
  65150. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65151. var lerpValue = axisValue * 0.5 + 0.5;
  65152. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65153. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65154. };
  65155. /**
  65156. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65157. * @param scene scene in which to add meshes
  65158. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65159. */
  65160. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65161. var _this = this;
  65162. if (forceDefault === void 0) { forceDefault = false; }
  65163. var path;
  65164. var filename;
  65165. // Checking if GLB loader is present
  65166. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65167. // Determine the device specific folder based on the ID suffix
  65168. var device = 'default';
  65169. if (this.id && !forceDefault) {
  65170. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65171. device = ((match && match[0]) || device);
  65172. }
  65173. // Hand
  65174. if (this.hand === 'left') {
  65175. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65176. }
  65177. else {
  65178. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65179. }
  65180. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65181. }
  65182. else {
  65183. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65184. path = BABYLON.GenericController.MODEL_BASE_URL;
  65185. filename = BABYLON.GenericController.MODEL_FILENAME;
  65186. }
  65187. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65188. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65189. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65190. if (!_this._loadedMeshInfo) {
  65191. return;
  65192. }
  65193. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65194. _this.attachToMesh(_this._defaultModel);
  65195. if (meshLoaded) {
  65196. meshLoaded(_this._defaultModel);
  65197. }
  65198. }, null, function (scene, message) {
  65199. BABYLON.Tools.Log(message);
  65200. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65201. if (!forceDefault) {
  65202. _this.initControllerMesh(scene, meshLoaded, true);
  65203. }
  65204. });
  65205. };
  65206. /**
  65207. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65208. * can be transformed by button presses and axes values, based on this._mapping.
  65209. *
  65210. * @param scene scene in which the meshes exist
  65211. * @param meshes list of meshes that make up the controller model to process
  65212. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65213. */
  65214. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65215. var loadedMeshInfo = null;
  65216. // Create a new mesh to contain the glTF hierarchy
  65217. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65218. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65219. var childMesh = null;
  65220. for (var i = 0; i < meshes.length; i++) {
  65221. var mesh = meshes[i];
  65222. if (!mesh.parent) {
  65223. // Exclude controller meshes from picking results
  65224. mesh.isPickable = false;
  65225. // Handle root node, attach to the new parentMesh
  65226. childMesh = mesh;
  65227. break;
  65228. }
  65229. }
  65230. if (childMesh) {
  65231. childMesh.setParent(parentMesh);
  65232. // Create our mesh info. Note that this method will always return non-null.
  65233. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65234. }
  65235. else {
  65236. BABYLON.Tools.Warn('Could not find root node in model file.');
  65237. }
  65238. return loadedMeshInfo;
  65239. };
  65240. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65241. var loadedMeshInfo = new LoadedMeshInfo();
  65242. var i;
  65243. loadedMeshInfo.rootNode = rootNode;
  65244. // Reset the caches
  65245. loadedMeshInfo.buttonMeshes = {};
  65246. loadedMeshInfo.axisMeshes = {};
  65247. // Button Meshes
  65248. for (i = 0; i < this._mapping.buttons.length; i++) {
  65249. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65250. if (!buttonMeshName) {
  65251. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65252. continue;
  65253. }
  65254. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65255. if (!buttonMesh) {
  65256. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65257. continue;
  65258. }
  65259. var buttonMeshInfo = {
  65260. index: i,
  65261. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65262. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65263. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65264. };
  65265. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65266. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65267. }
  65268. else {
  65269. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65270. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65271. '(VALUE: ' + !!buttonMeshInfo.value +
  65272. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65273. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65274. ')');
  65275. }
  65276. }
  65277. // Axis Meshes
  65278. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65279. var axisMeshName = this._mapping.axisMeshNames[i];
  65280. if (!axisMeshName) {
  65281. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65282. continue;
  65283. }
  65284. var axisMesh = getChildByName(rootNode, axisMeshName);
  65285. if (!axisMesh) {
  65286. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65287. continue;
  65288. }
  65289. var axisMeshInfo = {
  65290. index: i,
  65291. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65292. min: getImmediateChildByName(axisMesh, 'MIN'),
  65293. max: getImmediateChildByName(axisMesh, 'MAX')
  65294. };
  65295. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65296. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65297. }
  65298. else {
  65299. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65300. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65301. '(VALUE: ' + !!axisMeshInfo.value +
  65302. ', MIN: ' + !!axisMeshInfo.min +
  65303. ', MAX:' + !!axisMeshInfo.max +
  65304. ')');
  65305. }
  65306. }
  65307. // Pointing Ray
  65308. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65309. if (!loadedMeshInfo.pointingPoseNode) {
  65310. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65311. }
  65312. return loadedMeshInfo;
  65313. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65314. function getChildByName(node, name) {
  65315. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65316. }
  65317. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65318. function getImmediateChildByName(node, name) {
  65319. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65320. }
  65321. };
  65322. WindowsMotionController.prototype.getForwardRay = function (length) {
  65323. if (length === void 0) { length = 100; }
  65324. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65325. return _super.prototype.getForwardRay.call(this, length);
  65326. }
  65327. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65328. var origin = m.getTranslation();
  65329. var forward = new BABYLON.Vector3(0, 0, -1);
  65330. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65331. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65332. return new BABYLON.Ray(origin, direction, length);
  65333. };
  65334. WindowsMotionController.prototype.dispose = function () {
  65335. _super.prototype.dispose.call(this);
  65336. this.onTrackpadChangedObservable.clear();
  65337. };
  65338. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65339. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65340. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65341. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65342. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65343. return WindowsMotionController;
  65344. }(BABYLON.WebVRController));
  65345. BABYLON.WindowsMotionController = WindowsMotionController;
  65346. })(BABYLON || (BABYLON = {}));
  65347. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65348. var BABYLON;
  65349. (function (BABYLON) {
  65350. var GearVRController = /** @class */ (function (_super) {
  65351. __extends(GearVRController, _super);
  65352. function GearVRController(vrGamepad) {
  65353. var _this = _super.call(this, vrGamepad) || this;
  65354. _this._buttonIndexToObservableNameMap = [
  65355. 'onTrackpadChangedObservable',
  65356. 'onTriggerStateChangedObservable' // Trigger
  65357. ];
  65358. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65359. return _this;
  65360. }
  65361. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65362. var _this = this;
  65363. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65364. _this._defaultModel = newMeshes[1];
  65365. _this.attachToMesh(_this._defaultModel);
  65366. if (meshLoaded) {
  65367. meshLoaded(_this._defaultModel);
  65368. }
  65369. });
  65370. };
  65371. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65372. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65373. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65374. // Only emit events for buttons that we know how to map from index to observable
  65375. var observable = this[observableName];
  65376. if (observable) {
  65377. observable.notifyObservers(state);
  65378. }
  65379. }
  65380. };
  65381. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65382. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65383. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65384. return GearVRController;
  65385. }(BABYLON.WebVRController));
  65386. BABYLON.GearVRController = GearVRController;
  65387. })(BABYLON || (BABYLON = {}));
  65388. //# sourceMappingURL=babylon.gearVRController.js.map
  65389. var BABYLON;
  65390. (function (BABYLON) {
  65391. /**
  65392. * Google Daydream controller
  65393. */
  65394. var DaydreamController = /** @class */ (function (_super) {
  65395. __extends(DaydreamController, _super);
  65396. function DaydreamController(vrGamepad) {
  65397. var _this = _super.call(this, vrGamepad) || this;
  65398. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65399. return _this;
  65400. }
  65401. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65402. var _this = this;
  65403. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65404. _this._defaultModel = newMeshes[1];
  65405. _this.attachToMesh(_this._defaultModel);
  65406. if (meshLoaded) {
  65407. meshLoaded(_this._defaultModel);
  65408. }
  65409. });
  65410. };
  65411. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65412. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65413. if (buttonIdx === 0) {
  65414. var observable = this.onTriggerStateChangedObservable;
  65415. if (observable) {
  65416. observable.notifyObservers(state);
  65417. }
  65418. }
  65419. else {
  65420. // If the app or home buttons are ever made available
  65421. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65422. }
  65423. };
  65424. /**
  65425. * Base Url for the controller model.
  65426. */
  65427. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65428. /**
  65429. * File name for the controller model.
  65430. */
  65431. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65432. /**
  65433. * Gamepad Id prefix used to identify Daydream Controller.
  65434. */
  65435. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65436. return DaydreamController;
  65437. }(BABYLON.WebVRController));
  65438. BABYLON.DaydreamController = DaydreamController;
  65439. })(BABYLON || (BABYLON = {}));
  65440. //# sourceMappingURL=babylon.daydreamController.js.map
  65441. var BABYLON;
  65442. (function (BABYLON) {
  65443. var FollowCamera = /** @class */ (function (_super) {
  65444. __extends(FollowCamera, _super);
  65445. function FollowCamera(name, position, scene, lockedTarget) {
  65446. if (lockedTarget === void 0) { lockedTarget = null; }
  65447. var _this = _super.call(this, name, position, scene) || this;
  65448. _this.radius = 12;
  65449. _this.rotationOffset = 0;
  65450. _this.heightOffset = 4;
  65451. _this.cameraAcceleration = 0.05;
  65452. _this.maxCameraSpeed = 20;
  65453. _this.lockedTarget = lockedTarget;
  65454. return _this;
  65455. }
  65456. FollowCamera.prototype.getRadians = function (degrees) {
  65457. return degrees * Math.PI / 180;
  65458. };
  65459. FollowCamera.prototype.follow = function (cameraTarget) {
  65460. if (!cameraTarget)
  65461. return;
  65462. var yRotation;
  65463. if (cameraTarget.rotationQuaternion) {
  65464. var rotMatrix = new BABYLON.Matrix();
  65465. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65466. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65467. }
  65468. else {
  65469. yRotation = cameraTarget.rotation.y;
  65470. }
  65471. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65472. var targetPosition = cameraTarget.getAbsolutePosition();
  65473. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65474. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65475. var dx = targetX - this.position.x;
  65476. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65477. var dz = (targetZ) - this.position.z;
  65478. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65479. var vy = dy * this.cameraAcceleration;
  65480. var vz = dz * this.cameraAcceleration * 2;
  65481. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65482. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65483. }
  65484. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65485. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65486. }
  65487. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65488. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65489. }
  65490. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65491. this.setTarget(targetPosition);
  65492. };
  65493. FollowCamera.prototype._checkInputs = function () {
  65494. _super.prototype._checkInputs.call(this);
  65495. if (this.lockedTarget) {
  65496. this.follow(this.lockedTarget);
  65497. }
  65498. };
  65499. FollowCamera.prototype.getClassName = function () {
  65500. return "FollowCamera";
  65501. };
  65502. __decorate([
  65503. BABYLON.serialize()
  65504. ], FollowCamera.prototype, "radius", void 0);
  65505. __decorate([
  65506. BABYLON.serialize()
  65507. ], FollowCamera.prototype, "rotationOffset", void 0);
  65508. __decorate([
  65509. BABYLON.serialize()
  65510. ], FollowCamera.prototype, "heightOffset", void 0);
  65511. __decorate([
  65512. BABYLON.serialize()
  65513. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65514. __decorate([
  65515. BABYLON.serialize()
  65516. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65517. __decorate([
  65518. BABYLON.serializeAsMeshReference("lockedTargetId")
  65519. ], FollowCamera.prototype, "lockedTarget", void 0);
  65520. return FollowCamera;
  65521. }(BABYLON.TargetCamera));
  65522. BABYLON.FollowCamera = FollowCamera;
  65523. var ArcFollowCamera = /** @class */ (function (_super) {
  65524. __extends(ArcFollowCamera, _super);
  65525. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65526. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65527. _this.alpha = alpha;
  65528. _this.beta = beta;
  65529. _this.radius = radius;
  65530. _this.target = target;
  65531. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65532. _this.follow();
  65533. return _this;
  65534. }
  65535. ArcFollowCamera.prototype.follow = function () {
  65536. if (!this.target) {
  65537. return;
  65538. }
  65539. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65540. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65541. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65542. var targetPosition = this.target.getAbsolutePosition();
  65543. this.position = targetPosition.add(this._cartesianCoordinates);
  65544. this.setTarget(targetPosition);
  65545. };
  65546. ArcFollowCamera.prototype._checkInputs = function () {
  65547. _super.prototype._checkInputs.call(this);
  65548. this.follow();
  65549. };
  65550. ArcFollowCamera.prototype.getClassName = function () {
  65551. return "ArcFollowCamera";
  65552. };
  65553. return ArcFollowCamera;
  65554. }(BABYLON.TargetCamera));
  65555. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65556. })(BABYLON || (BABYLON = {}));
  65557. //# sourceMappingURL=babylon.followCamera.js.map
  65558. var BABYLON;
  65559. (function (BABYLON) {
  65560. // We're mainly based on the logic defined into the FreeCamera code
  65561. var UniversalCamera = /** @class */ (function (_super) {
  65562. __extends(UniversalCamera, _super);
  65563. //-- end properties for backward compatibility for inputs
  65564. function UniversalCamera(name, position, scene) {
  65565. var _this = _super.call(this, name, position, scene) || this;
  65566. _this.inputs.addGamepad();
  65567. return _this;
  65568. }
  65569. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65570. //-- Begin properties for backward compatibility for inputs
  65571. get: function () {
  65572. var gamepad = this.inputs.attached["gamepad"];
  65573. if (gamepad)
  65574. return gamepad.gamepadAngularSensibility;
  65575. return 0;
  65576. },
  65577. set: function (value) {
  65578. var gamepad = this.inputs.attached["gamepad"];
  65579. if (gamepad)
  65580. gamepad.gamepadAngularSensibility = value;
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65586. get: function () {
  65587. var gamepad = this.inputs.attached["gamepad"];
  65588. if (gamepad)
  65589. return gamepad.gamepadMoveSensibility;
  65590. return 0;
  65591. },
  65592. set: function (value) {
  65593. var gamepad = this.inputs.attached["gamepad"];
  65594. if (gamepad)
  65595. gamepad.gamepadMoveSensibility = value;
  65596. },
  65597. enumerable: true,
  65598. configurable: true
  65599. });
  65600. UniversalCamera.prototype.getClassName = function () {
  65601. return "UniversalCamera";
  65602. };
  65603. return UniversalCamera;
  65604. }(BABYLON.TouchCamera));
  65605. BABYLON.UniversalCamera = UniversalCamera;
  65606. })(BABYLON || (BABYLON = {}));
  65607. //# sourceMappingURL=babylon.universalCamera.js.map
  65608. var BABYLON;
  65609. (function (BABYLON) {
  65610. // We're mainly based on the logic defined into the FreeCamera code
  65611. var GamepadCamera = /** @class */ (function (_super) {
  65612. __extends(GamepadCamera, _super);
  65613. //-- end properties for backward compatibility for inputs
  65614. function GamepadCamera(name, position, scene) {
  65615. return _super.call(this, name, position, scene) || this;
  65616. }
  65617. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65618. //-- Begin properties for backward compatibility for inputs
  65619. get: function () {
  65620. var gamepad = this.inputs.attached["gamepad"];
  65621. if (gamepad)
  65622. return gamepad.gamepadAngularSensibility;
  65623. return 0;
  65624. },
  65625. set: function (value) {
  65626. var gamepad = this.inputs.attached["gamepad"];
  65627. if (gamepad)
  65628. gamepad.gamepadAngularSensibility = value;
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65634. get: function () {
  65635. var gamepad = this.inputs.attached["gamepad"];
  65636. if (gamepad)
  65637. return gamepad.gamepadMoveSensibility;
  65638. return 0;
  65639. },
  65640. set: function (value) {
  65641. var gamepad = this.inputs.attached["gamepad"];
  65642. if (gamepad)
  65643. gamepad.gamepadMoveSensibility = value;
  65644. },
  65645. enumerable: true,
  65646. configurable: true
  65647. });
  65648. GamepadCamera.prototype.getClassName = function () {
  65649. return "GamepadCamera";
  65650. };
  65651. return GamepadCamera;
  65652. }(BABYLON.UniversalCamera));
  65653. BABYLON.GamepadCamera = GamepadCamera;
  65654. })(BABYLON || (BABYLON = {}));
  65655. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65656. var BABYLON;
  65657. (function (BABYLON) {
  65658. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65659. function PostProcessRenderPipelineManager() {
  65660. this._renderPipelines = {};
  65661. }
  65662. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65663. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65664. };
  65665. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65666. if (unique === void 0) { unique = false; }
  65667. var renderPipeline = this._renderPipelines[renderPipelineName];
  65668. if (!renderPipeline) {
  65669. return;
  65670. }
  65671. renderPipeline._attachCameras(cameras, unique);
  65672. };
  65673. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65674. var renderPipeline = this._renderPipelines[renderPipelineName];
  65675. if (!renderPipeline) {
  65676. return;
  65677. }
  65678. renderPipeline._detachCameras(cameras);
  65679. };
  65680. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65681. var renderPipeline = this._renderPipelines[renderPipelineName];
  65682. if (!renderPipeline) {
  65683. return;
  65684. }
  65685. renderPipeline._enableEffect(renderEffectName, cameras);
  65686. };
  65687. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65688. var renderPipeline = this._renderPipelines[renderPipelineName];
  65689. if (!renderPipeline) {
  65690. return;
  65691. }
  65692. renderPipeline._disableEffect(renderEffectName, cameras);
  65693. };
  65694. PostProcessRenderPipelineManager.prototype.update = function () {
  65695. for (var renderPipelineName in this._renderPipelines) {
  65696. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65697. var pipeline = this._renderPipelines[renderPipelineName];
  65698. if (!pipeline.isSupported) {
  65699. pipeline.dispose();
  65700. delete this._renderPipelines[renderPipelineName];
  65701. }
  65702. else {
  65703. pipeline._update();
  65704. }
  65705. }
  65706. }
  65707. };
  65708. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65709. for (var renderPipelineName in this._renderPipelines) {
  65710. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65711. var pipeline = this._renderPipelines[renderPipelineName];
  65712. pipeline._rebuild();
  65713. }
  65714. }
  65715. };
  65716. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65717. for (var renderPipelineName in this._renderPipelines) {
  65718. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65719. var pipeline = this._renderPipelines[renderPipelineName];
  65720. pipeline.dispose();
  65721. }
  65722. }
  65723. };
  65724. return PostProcessRenderPipelineManager;
  65725. }());
  65726. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65727. })(BABYLON || (BABYLON = {}));
  65728. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65729. var BABYLON;
  65730. (function (BABYLON) {
  65731. /**
  65732. * This represents a set of one or more post processes in Babylon.
  65733. * A post process can be used to apply a shader to a texture after it is rendered.
  65734. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65735. */
  65736. var PostProcessRenderEffect = /** @class */ (function () {
  65737. /**
  65738. * Instantiates a post process render effect.
  65739. * A post process can be used to apply a shader to a texture after it is rendered.
  65740. * @param engine The engine the effect is tied to
  65741. * @param name The name of the effect
  65742. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65743. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65744. */
  65745. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65746. this._name = name;
  65747. this._singleInstance = singleInstance || true;
  65748. this._getPostProcesses = getPostProcesses;
  65749. this._cameras = {};
  65750. this._indicesForCamera = {};
  65751. this._postProcesses = {};
  65752. }
  65753. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65754. /**
  65755. * Checks if all the post processes in the effect are supported.
  65756. */
  65757. get: function () {
  65758. for (var index in this._postProcesses) {
  65759. for (var ppIndex in this._postProcesses[index]) {
  65760. if (!this._postProcesses[index][ppIndex].isSupported) {
  65761. return false;
  65762. }
  65763. }
  65764. }
  65765. return true;
  65766. },
  65767. enumerable: true,
  65768. configurable: true
  65769. });
  65770. /**
  65771. * Updates the current state of the effect
  65772. */
  65773. PostProcessRenderEffect.prototype._update = function () {
  65774. };
  65775. /**
  65776. * Attaches the effect on cameras
  65777. * @param cameras The camera to attach to.
  65778. */
  65779. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65780. var _this = this;
  65781. var cameraKey;
  65782. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65783. if (!cams) {
  65784. return;
  65785. }
  65786. for (var i = 0; i < cams.length; i++) {
  65787. var camera = cams[i];
  65788. var cameraName = camera.name;
  65789. if (this._singleInstance) {
  65790. cameraKey = 0;
  65791. }
  65792. else {
  65793. cameraKey = cameraName;
  65794. }
  65795. if (!this._postProcesses[cameraKey]) {
  65796. var postProcess = this._getPostProcesses();
  65797. if (postProcess) {
  65798. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65799. }
  65800. }
  65801. if (!this._indicesForCamera[cameraName]) {
  65802. this._indicesForCamera[cameraName] = [];
  65803. }
  65804. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65805. var index = camera.attachPostProcess(postProcess);
  65806. _this._indicesForCamera[cameraName].push(index);
  65807. });
  65808. if (!this._cameras[cameraName]) {
  65809. this._cameras[cameraName] = camera;
  65810. }
  65811. }
  65812. };
  65813. /**
  65814. * Detatches the effect on cameras
  65815. * @param cameras The camera to detatch from.
  65816. */
  65817. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65818. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65819. if (!cams) {
  65820. return;
  65821. }
  65822. for (var i = 0; i < cams.length; i++) {
  65823. var camera = cams[i];
  65824. var cameraName = camera.name;
  65825. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65826. camera.detachPostProcess(postProcess);
  65827. });
  65828. if (this._cameras[cameraName]) {
  65829. //this._indicesForCamera.splice(index, 1);
  65830. this._cameras[cameraName] = null;
  65831. }
  65832. }
  65833. };
  65834. /**
  65835. * Enables the effect on given cameras
  65836. * @param cameras The camera to enable.
  65837. */
  65838. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65839. var _this = this;
  65840. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65841. if (!cams) {
  65842. return;
  65843. }
  65844. for (var i = 0; i < cams.length; i++) {
  65845. var camera = cams[i];
  65846. var cameraName = camera.name;
  65847. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65848. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65849. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65850. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65851. });
  65852. }
  65853. }
  65854. }
  65855. };
  65856. /**
  65857. * Disables the effect on the given cameras
  65858. * @param cameras The camera to disable.
  65859. */
  65860. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65861. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65862. if (!cams) {
  65863. return;
  65864. }
  65865. for (var i = 0; i < cams.length; i++) {
  65866. var camera = cams[i];
  65867. var cameraName = camera.name;
  65868. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65869. camera.detachPostProcess(postProcess);
  65870. });
  65871. }
  65872. };
  65873. /**
  65874. * Gets a list of the post processes contained in the effect.
  65875. * @param camera The camera to get the post processes on.
  65876. * @returns The list of the post processes in the effect.
  65877. */
  65878. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65879. if (this._singleInstance) {
  65880. return this._postProcesses[0];
  65881. }
  65882. else {
  65883. if (!camera) {
  65884. return null;
  65885. }
  65886. return this._postProcesses[camera.name];
  65887. }
  65888. };
  65889. return PostProcessRenderEffect;
  65890. }());
  65891. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65892. })(BABYLON || (BABYLON = {}));
  65893. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65894. var BABYLON;
  65895. (function (BABYLON) {
  65896. var PostProcessRenderPipeline = /** @class */ (function () {
  65897. function PostProcessRenderPipeline(engine, name) {
  65898. this.engine = engine;
  65899. this._name = name;
  65900. this._renderEffects = {};
  65901. this._renderEffectsForIsolatedPass = new Array();
  65902. this._cameras = [];
  65903. }
  65904. PostProcessRenderPipeline.prototype.getClassName = function () {
  65905. return "PostProcessRenderPipeline";
  65906. };
  65907. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65908. get: function () {
  65909. for (var renderEffectName in this._renderEffects) {
  65910. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65911. if (!this._renderEffects[renderEffectName].isSupported) {
  65912. return false;
  65913. }
  65914. }
  65915. }
  65916. return true;
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65922. this._renderEffects[renderEffect._name] = renderEffect;
  65923. };
  65924. // private
  65925. PostProcessRenderPipeline.prototype._rebuild = function () {
  65926. };
  65927. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65928. var renderEffects = this._renderEffects[renderEffectName];
  65929. if (!renderEffects) {
  65930. return;
  65931. }
  65932. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65933. };
  65934. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65935. var renderEffects = this._renderEffects[renderEffectName];
  65936. if (!renderEffects) {
  65937. return;
  65938. }
  65939. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65940. };
  65941. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65942. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65943. if (!cams) {
  65944. return;
  65945. }
  65946. var indicesToDelete = [];
  65947. var i;
  65948. for (i = 0; i < cams.length; i++) {
  65949. var camera = cams[i];
  65950. var cameraName = camera.name;
  65951. if (this._cameras.indexOf(camera) === -1) {
  65952. this._cameras[cameraName] = camera;
  65953. }
  65954. else if (unique) {
  65955. indicesToDelete.push(i);
  65956. }
  65957. }
  65958. for (i = 0; i < indicesToDelete.length; i++) {
  65959. cameras.splice(indicesToDelete[i], 1);
  65960. }
  65961. for (var renderEffectName in this._renderEffects) {
  65962. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65963. this._renderEffects[renderEffectName]._attachCameras(cams);
  65964. }
  65965. }
  65966. };
  65967. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65968. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65969. if (!cams) {
  65970. return;
  65971. }
  65972. for (var renderEffectName in this._renderEffects) {
  65973. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65974. this._renderEffects[renderEffectName]._detachCameras(cams);
  65975. }
  65976. }
  65977. for (var i = 0; i < cams.length; i++) {
  65978. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65979. }
  65980. };
  65981. PostProcessRenderPipeline.prototype._update = function () {
  65982. for (var renderEffectName in this._renderEffects) {
  65983. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65984. this._renderEffects[renderEffectName]._update();
  65985. }
  65986. }
  65987. for (var i = 0; i < this._cameras.length; i++) {
  65988. var cameraName = this._cameras[i].name;
  65989. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65990. this._renderEffectsForIsolatedPass[cameraName]._update();
  65991. }
  65992. }
  65993. };
  65994. PostProcessRenderPipeline.prototype._reset = function () {
  65995. this._renderEffects = {};
  65996. this._renderEffectsForIsolatedPass = new Array();
  65997. };
  65998. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65999. // 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)
  66000. var effectKeys = Object.keys(this._renderEffects);
  66001. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66002. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66003. if (postProcesses) {
  66004. postProcesses[0].samples = 4;
  66005. return true;
  66006. }
  66007. }
  66008. return false;
  66009. };
  66010. PostProcessRenderPipeline.prototype.dispose = function () {
  66011. // Must be implemented by children
  66012. };
  66013. __decorate([
  66014. BABYLON.serialize()
  66015. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66016. return PostProcessRenderPipeline;
  66017. }());
  66018. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66019. })(BABYLON || (BABYLON = {}));
  66020. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66021. var BABYLON;
  66022. (function (BABYLON) {
  66023. /**
  66024. * This represents a depth renderer in Babylon.
  66025. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66026. */
  66027. var DepthRenderer = /** @class */ (function () {
  66028. /**
  66029. * Instantiates a depth renderer
  66030. * @param scene The scene the renderer belongs to
  66031. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66032. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66033. */
  66034. function DepthRenderer(scene, type, camera) {
  66035. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66036. if (camera === void 0) { camera = null; }
  66037. var _this = this;
  66038. this._scene = scene;
  66039. this._camera = camera;
  66040. var engine = scene.getEngine();
  66041. // Render target
  66042. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66043. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66044. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66045. this._depthMap.refreshRate = 1;
  66046. this._depthMap.renderParticles = false;
  66047. this._depthMap.renderList = null;
  66048. // Camera to get depth map from to support multiple concurrent cameras
  66049. this._depthMap.activeCamera = this._camera;
  66050. this._depthMap.ignoreCameraViewport = true;
  66051. this._depthMap.useCameraPostProcesses = false;
  66052. // set default depth value to 1.0 (far away)
  66053. this._depthMap.onClearObservable.add(function (engine) {
  66054. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66055. });
  66056. // Custom render function
  66057. var renderSubMesh = function (subMesh) {
  66058. var mesh = subMesh.getRenderingMesh();
  66059. var scene = _this._scene;
  66060. var engine = scene.getEngine();
  66061. var material = subMesh.getMaterial();
  66062. if (!material) {
  66063. return;
  66064. }
  66065. // Culling and reverse (right handed system)
  66066. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66067. // Managing instances
  66068. var batch = mesh._getInstancesRenderList(subMesh._id);
  66069. if (batch.mustReturn) {
  66070. return;
  66071. }
  66072. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66073. var camera = _this._camera || scene.activeCamera;
  66074. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66075. engine.enableEffect(_this._effect);
  66076. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66077. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66078. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66079. // Alpha test
  66080. if (material && material.needAlphaTesting()) {
  66081. var alphaTexture = material.getAlphaTestTexture();
  66082. if (alphaTexture) {
  66083. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66084. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66085. }
  66086. }
  66087. // Bones
  66088. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66089. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66090. }
  66091. // Draw
  66092. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66093. }
  66094. };
  66095. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66096. var index;
  66097. if (depthOnlySubMeshes.length) {
  66098. engine.setColorWrite(false);
  66099. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66100. renderSubMesh(depthOnlySubMeshes.data[index]);
  66101. }
  66102. engine.setColorWrite(true);
  66103. }
  66104. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66105. renderSubMesh(opaqueSubMeshes.data[index]);
  66106. }
  66107. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66108. renderSubMesh(alphaTestSubMeshes.data[index]);
  66109. }
  66110. };
  66111. }
  66112. /**
  66113. * Creates the depth rendering effect and checks if the effect is ready.
  66114. * @param subMesh The submesh to be used to render the depth map of
  66115. * @param useInstances If multiple world instances should be used
  66116. * @returns if the depth renderer is ready to render the depth map
  66117. */
  66118. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66119. var material = subMesh.getMaterial();
  66120. if (material.disableDepthWrite) {
  66121. return false;
  66122. }
  66123. var defines = [];
  66124. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66125. var mesh = subMesh.getMesh();
  66126. // Alpha test
  66127. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66128. defines.push("#define ALPHATEST");
  66129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66130. attribs.push(BABYLON.VertexBuffer.UVKind);
  66131. defines.push("#define UV1");
  66132. }
  66133. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66134. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66135. defines.push("#define UV2");
  66136. }
  66137. }
  66138. // Bones
  66139. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66142. if (mesh.numBoneInfluencers > 4) {
  66143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66145. }
  66146. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66147. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66148. }
  66149. else {
  66150. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66151. }
  66152. // Instances
  66153. if (useInstances) {
  66154. defines.push("#define INSTANCES");
  66155. attribs.push("world0");
  66156. attribs.push("world1");
  66157. attribs.push("world2");
  66158. attribs.push("world3");
  66159. }
  66160. // Get correct effect
  66161. var join = defines.join("\n");
  66162. if (this._cachedDefines !== join) {
  66163. this._cachedDefines = join;
  66164. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66165. }
  66166. return this._effect.isReady();
  66167. };
  66168. /**
  66169. * Gets the texture which the depth map will be written to.
  66170. * @returns The depth map texture
  66171. */
  66172. DepthRenderer.prototype.getDepthMap = function () {
  66173. return this._depthMap;
  66174. };
  66175. /**
  66176. * Disposes of the depth renderer.
  66177. */
  66178. DepthRenderer.prototype.dispose = function () {
  66179. this._depthMap.dispose();
  66180. };
  66181. return DepthRenderer;
  66182. }());
  66183. BABYLON.DepthRenderer = DepthRenderer;
  66184. })(BABYLON || (BABYLON = {}));
  66185. //# sourceMappingURL=babylon.depthRenderer.js.map
  66186. var BABYLON;
  66187. (function (BABYLON) {
  66188. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66189. __extends(SSAORenderingPipeline, _super);
  66190. /**
  66191. * @constructor
  66192. * @param {string} name - The rendering pipeline name
  66193. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66194. * @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 }
  66195. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66196. */
  66197. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66198. var _this = _super.call(this, scene.getEngine(), name) || this;
  66199. // Members
  66200. /**
  66201. * The PassPostProcess id in the pipeline that contains the original scene color
  66202. * @type {string}
  66203. */
  66204. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66205. /**
  66206. * The SSAO PostProcess id in the pipeline
  66207. * @type {string}
  66208. */
  66209. _this.SSAORenderEffect = "SSAORenderEffect";
  66210. /**
  66211. * The horizontal blur PostProcess id in the pipeline
  66212. * @type {string}
  66213. */
  66214. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66215. /**
  66216. * The vertical blur PostProcess id in the pipeline
  66217. * @type {string}
  66218. */
  66219. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66220. /**
  66221. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66222. * @type {string}
  66223. */
  66224. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66225. /**
  66226. * The output strength of the SSAO post-process. Default value is 1.0.
  66227. * @type {number}
  66228. */
  66229. _this.totalStrength = 1.0;
  66230. /**
  66231. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66232. * @type {number}
  66233. */
  66234. _this.radius = 0.0001;
  66235. /**
  66236. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66237. * Must not be equal to fallOff and superior to fallOff.
  66238. * Default value is 0.975
  66239. * @type {number}
  66240. */
  66241. _this.area = 0.0075;
  66242. /**
  66243. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66244. * Must not be equal to area and inferior to area.
  66245. * Default value is 0.0
  66246. * @type {number}
  66247. */
  66248. _this.fallOff = 0.000001;
  66249. /**
  66250. * The base color of the SSAO post-process
  66251. * The final result is "base + ssao" between [0, 1]
  66252. * @type {number}
  66253. */
  66254. _this.base = 0.5;
  66255. _this._firstUpdate = true;
  66256. _this._scene = scene;
  66257. // Set up assets
  66258. _this._createRandomTexture();
  66259. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66260. var ssaoRatio = ratio.ssaoRatio || ratio;
  66261. var combineRatio = ratio.combineRatio || ratio;
  66262. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66263. _this._createSSAOPostProcess(ssaoRatio);
  66264. _this._createBlurPostProcess(ssaoRatio);
  66265. _this._createSSAOCombinePostProcess(combineRatio);
  66266. // Set up pipeline
  66267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66270. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66271. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66272. // Finish
  66273. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66274. if (cameras)
  66275. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66276. return _this;
  66277. }
  66278. // Public Methods
  66279. /**
  66280. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66281. */
  66282. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66283. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66284. for (var i = 0; i < this._scene.cameras.length; i++) {
  66285. var camera = this._scene.cameras[i];
  66286. this._originalColorPostProcess.dispose(camera);
  66287. this._ssaoPostProcess.dispose(camera);
  66288. this._blurHPostProcess.dispose(camera);
  66289. this._blurVPostProcess.dispose(camera);
  66290. this._ssaoCombinePostProcess.dispose(camera);
  66291. }
  66292. this._randomTexture.dispose();
  66293. if (disableDepthRender)
  66294. this._scene.disableDepthRenderer();
  66295. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66296. _super.prototype.dispose.call(this);
  66297. };
  66298. // Private Methods
  66299. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66300. var _this = this;
  66301. var size = 16;
  66302. 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);
  66303. 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);
  66304. this._blurHPostProcess.onActivateObservable.add(function () {
  66305. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66306. _this._blurHPostProcess.kernel = size * dw;
  66307. });
  66308. this._blurVPostProcess.onActivateObservable.add(function () {
  66309. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66310. _this._blurVPostProcess.kernel = size * dw;
  66311. });
  66312. };
  66313. SSAORenderingPipeline.prototype._rebuild = function () {
  66314. this._firstUpdate = true;
  66315. _super.prototype._rebuild.call(this);
  66316. };
  66317. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66318. var _this = this;
  66319. var numSamples = 16;
  66320. var sampleSphere = [
  66321. 0.5381, 0.1856, -0.4319,
  66322. 0.1379, 0.2486, 0.4430,
  66323. 0.3371, 0.5679, -0.0057,
  66324. -0.6999, -0.0451, -0.0019,
  66325. 0.0689, -0.1598, -0.8547,
  66326. 0.0560, 0.0069, -0.1843,
  66327. -0.0146, 0.1402, 0.0762,
  66328. 0.0100, -0.1924, -0.0344,
  66329. -0.3577, -0.5301, -0.4358,
  66330. -0.3169, 0.1063, 0.0158,
  66331. 0.0103, -0.5869, 0.0046,
  66332. -0.0897, -0.4940, 0.3287,
  66333. 0.7119, -0.0154, -0.0918,
  66334. -0.0533, 0.0596, -0.5411,
  66335. 0.0352, -0.0631, 0.5460,
  66336. -0.4776, 0.2847, -0.0271
  66337. ];
  66338. var samplesFactor = 1.0 / numSamples;
  66339. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66340. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66341. "area", "fallOff", "base", "range", "viewport"
  66342. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66343. this._ssaoPostProcess.onApply = function (effect) {
  66344. if (_this._firstUpdate) {
  66345. effect.setArray3("sampleSphere", sampleSphere);
  66346. effect.setFloat("samplesFactor", samplesFactor);
  66347. effect.setFloat("randTextureTiles", 4.0);
  66348. }
  66349. effect.setFloat("totalStrength", _this.totalStrength);
  66350. effect.setFloat("radius", _this.radius);
  66351. effect.setFloat("area", _this.area);
  66352. effect.setFloat("fallOff", _this.fallOff);
  66353. effect.setFloat("base", _this.base);
  66354. effect.setTexture("textureSampler", _this._depthTexture);
  66355. effect.setTexture("randomSampler", _this._randomTexture);
  66356. };
  66357. };
  66358. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66359. var _this = this;
  66360. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66361. this._ssaoCombinePostProcess.onApply = function (effect) {
  66362. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66363. };
  66364. };
  66365. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66366. var size = 512;
  66367. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66368. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66369. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66370. var context = this._randomTexture.getContext();
  66371. var rand = function (min, max) {
  66372. return Math.random() * (max - min) + min;
  66373. };
  66374. var randVector = BABYLON.Vector3.Zero();
  66375. for (var x = 0; x < size; x++) {
  66376. for (var y = 0; y < size; y++) {
  66377. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66378. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66379. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66380. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66381. context.fillRect(x, y, 1, 1);
  66382. }
  66383. }
  66384. this._randomTexture.update(false);
  66385. };
  66386. __decorate([
  66387. BABYLON.serialize()
  66388. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66389. __decorate([
  66390. BABYLON.serialize()
  66391. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66392. __decorate([
  66393. BABYLON.serialize()
  66394. ], SSAORenderingPipeline.prototype, "area", void 0);
  66395. __decorate([
  66396. BABYLON.serialize()
  66397. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66398. __decorate([
  66399. BABYLON.serialize()
  66400. ], SSAORenderingPipeline.prototype, "base", void 0);
  66401. return SSAORenderingPipeline;
  66402. }(BABYLON.PostProcessRenderPipeline));
  66403. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66404. })(BABYLON || (BABYLON = {}));
  66405. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66406. var BABYLON;
  66407. (function (BABYLON) {
  66408. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66409. __extends(SSAO2RenderingPipeline, _super);
  66410. /**
  66411. * @constructor
  66412. * @param {string} name - The rendering pipeline name
  66413. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66414. * @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 }
  66415. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66416. */
  66417. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66418. var _this = _super.call(this, scene.getEngine(), name) || this;
  66419. // Members
  66420. /**
  66421. * The PassPostProcess id in the pipeline that contains the original scene color
  66422. * @type {string}
  66423. */
  66424. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66425. /**
  66426. * The SSAO PostProcess id in the pipeline
  66427. * @type {string}
  66428. */
  66429. _this.SSAORenderEffect = "SSAORenderEffect";
  66430. /**
  66431. * The horizontal blur PostProcess id in the pipeline
  66432. * @type {string}
  66433. */
  66434. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66435. /**
  66436. * The vertical blur PostProcess id in the pipeline
  66437. * @type {string}
  66438. */
  66439. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66440. /**
  66441. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66442. * @type {string}
  66443. */
  66444. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66445. /**
  66446. * The output strength of the SSAO post-process. Default value is 1.0.
  66447. * @type {number}
  66448. */
  66449. _this.totalStrength = 1.0;
  66450. /**
  66451. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66452. * @type {number}
  66453. */
  66454. _this.maxZ = 100.0;
  66455. /**
  66456. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66457. * @type {number}
  66458. */
  66459. _this.minZAspect = 0.2;
  66460. /**
  66461. * Number of samples used for the SSAO calculations. Default value is 8
  66462. * @type {number}
  66463. */
  66464. _this._samples = 8;
  66465. /**
  66466. * Are we using bilateral blur ?
  66467. * @type {boolean}
  66468. */
  66469. _this._expensiveBlur = true;
  66470. /**
  66471. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66472. * @type {number}
  66473. */
  66474. _this.radius = 2.0;
  66475. /**
  66476. * The base color of the SSAO post-process
  66477. * The final result is "base + ssao" between [0, 1]
  66478. * @type {number}
  66479. */
  66480. _this.base = 0.1;
  66481. _this._firstUpdate = true;
  66482. _this._scene = scene;
  66483. if (!_this.isSupported) {
  66484. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66485. return _this;
  66486. }
  66487. var ssaoRatio = ratio.ssaoRatio || ratio;
  66488. var blurRatio = ratio.blurRatio || ratio;
  66489. // Set up assets
  66490. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66491. _this._createRandomTexture();
  66492. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66493. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66494. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66495. _this._createSSAOPostProcess(1.0);
  66496. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66497. _this._createSSAOCombinePostProcess(blurRatio);
  66498. // Set up pipeline
  66499. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66500. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66501. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66502. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66503. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66504. // Finish
  66505. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66506. if (cameras)
  66507. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66508. return _this;
  66509. }
  66510. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66511. get: function () {
  66512. return this._samples;
  66513. },
  66514. set: function (n) {
  66515. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66516. this._samples = n;
  66517. this._sampleSphere = this._generateHemisphere();
  66518. this._firstUpdate = true;
  66519. },
  66520. enumerable: true,
  66521. configurable: true
  66522. });
  66523. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66524. get: function () {
  66525. return this._expensiveBlur;
  66526. },
  66527. set: function (b) {
  66528. 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"]);
  66529. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66530. this._expensiveBlur = b;
  66531. this._firstUpdate = true;
  66532. },
  66533. enumerable: true,
  66534. configurable: true
  66535. });
  66536. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66537. /**
  66538. * Support test.
  66539. * @type {boolean}
  66540. */
  66541. get: function () {
  66542. var engine = BABYLON.Engine.LastCreatedEngine;
  66543. if (!engine) {
  66544. return false;
  66545. }
  66546. return engine.getCaps().drawBuffersExtension;
  66547. },
  66548. enumerable: true,
  66549. configurable: true
  66550. });
  66551. // Public Methods
  66552. /**
  66553. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66554. */
  66555. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66556. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66557. for (var i = 0; i < this._scene.cameras.length; i++) {
  66558. var camera = this._scene.cameras[i];
  66559. this._originalColorPostProcess.dispose(camera);
  66560. this._ssaoPostProcess.dispose(camera);
  66561. this._blurHPostProcess.dispose(camera);
  66562. this._blurVPostProcess.dispose(camera);
  66563. this._ssaoCombinePostProcess.dispose(camera);
  66564. }
  66565. this._randomTexture.dispose();
  66566. if (disableGeometryBufferRenderer)
  66567. this._scene.disableGeometryBufferRenderer();
  66568. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66569. _super.prototype.dispose.call(this);
  66570. };
  66571. // Private Methods
  66572. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66573. var _this = this;
  66574. this._samplerOffsets = [];
  66575. var expensive = this.expensiveBlur;
  66576. for (var i = -8; i < 8; i++) {
  66577. this._samplerOffsets.push(i * 2 + 0.5);
  66578. }
  66579. 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");
  66580. this._blurHPostProcess.onApply = function (effect) {
  66581. if (!_this._scene.activeCamera) {
  66582. return;
  66583. }
  66584. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66585. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66586. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66587. effect.setFloat("radius", _this.radius);
  66588. effect.setTexture("depthSampler", _this._depthTexture);
  66589. if (_this._firstUpdate) {
  66590. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66591. }
  66592. };
  66593. 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");
  66594. this._blurVPostProcess.onApply = function (effect) {
  66595. if (!_this._scene.activeCamera) {
  66596. return;
  66597. }
  66598. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66599. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66600. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66601. effect.setFloat("radius", _this.radius);
  66602. effect.setTexture("depthSampler", _this._depthTexture);
  66603. if (_this._firstUpdate) {
  66604. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66605. _this._firstUpdate = false;
  66606. }
  66607. };
  66608. };
  66609. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66610. this._firstUpdate = true;
  66611. _super.prototype._rebuild.call(this);
  66612. };
  66613. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66614. var numSamples = this.samples;
  66615. var result = [];
  66616. var vector, scale;
  66617. var rand = function (min, max) {
  66618. return Math.random() * (max - min) + min;
  66619. };
  66620. var i = 0;
  66621. while (i < numSamples) {
  66622. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66623. vector.normalize();
  66624. scale = i / numSamples;
  66625. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66626. vector.scaleInPlace(scale);
  66627. result.push(vector.x, vector.y, vector.z);
  66628. i++;
  66629. }
  66630. return result;
  66631. };
  66632. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66633. var _this = this;
  66634. var numSamples = this.samples;
  66635. this._sampleSphere = this._generateHemisphere();
  66636. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66637. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66638. "base", "range", "projection", "near", "far", "texelSize",
  66639. "xViewport", "yViewport", "maxZ", "minZAspect"
  66640. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66641. this._ssaoPostProcess.onApply = function (effect) {
  66642. if (_this._firstUpdate) {
  66643. effect.setArray3("sampleSphere", _this._sampleSphere);
  66644. effect.setFloat("randTextureTiles", 4.0);
  66645. }
  66646. if (!_this._scene.activeCamera) {
  66647. return;
  66648. }
  66649. effect.setFloat("samplesFactor", 1 / _this.samples);
  66650. effect.setFloat("totalStrength", _this.totalStrength);
  66651. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66652. effect.setFloat("radius", _this.radius);
  66653. effect.setFloat("maxZ", _this.maxZ);
  66654. effect.setFloat("minZAspect", _this.minZAspect);
  66655. effect.setFloat("base", _this.base);
  66656. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66657. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66658. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66659. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66660. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66661. effect.setTexture("textureSampler", _this._depthTexture);
  66662. effect.setTexture("normalSampler", _this._normalTexture);
  66663. effect.setTexture("randomSampler", _this._randomTexture);
  66664. };
  66665. };
  66666. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66667. var _this = this;
  66668. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66669. this._ssaoCombinePostProcess.onApply = function (effect) {
  66670. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66671. };
  66672. };
  66673. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66674. var size = 512;
  66675. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66676. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66677. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66678. var context = this._randomTexture.getContext();
  66679. var rand = function (min, max) {
  66680. return Math.random() * (max - min) + min;
  66681. };
  66682. var randVector = BABYLON.Vector3.Zero();
  66683. for (var x = 0; x < size; x++) {
  66684. for (var y = 0; y < size; y++) {
  66685. randVector.x = rand(0.0, 1.0);
  66686. randVector.y = rand(0.0, 1.0);
  66687. randVector.z = 0.0;
  66688. randVector.normalize();
  66689. randVector.scaleInPlace(255);
  66690. randVector.x = Math.floor(randVector.x);
  66691. randVector.y = Math.floor(randVector.y);
  66692. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66693. context.fillRect(x, y, 1, 1);
  66694. }
  66695. }
  66696. this._randomTexture.update(false);
  66697. };
  66698. __decorate([
  66699. BABYLON.serialize()
  66700. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66701. __decorate([
  66702. BABYLON.serialize()
  66703. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66704. __decorate([
  66705. BABYLON.serialize()
  66706. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66707. __decorate([
  66708. BABYLON.serialize("samples")
  66709. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66710. __decorate([
  66711. BABYLON.serialize("expensiveBlur")
  66712. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66713. __decorate([
  66714. BABYLON.serialize()
  66715. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66716. __decorate([
  66717. BABYLON.serialize()
  66718. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66719. return SSAO2RenderingPipeline;
  66720. }(BABYLON.PostProcessRenderPipeline));
  66721. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66722. })(BABYLON || (BABYLON = {}));
  66723. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66724. // BABYLON.JS Chromatic Aberration GLSL Shader
  66725. // Author: Olivier Guyot
  66726. // Separates very slightly R, G and B colors on the edges of the screen
  66727. // Inspired by Francois Tarlier & Martins Upitis
  66728. var BABYLON;
  66729. (function (BABYLON) {
  66730. var LensRenderingPipeline = /** @class */ (function (_super) {
  66731. __extends(LensRenderingPipeline, _super);
  66732. /**
  66733. * @constructor
  66734. *
  66735. * Effect parameters are as follow:
  66736. * {
  66737. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66738. * edge_blur: number; // from 0 to x (1 for realism)
  66739. * distortion: number; // from 0 to x (1 for realism)
  66740. * grain_amount: number; // from 0 to 1
  66741. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66742. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66743. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66744. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66745. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66746. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66747. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66748. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66749. * }
  66750. * Note: if an effect parameter is unset, effect is disabled
  66751. *
  66752. * @param {string} name - The rendering pipeline name
  66753. * @param {object} parameters - An object containing all parameters (see above)
  66754. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66755. * @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)
  66756. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66757. */
  66758. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66759. if (ratio === void 0) { ratio = 1.0; }
  66760. var _this = _super.call(this, scene.getEngine(), name) || this;
  66761. // Lens effects can be of the following:
  66762. // - chromatic aberration (slight shift of RGB colors)
  66763. // - blur on the edge of the lens
  66764. // - lens distortion
  66765. // - depth-of-field blur & highlights enhancing
  66766. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66767. // - grain effect (noise or custom texture)
  66768. // Two additional texture samplers are needed:
  66769. // - depth map (for depth-of-field)
  66770. // - grain texture
  66771. /**
  66772. * The chromatic aberration PostProcess id in the pipeline
  66773. * @type {string}
  66774. */
  66775. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66776. /**
  66777. * The highlights enhancing PostProcess id in the pipeline
  66778. * @type {string}
  66779. */
  66780. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66781. /**
  66782. * The depth-of-field PostProcess id in the pipeline
  66783. * @type {string}
  66784. */
  66785. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66786. _this._scene = scene;
  66787. // Fetch texture samplers
  66788. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66789. if (parameters.grain_texture) {
  66790. _this._grainTexture = parameters.grain_texture;
  66791. }
  66792. else {
  66793. _this._createGrainTexture();
  66794. }
  66795. // save parameters
  66796. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66797. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66798. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66799. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66800. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66801. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66802. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66803. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66804. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66805. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66806. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66807. // Create effects
  66808. _this._createChromaticAberrationPostProcess(ratio);
  66809. _this._createHighlightsPostProcess(ratio);
  66810. _this._createDepthOfFieldPostProcess(ratio / 4);
  66811. // Set up pipeline
  66812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66813. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66814. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66815. if (_this._highlightsGain === -1) {
  66816. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66817. }
  66818. // Finish
  66819. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66820. if (cameras) {
  66821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66822. }
  66823. return _this;
  66824. }
  66825. // public methods (self explanatory)
  66826. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66827. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66828. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66829. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66830. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66831. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66832. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66833. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66834. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66835. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66836. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66837. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66838. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66839. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66840. };
  66841. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66842. this._highlightsPostProcess.updateEffect();
  66843. };
  66844. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66845. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66846. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66847. this._highlightsGain = amount;
  66848. };
  66849. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66850. if (this._highlightsGain === -1) {
  66851. this._highlightsGain = 1.0;
  66852. }
  66853. this._highlightsThreshold = amount;
  66854. };
  66855. LensRenderingPipeline.prototype.disableHighlights = function () {
  66856. this._highlightsGain = -1;
  66857. };
  66858. /**
  66859. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66860. */
  66861. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66862. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66863. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66864. this._chromaticAberrationPostProcess = null;
  66865. this._highlightsPostProcess = null;
  66866. this._depthOfFieldPostProcess = null;
  66867. this._grainTexture.dispose();
  66868. if (disableDepthRender)
  66869. this._scene.disableDepthRenderer();
  66870. };
  66871. // colors shifting and distortion
  66872. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66873. var _this = this;
  66874. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  66875. [], // samplers
  66876. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66877. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66878. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66879. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66880. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66881. effect.setFloat('radialIntensity', 1);
  66882. effect.setFloat2('direction', 17, 17);
  66883. effect.setFloat2('centerPosition', 0.5, 0.5);
  66884. };
  66885. };
  66886. // highlights enhancing
  66887. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66888. var _this = this;
  66889. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66890. [], // samplers
  66891. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66892. this._highlightsPostProcess.onApply = function (effect) {
  66893. effect.setFloat('gain', _this._highlightsGain);
  66894. effect.setFloat('threshold', _this._highlightsThreshold);
  66895. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66896. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66897. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66898. };
  66899. };
  66900. // colors shifting and distortion
  66901. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66902. var _this = this;
  66903. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66904. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66905. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66906. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66907. this._depthOfFieldPostProcess.onApply = function (effect) {
  66908. effect.setTexture("depthSampler", _this._depthTexture);
  66909. effect.setTexture("grainSampler", _this._grainTexture);
  66910. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66911. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66912. effect.setFloat('grain_amount', _this._grainAmount);
  66913. effect.setBool('blur_noise', _this._blurNoise);
  66914. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66915. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66916. effect.setFloat('distortion', _this._distortion);
  66917. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66918. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66919. effect.setFloat('aperture', _this._dofAperture);
  66920. effect.setFloat('darken', _this._dofDarken);
  66921. effect.setFloat('edge_blur', _this._edgeBlur);
  66922. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66923. if (_this._scene.activeCamera) {
  66924. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66925. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66926. }
  66927. };
  66928. };
  66929. // creates a black and white random noise texture, 512x512
  66930. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66931. var size = 512;
  66932. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66933. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66934. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66935. var context = this._grainTexture.getContext();
  66936. var rand = function (min, max) {
  66937. return Math.random() * (max - min) + min;
  66938. };
  66939. var value;
  66940. for (var x = 0; x < size; x++) {
  66941. for (var y = 0; y < size; y++) {
  66942. value = Math.floor(rand(0.42, 0.58) * 255);
  66943. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66944. context.fillRect(x, y, 1, 1);
  66945. }
  66946. }
  66947. this._grainTexture.update(false);
  66948. };
  66949. return LensRenderingPipeline;
  66950. }(BABYLON.PostProcessRenderPipeline));
  66951. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66952. })(BABYLON || (BABYLON = {}));
  66953. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66954. var BABYLON;
  66955. (function (BABYLON) {
  66956. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66957. __extends(StandardRenderingPipeline, _super);
  66958. /**
  66959. * @constructor
  66960. * @param {string} name - The rendering pipeline name
  66961. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66962. * @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)
  66963. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66964. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66965. */
  66966. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66967. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66968. var _this = _super.call(this, scene.getEngine(), name) || this;
  66969. _this.downSampleX4PostProcess = null;
  66970. _this.brightPassPostProcess = null;
  66971. _this.blurHPostProcesses = [];
  66972. _this.blurVPostProcesses = [];
  66973. _this.textureAdderPostProcess = null;
  66974. _this.volumetricLightPostProcess = null;
  66975. _this.volumetricLightSmoothXPostProcess = null;
  66976. _this.volumetricLightSmoothYPostProcess = null;
  66977. _this.volumetricLightMergePostProces = null;
  66978. _this.volumetricLightFinalPostProcess = null;
  66979. _this.luminancePostProcess = null;
  66980. _this.luminanceDownSamplePostProcesses = [];
  66981. _this.hdrPostProcess = null;
  66982. _this.textureAdderFinalPostProcess = null;
  66983. _this.lensFlareFinalPostProcess = null;
  66984. _this.hdrFinalPostProcess = null;
  66985. _this.lensFlarePostProcess = null;
  66986. _this.lensFlareComposePostProcess = null;
  66987. _this.motionBlurPostProcess = null;
  66988. _this.depthOfFieldPostProcess = null;
  66989. // Values
  66990. _this.brightThreshold = 1.0;
  66991. _this.blurWidth = 512.0;
  66992. _this.horizontalBlur = false;
  66993. _this.exposure = 1.0;
  66994. _this.lensTexture = null;
  66995. _this.volumetricLightCoefficient = 0.2;
  66996. _this.volumetricLightPower = 4.0;
  66997. _this.volumetricLightBlurScale = 64.0;
  66998. _this.sourceLight = null;
  66999. _this.hdrMinimumLuminance = 1.0;
  67000. _this.hdrDecreaseRate = 0.5;
  67001. _this.hdrIncreaseRate = 0.5;
  67002. _this.lensColorTexture = null;
  67003. _this.lensFlareStrength = 20.0;
  67004. _this.lensFlareGhostDispersal = 1.4;
  67005. _this.lensFlareHaloWidth = 0.7;
  67006. _this.lensFlareDistortionStrength = 16.0;
  67007. _this.lensStarTexture = null;
  67008. _this.lensFlareDirtTexture = null;
  67009. _this.depthOfFieldDistance = 10.0;
  67010. _this.depthOfFieldBlurWidth = 64.0;
  67011. _this.motionStrength = 1.0;
  67012. // IAnimatable
  67013. _this.animations = [];
  67014. _this._currentDepthOfFieldSource = null;
  67015. _this._hdrCurrentLuminance = 1.0;
  67016. // Getters and setters
  67017. _this._bloomEnabled = true;
  67018. _this._depthOfFieldEnabled = false;
  67019. _this._vlsEnabled = false;
  67020. _this._lensFlareEnabled = false;
  67021. _this._hdrEnabled = false;
  67022. _this._motionBlurEnabled = false;
  67023. _this._motionBlurSamples = 64.0;
  67024. _this._volumetricLightStepsCount = 50.0;
  67025. _this._cameras = cameras || [];
  67026. // Initialize
  67027. _this._scene = scene;
  67028. _this._basePostProcess = originalPostProcess;
  67029. _this._ratio = ratio;
  67030. // Misc
  67031. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67032. // Finish
  67033. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67034. _this._buildPipeline();
  67035. return _this;
  67036. }
  67037. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67038. get: function () {
  67039. return this._bloomEnabled;
  67040. },
  67041. set: function (enabled) {
  67042. if (this._bloomEnabled === enabled) {
  67043. return;
  67044. }
  67045. this._bloomEnabled = enabled;
  67046. this._buildPipeline();
  67047. },
  67048. enumerable: true,
  67049. configurable: true
  67050. });
  67051. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67052. get: function () {
  67053. return this._depthOfFieldEnabled;
  67054. },
  67055. set: function (enabled) {
  67056. if (this._depthOfFieldEnabled === enabled) {
  67057. return;
  67058. }
  67059. this._depthOfFieldEnabled = enabled;
  67060. this._buildPipeline();
  67061. },
  67062. enumerable: true,
  67063. configurable: true
  67064. });
  67065. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67066. get: function () {
  67067. return this._lensFlareEnabled;
  67068. },
  67069. set: function (enabled) {
  67070. if (this._lensFlareEnabled === enabled) {
  67071. return;
  67072. }
  67073. this._lensFlareEnabled = enabled;
  67074. this._buildPipeline();
  67075. },
  67076. enumerable: true,
  67077. configurable: true
  67078. });
  67079. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67080. get: function () {
  67081. return this._hdrEnabled;
  67082. },
  67083. set: function (enabled) {
  67084. if (this._hdrEnabled === enabled) {
  67085. return;
  67086. }
  67087. this._hdrEnabled = enabled;
  67088. this._buildPipeline();
  67089. },
  67090. enumerable: true,
  67091. configurable: true
  67092. });
  67093. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67094. get: function () {
  67095. return this._vlsEnabled;
  67096. },
  67097. set: function (enabled) {
  67098. if (this._vlsEnabled === enabled) {
  67099. return;
  67100. }
  67101. if (enabled) {
  67102. var geometry = this._scene.enableGeometryBufferRenderer();
  67103. if (!geometry) {
  67104. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67105. return;
  67106. }
  67107. }
  67108. this._vlsEnabled = enabled;
  67109. this._buildPipeline();
  67110. },
  67111. enumerable: true,
  67112. configurable: true
  67113. });
  67114. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67115. get: function () {
  67116. return this._motionBlurEnabled;
  67117. },
  67118. set: function (enabled) {
  67119. if (this._motionBlurEnabled === enabled) {
  67120. return;
  67121. }
  67122. this._motionBlurEnabled = enabled;
  67123. this._buildPipeline();
  67124. },
  67125. enumerable: true,
  67126. configurable: true
  67127. });
  67128. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67129. get: function () {
  67130. return this._volumetricLightStepsCount;
  67131. },
  67132. set: function (count) {
  67133. if (this.volumetricLightPostProcess) {
  67134. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67135. }
  67136. this._volumetricLightStepsCount = count;
  67137. },
  67138. enumerable: true,
  67139. configurable: true
  67140. });
  67141. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67142. get: function () {
  67143. return this._motionBlurSamples;
  67144. },
  67145. set: function (samples) {
  67146. if (this.motionBlurPostProcess) {
  67147. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67148. }
  67149. this._motionBlurSamples = samples;
  67150. },
  67151. enumerable: true,
  67152. configurable: true
  67153. });
  67154. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67155. var _this = this;
  67156. var ratio = this._ratio;
  67157. var scene = this._scene;
  67158. this._disposePostProcesses();
  67159. this._reset();
  67160. // Create pass post-process
  67161. if (!this._basePostProcess) {
  67162. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67163. this.originalPostProcess.onApply = function (effect) {
  67164. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67165. };
  67166. }
  67167. else {
  67168. this.originalPostProcess = this._basePostProcess;
  67169. }
  67170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67171. this._currentDepthOfFieldSource = this.originalPostProcess;
  67172. if (this._vlsEnabled) {
  67173. // Create volumetric light
  67174. this._createVolumetricLightPostProcess(scene, ratio);
  67175. // Create volumetric light final post-process
  67176. 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);
  67177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67178. }
  67179. if (this._bloomEnabled) {
  67180. // Create down sample X4 post-process
  67181. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67182. // Create bright pass post-process
  67183. this._createBrightPassPostProcess(scene, ratio / 2);
  67184. // Create gaussian blur post-processes (down sampling blurs)
  67185. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67186. // Create texture adder post-process
  67187. this._createTextureAdderPostProcess(scene, ratio);
  67188. // Create depth-of-field source post-process
  67189. 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);
  67190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67191. }
  67192. if (this._lensFlareEnabled) {
  67193. // Create lens flare post-process
  67194. this._createLensFlarePostProcess(scene, ratio);
  67195. // Create depth-of-field source post-process post lens-flare and disable it now
  67196. 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);
  67197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67198. }
  67199. if (this._hdrEnabled) {
  67200. // Create luminance
  67201. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67202. // Create HDR
  67203. this._createHdrPostProcess(scene, ratio);
  67204. // Create depth-of-field source post-process post hdr and disable it now
  67205. 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);
  67206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67207. }
  67208. if (this._depthOfFieldEnabled) {
  67209. // Create gaussian blur used by depth-of-field
  67210. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67211. // Create depth-of-field post-process
  67212. this._createDepthOfFieldPostProcess(scene, ratio);
  67213. }
  67214. if (this._motionBlurEnabled) {
  67215. // Create motion blur post-process
  67216. this._createMotionBlurPostProcess(scene, ratio);
  67217. }
  67218. if (this._cameras !== null) {
  67219. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67220. }
  67221. };
  67222. // Down Sample X4 Post-Processs
  67223. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67224. var _this = this;
  67225. var downSampleX4Offsets = new Array(32);
  67226. 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);
  67227. this.downSampleX4PostProcess.onApply = function (effect) {
  67228. var id = 0;
  67229. var width = _this.downSampleX4PostProcess.width;
  67230. var height = _this.downSampleX4PostProcess.height;
  67231. for (var i = -2; i < 2; i++) {
  67232. for (var j = -2; j < 2; j++) {
  67233. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67234. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67235. id += 2;
  67236. }
  67237. }
  67238. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67239. };
  67240. // Add to pipeline
  67241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67242. };
  67243. // Brightpass Post-Process
  67244. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67245. var _this = this;
  67246. var brightOffsets = new Array(8);
  67247. 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);
  67248. this.brightPassPostProcess.onApply = function (effect) {
  67249. var sU = (1.0 / _this.brightPassPostProcess.width);
  67250. var sV = (1.0 / _this.brightPassPostProcess.height);
  67251. brightOffsets[0] = -0.5 * sU;
  67252. brightOffsets[1] = 0.5 * sV;
  67253. brightOffsets[2] = 0.5 * sU;
  67254. brightOffsets[3] = 0.5 * sV;
  67255. brightOffsets[4] = -0.5 * sU;
  67256. brightOffsets[5] = -0.5 * sV;
  67257. brightOffsets[6] = 0.5 * sU;
  67258. brightOffsets[7] = -0.5 * sV;
  67259. effect.setArray2("dsOffsets", brightOffsets);
  67260. effect.setFloat("brightThreshold", _this.brightThreshold);
  67261. };
  67262. // Add to pipeline
  67263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67264. };
  67265. // Create blur H&V post-processes
  67266. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67267. var _this = this;
  67268. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67269. var engine = scene.getEngine();
  67270. 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);
  67271. 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);
  67272. blurX.onActivateObservable.add(function () {
  67273. var dw = blurX.width / engine.getRenderWidth();
  67274. blurX.kernel = _this[blurWidthKey] * dw;
  67275. });
  67276. blurY.onActivateObservable.add(function () {
  67277. var dw = blurY.height / engine.getRenderHeight();
  67278. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67279. });
  67280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67282. this.blurHPostProcesses.push(blurX);
  67283. this.blurVPostProcesses.push(blurY);
  67284. };
  67285. // Create texture adder post-process
  67286. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67287. var _this = this;
  67288. 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);
  67289. this.textureAdderPostProcess.onApply = function (effect) {
  67290. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67291. effect.setTexture("lensSampler", _this.lensTexture);
  67292. effect.setFloat("exposure", _this.exposure);
  67293. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67294. };
  67295. // Add to pipeline
  67296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67297. };
  67298. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67299. var _this = this;
  67300. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67301. geometryRenderer.enablePosition = true;
  67302. var geometry = geometryRenderer.getGBuffer();
  67303. // Base post-process
  67304. 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));
  67305. var depthValues = BABYLON.Vector2.Zero();
  67306. this.volumetricLightPostProcess.onApply = function (effect) {
  67307. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67308. var generator = _this.sourceLight.getShadowGenerator();
  67309. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67310. effect.setTexture("positionSampler", geometry.textures[2]);
  67311. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67312. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67313. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67314. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67315. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67316. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67317. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67318. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67319. effect.setVector2("depthValues", depthValues);
  67320. }
  67321. };
  67322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67323. // Smooth
  67324. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67325. // Merge
  67326. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67327. this.volumetricLightMergePostProces.onApply = function (effect) {
  67328. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67329. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67330. };
  67331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67332. };
  67333. // Create luminance
  67334. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67335. var _this = this;
  67336. // Create luminance
  67337. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67338. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67339. var offsets = [];
  67340. this.luminancePostProcess.onApply = function (effect) {
  67341. var sU = (1.0 / _this.luminancePostProcess.width);
  67342. var sV = (1.0 / _this.luminancePostProcess.height);
  67343. offsets[0] = -0.5 * sU;
  67344. offsets[1] = 0.5 * sV;
  67345. offsets[2] = 0.5 * sU;
  67346. offsets[3] = 0.5 * sV;
  67347. offsets[4] = -0.5 * sU;
  67348. offsets[5] = -0.5 * sV;
  67349. offsets[6] = 0.5 * sU;
  67350. offsets[7] = -0.5 * sV;
  67351. effect.setArray2("lumOffsets", offsets);
  67352. };
  67353. // Add to pipeline
  67354. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67355. // Create down sample luminance
  67356. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67357. var size = Math.pow(3, i);
  67358. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67359. if (i === 0) {
  67360. defines += "#define FINAL_DOWN_SAMPLER";
  67361. }
  67362. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67363. this.luminanceDownSamplePostProcesses.push(postProcess);
  67364. }
  67365. // Create callbacks and add effects
  67366. var lastLuminance = this.luminancePostProcess;
  67367. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67368. var downSampleOffsets = new Array(18);
  67369. pp.onApply = function (effect) {
  67370. if (!lastLuminance) {
  67371. return;
  67372. }
  67373. var id = 0;
  67374. for (var x = -1; x < 2; x++) {
  67375. for (var y = -1; y < 2; y++) {
  67376. downSampleOffsets[id] = x / lastLuminance.width;
  67377. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67378. id += 2;
  67379. }
  67380. }
  67381. effect.setArray2("dsOffsets", downSampleOffsets);
  67382. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67383. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67384. lastLuminance = _this.luminancePostProcess;
  67385. }
  67386. else {
  67387. lastLuminance = pp;
  67388. }
  67389. };
  67390. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67391. pp.onAfterRender = function (effect) {
  67392. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67393. 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);
  67394. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67395. };
  67396. }
  67397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67398. });
  67399. };
  67400. // Create HDR post-process
  67401. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67402. var _this = this;
  67403. 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);
  67404. var outputLiminance = 1;
  67405. var time = 0;
  67406. var lastTime = 0;
  67407. this.hdrPostProcess.onApply = function (effect) {
  67408. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67409. time += scene.getEngine().getDeltaTime();
  67410. if (outputLiminance < 0) {
  67411. outputLiminance = _this._hdrCurrentLuminance;
  67412. }
  67413. else {
  67414. var dt = (lastTime - time) / 1000.0;
  67415. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67416. outputLiminance += _this.hdrDecreaseRate * dt;
  67417. }
  67418. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67419. outputLiminance -= _this.hdrIncreaseRate * dt;
  67420. }
  67421. else {
  67422. outputLiminance = _this._hdrCurrentLuminance;
  67423. }
  67424. }
  67425. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67426. effect.setFloat("averageLuminance", outputLiminance);
  67427. lastTime = time;
  67428. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67429. };
  67430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67431. };
  67432. // Create lens flare post-process
  67433. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67434. var _this = this;
  67435. 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);
  67436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67437. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67438. 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);
  67439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67440. var resolution = new BABYLON.Vector2(0, 0);
  67441. // Lens flare
  67442. this.lensFlarePostProcess.onApply = function (effect) {
  67443. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67444. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67445. effect.setFloat("strength", _this.lensFlareStrength);
  67446. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67447. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67448. // Shift
  67449. resolution.x = _this.lensFlarePostProcess.width;
  67450. resolution.y = _this.lensFlarePostProcess.height;
  67451. effect.setVector2("resolution", resolution);
  67452. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67453. };
  67454. // Compose
  67455. 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);
  67456. 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);
  67457. this.lensFlareComposePostProcess.onApply = function (effect) {
  67458. if (!_this._scene.activeCamera) {
  67459. return;
  67460. }
  67461. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67462. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67463. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67464. // Lens start rotation matrix
  67465. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67466. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67467. 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));
  67468. camRot *= 4.0;
  67469. 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);
  67470. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67471. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67472. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67473. };
  67474. };
  67475. // Create depth-of-field post-process
  67476. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67477. var _this = this;
  67478. 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);
  67479. this.depthOfFieldPostProcess.onApply = function (effect) {
  67480. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67481. effect.setTexture("depthSampler", _this._getDepthTexture());
  67482. effect.setFloat("distance", _this.depthOfFieldDistance);
  67483. };
  67484. // Add to pipeline
  67485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67486. };
  67487. // Create motion blur post-process
  67488. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67489. var _this = this;
  67490. 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);
  67491. var motionScale = 0;
  67492. var prevViewProjection = BABYLON.Matrix.Identity();
  67493. var invViewProjection = BABYLON.Matrix.Identity();
  67494. var viewProjection = BABYLON.Matrix.Identity();
  67495. var screenSize = BABYLON.Vector2.Zero();
  67496. this.motionBlurPostProcess.onApply = function (effect) {
  67497. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67498. viewProjection.invertToRef(invViewProjection);
  67499. effect.setMatrix("inverseViewProjection", invViewProjection);
  67500. effect.setMatrix("prevViewProjection", prevViewProjection);
  67501. prevViewProjection = viewProjection;
  67502. screenSize.x = _this.motionBlurPostProcess.width;
  67503. screenSize.y = _this.motionBlurPostProcess.height;
  67504. effect.setVector2("screenSize", screenSize);
  67505. motionScale = scene.getEngine().getFps() / 60.0;
  67506. effect.setFloat("motionScale", motionScale);
  67507. effect.setFloat("motionStrength", _this.motionStrength);
  67508. effect.setTexture("depthSampler", _this._getDepthTexture());
  67509. };
  67510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67511. };
  67512. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67513. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67514. var renderer = this._scene.enableGeometryBufferRenderer();
  67515. return renderer.getGBuffer().textures[0];
  67516. }
  67517. return this._scene.enableDepthRenderer().getDepthMap();
  67518. };
  67519. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67520. for (var i = 0; i < this._cameras.length; i++) {
  67521. var camera = this._cameras[i];
  67522. if (this.originalPostProcess) {
  67523. this.originalPostProcess.dispose(camera);
  67524. }
  67525. if (this.downSampleX4PostProcess) {
  67526. this.downSampleX4PostProcess.dispose(camera);
  67527. }
  67528. if (this.brightPassPostProcess) {
  67529. this.brightPassPostProcess.dispose(camera);
  67530. }
  67531. if (this.textureAdderPostProcess) {
  67532. this.textureAdderPostProcess.dispose(camera);
  67533. }
  67534. if (this.textureAdderFinalPostProcess) {
  67535. this.textureAdderFinalPostProcess.dispose(camera);
  67536. }
  67537. if (this.volumetricLightPostProcess) {
  67538. this.volumetricLightPostProcess.dispose(camera);
  67539. }
  67540. if (this.volumetricLightSmoothXPostProcess) {
  67541. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67542. }
  67543. if (this.volumetricLightSmoothYPostProcess) {
  67544. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67545. }
  67546. if (this.volumetricLightMergePostProces) {
  67547. this.volumetricLightMergePostProces.dispose(camera);
  67548. }
  67549. if (this.volumetricLightFinalPostProcess) {
  67550. this.volumetricLightFinalPostProcess.dispose(camera);
  67551. }
  67552. if (this.lensFlarePostProcess) {
  67553. this.lensFlarePostProcess.dispose(camera);
  67554. }
  67555. if (this.lensFlareComposePostProcess) {
  67556. this.lensFlareComposePostProcess.dispose(camera);
  67557. }
  67558. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67559. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67560. }
  67561. if (this.luminancePostProcess) {
  67562. this.luminancePostProcess.dispose(camera);
  67563. }
  67564. if (this.hdrPostProcess) {
  67565. this.hdrPostProcess.dispose(camera);
  67566. }
  67567. if (this.hdrFinalPostProcess) {
  67568. this.hdrFinalPostProcess.dispose(camera);
  67569. }
  67570. if (this.depthOfFieldPostProcess) {
  67571. this.depthOfFieldPostProcess.dispose(camera);
  67572. }
  67573. if (this.motionBlurPostProcess) {
  67574. this.motionBlurPostProcess.dispose(camera);
  67575. }
  67576. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67577. this.blurHPostProcesses[j].dispose(camera);
  67578. }
  67579. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67580. this.blurVPostProcesses[j].dispose(camera);
  67581. }
  67582. }
  67583. this.originalPostProcess = null;
  67584. this.downSampleX4PostProcess = null;
  67585. this.brightPassPostProcess = null;
  67586. this.textureAdderPostProcess = null;
  67587. this.textureAdderFinalPostProcess = null;
  67588. this.volumetricLightPostProcess = null;
  67589. this.volumetricLightSmoothXPostProcess = null;
  67590. this.volumetricLightSmoothYPostProcess = null;
  67591. this.volumetricLightMergePostProces = null;
  67592. this.volumetricLightFinalPostProcess = null;
  67593. this.lensFlarePostProcess = null;
  67594. this.lensFlareComposePostProcess = null;
  67595. this.luminancePostProcess = null;
  67596. this.hdrPostProcess = null;
  67597. this.hdrFinalPostProcess = null;
  67598. this.depthOfFieldPostProcess = null;
  67599. this.motionBlurPostProcess = null;
  67600. this.luminanceDownSamplePostProcesses = [];
  67601. this.blurHPostProcesses = [];
  67602. this.blurVPostProcesses = [];
  67603. };
  67604. // Dispose
  67605. StandardRenderingPipeline.prototype.dispose = function () {
  67606. this._disposePostProcesses();
  67607. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67608. _super.prototype.dispose.call(this);
  67609. };
  67610. // Serialize rendering pipeline
  67611. StandardRenderingPipeline.prototype.serialize = function () {
  67612. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67613. serializationObject.customType = "StandardRenderingPipeline";
  67614. return serializationObject;
  67615. };
  67616. /**
  67617. * Static members
  67618. */
  67619. // Parse serialized pipeline
  67620. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67621. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67622. };
  67623. // Luminance steps
  67624. StandardRenderingPipeline.LuminanceSteps = 6;
  67625. __decorate([
  67626. BABYLON.serialize()
  67627. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67628. __decorate([
  67629. BABYLON.serialize()
  67630. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67631. __decorate([
  67632. BABYLON.serialize()
  67633. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67634. __decorate([
  67635. BABYLON.serialize()
  67636. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67637. __decorate([
  67638. BABYLON.serializeAsTexture("lensTexture")
  67639. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67640. __decorate([
  67641. BABYLON.serialize()
  67642. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67643. __decorate([
  67644. BABYLON.serialize()
  67645. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67646. __decorate([
  67647. BABYLON.serialize()
  67648. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67649. __decorate([
  67650. BABYLON.serialize()
  67651. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67652. __decorate([
  67653. BABYLON.serialize()
  67654. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67655. __decorate([
  67656. BABYLON.serialize()
  67657. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67658. __decorate([
  67659. BABYLON.serializeAsTexture("lensColorTexture")
  67660. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67661. __decorate([
  67662. BABYLON.serialize()
  67663. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67664. __decorate([
  67665. BABYLON.serialize()
  67666. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67667. __decorate([
  67668. BABYLON.serialize()
  67669. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67670. __decorate([
  67671. BABYLON.serialize()
  67672. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67673. __decorate([
  67674. BABYLON.serializeAsTexture("lensStarTexture")
  67675. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67676. __decorate([
  67677. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67678. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67679. __decorate([
  67680. BABYLON.serialize()
  67681. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67682. __decorate([
  67683. BABYLON.serialize()
  67684. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67685. __decorate([
  67686. BABYLON.serialize()
  67687. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67688. __decorate([
  67689. BABYLON.serialize()
  67690. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67691. __decorate([
  67692. BABYLON.serialize()
  67693. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67694. __decorate([
  67695. BABYLON.serialize()
  67696. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67697. __decorate([
  67698. BABYLON.serialize()
  67699. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67700. __decorate([
  67701. BABYLON.serialize()
  67702. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67703. __decorate([
  67704. BABYLON.serialize()
  67705. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67706. __decorate([
  67707. BABYLON.serialize()
  67708. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67709. __decorate([
  67710. BABYLON.serialize()
  67711. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67712. __decorate([
  67713. BABYLON.serialize()
  67714. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67715. return StandardRenderingPipeline;
  67716. }(BABYLON.PostProcessRenderPipeline));
  67717. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67718. })(BABYLON || (BABYLON = {}));
  67719. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67720. var BABYLON;
  67721. (function (BABYLON) {
  67722. var FxaaPostProcess = /** @class */ (function (_super) {
  67723. __extends(FxaaPostProcess, _super);
  67724. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67725. if (camera === void 0) { camera = null; }
  67726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67727. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67728. _this.onApplyObservable.add(function (effect) {
  67729. var texelSize = _this.texelSize;
  67730. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67731. });
  67732. return _this;
  67733. }
  67734. return FxaaPostProcess;
  67735. }(BABYLON.PostProcess));
  67736. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67737. })(BABYLON || (BABYLON = {}));
  67738. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67739. var BABYLON;
  67740. (function (BABYLON) {
  67741. /**
  67742. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  67743. */
  67744. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  67745. __extends(ChromaticAberrationPostProcess, _super);
  67746. /**
  67747. * Creates a new instance of @see ChromaticAberrationPostProcess
  67748. * @param name The name of the effect.
  67749. * @param screenWidth The width of the screen to apply the effect on.
  67750. * @param screenHeight The height of the screen to apply the effect on.
  67751. * @param options The required width/height ratio to downsize to before computing the render pass.
  67752. * @param camera The camera to apply the render pass to.
  67753. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67754. * @param engine The engine which the post process will be applied. (default: current engine)
  67755. * @param reusable If the post process can be reused on the same frame. (default: false)
  67756. * @param textureType Type of textures used when performing the post process. (default: 0)
  67757. */
  67758. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  67759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67760. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67761. /**
  67762. * The amount of seperation of rgb channels (default: 0)
  67763. */
  67764. _this.aberrationAmount = 0;
  67765. /**
  67766. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  67767. */
  67768. _this.radialIntensity = 0;
  67769. /**
  67770. * 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))
  67771. */
  67772. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  67773. /**
  67774. * 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))
  67775. */
  67776. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  67777. _this.onApplyObservable.add(function (effect) {
  67778. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  67779. effect.setFloat('screen_width', screenWidth);
  67780. effect.setFloat('screen_height', screenHeight);
  67781. effect.setFloat('radialIntensity', _this.radialIntensity);
  67782. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  67783. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  67784. });
  67785. return _this;
  67786. }
  67787. return ChromaticAberrationPostProcess;
  67788. }(BABYLON.PostProcess));
  67789. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  67790. })(BABYLON || (BABYLON = {}));
  67791. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  67792. var BABYLON;
  67793. (function (BABYLON) {
  67794. /**
  67795. * The SharpenPostProcess applies a sharpen kernel to every pixel
  67796. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67797. */
  67798. var SharpenPostProcess = /** @class */ (function (_super) {
  67799. __extends(SharpenPostProcess, _super);
  67800. /**
  67801. * Creates a new instance of @see ConvolutionPostProcess
  67802. * @param name The name of the effect.
  67803. * @param options The required width/height ratio to downsize to before computing the render pass.
  67804. * @param camera The camera to apply the render pass to.
  67805. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67806. * @param engine The engine which the post process will be applied. (default: current engine)
  67807. * @param reusable If the post process can be reused on the same frame. (default: false)
  67808. * @param textureType Type of textures used when performing the post process. (default: 0)
  67809. */
  67810. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67812. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67813. /**
  67814. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  67815. */
  67816. _this.colorAmount = 1.0;
  67817. /**
  67818. * How much sharpness should be applied (default: 0.3)
  67819. */
  67820. _this.edgeAmount = 0.3;
  67821. _this.onApply = function (effect) {
  67822. effect.setFloat2("screenSize", _this.width, _this.height);
  67823. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  67824. };
  67825. return _this;
  67826. }
  67827. return SharpenPostProcess;
  67828. }(BABYLON.PostProcess));
  67829. BABYLON.SharpenPostProcess = SharpenPostProcess;
  67830. })(BABYLON || (BABYLON = {}));
  67831. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  67832. var BABYLON;
  67833. (function (BABYLON) {
  67834. /**
  67835. * The Blur Post Process which blurs an image based on a kernel and direction.
  67836. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  67837. */
  67838. var BlurPostProcess = /** @class */ (function (_super) {
  67839. __extends(BlurPostProcess, _super);
  67840. /**
  67841. * Creates a new instance of @see BlurPostProcess
  67842. * @param name The name of the effect.
  67843. * @param direction The direction in which to blur the image.
  67844. * @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.
  67845. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67846. * @param camera The camera to apply the render pass to.
  67847. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67848. * @param engine The engine which the post process will be applied. (default: current engine)
  67849. * @param reusable If the post process can be reused on the same frame. (default: false)
  67850. * @param textureType Type of textures used when performing the post process. (default: 0)
  67851. */
  67852. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  67853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67854. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67855. if (defines === void 0) { defines = ""; }
  67856. 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;
  67857. _this.direction = direction;
  67858. _this._packedFloat = false;
  67859. _this._staticDefines = "";
  67860. _this._staticDefines = defines;
  67861. _this.onApplyObservable.add(function (effect) {
  67862. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  67863. });
  67864. _this.kernel = kernel;
  67865. return _this;
  67866. }
  67867. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  67868. /**
  67869. * Gets the length in pixels of the blur sample region
  67870. */
  67871. get: function () {
  67872. return this._idealKernel;
  67873. },
  67874. /**
  67875. * Sets the length in pixels of the blur sample region
  67876. */
  67877. set: function (v) {
  67878. if (this._idealKernel === v) {
  67879. return;
  67880. }
  67881. v = Math.max(v, 1);
  67882. this._idealKernel = v;
  67883. this._kernel = this._nearestBestKernel(v);
  67884. this._updateParameters();
  67885. },
  67886. enumerable: true,
  67887. configurable: true
  67888. });
  67889. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  67890. /**
  67891. * Gets wether or not the blur is unpacking/repacking floats
  67892. */
  67893. get: function () {
  67894. return this._packedFloat;
  67895. },
  67896. /**
  67897. * Sets wether or not the blur needs to unpack/repack floats
  67898. */
  67899. set: function (v) {
  67900. if (this._packedFloat === v) {
  67901. return;
  67902. }
  67903. this._packedFloat = v;
  67904. this._updateParameters();
  67905. },
  67906. enumerable: true,
  67907. configurable: true
  67908. });
  67909. BlurPostProcess.prototype._updateParameters = function () {
  67910. // Generate sampling offsets and weights
  67911. var N = this._kernel;
  67912. var centerIndex = (N - 1) / 2;
  67913. // Generate Gaussian sampling weights over kernel
  67914. var offsets = [];
  67915. var weights = [];
  67916. var totalWeight = 0;
  67917. for (var i = 0; i < N; i++) {
  67918. var u = i / (N - 1);
  67919. var w = this._gaussianWeight(u * 2.0 - 1);
  67920. offsets[i] = (i - centerIndex);
  67921. weights[i] = w;
  67922. totalWeight += w;
  67923. }
  67924. // Normalize weights
  67925. for (var i = 0; i < weights.length; i++) {
  67926. weights[i] /= totalWeight;
  67927. }
  67928. // Optimize: combine samples to take advantage of hardware linear sampling
  67929. // Walk from left to center, combining pairs (symmetrically)
  67930. var linearSamplingWeights = [];
  67931. var linearSamplingOffsets = [];
  67932. var linearSamplingMap = [];
  67933. for (var i = 0; i <= centerIndex; i += 2) {
  67934. var j = Math.min(i + 1, Math.floor(centerIndex));
  67935. var singleCenterSample = i === j;
  67936. if (singleCenterSample) {
  67937. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67938. }
  67939. else {
  67940. var sharedCell = j === centerIndex;
  67941. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  67942. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  67943. if (offsetLinear === 0) {
  67944. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67945. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  67946. }
  67947. else {
  67948. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  67949. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  67950. }
  67951. }
  67952. }
  67953. for (var i = 0; i < linearSamplingMap.length; i++) {
  67954. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  67955. linearSamplingWeights[i] = linearSamplingMap[i].w;
  67956. }
  67957. // Replace with optimized
  67958. offsets = linearSamplingOffsets;
  67959. weights = linearSamplingWeights;
  67960. // Generate shaders
  67961. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  67962. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  67963. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  67964. var defines = "";
  67965. defines += this._staticDefines;
  67966. for (var i = 0; i < varyingCount; i++) {
  67967. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  67968. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  67969. }
  67970. var depCount = 0;
  67971. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  67972. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  67973. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  67974. depCount++;
  67975. }
  67976. if (this.packedFloat) {
  67977. defines += "#define PACKEDFLOAT 1";
  67978. }
  67979. this.updateEffect(defines, null, null, {
  67980. varyingCount: varyingCount,
  67981. depCount: depCount
  67982. });
  67983. };
  67984. /**
  67985. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  67986. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  67987. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  67988. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  67989. * The gaps between physical kernels are compensated for in the weighting of the samples
  67990. * @param idealKernel Ideal blur kernel.
  67991. * @return Nearest best kernel.
  67992. */
  67993. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  67994. var v = Math.round(idealKernel);
  67995. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  67996. var k = _a[_i];
  67997. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  67998. return Math.max(k, 3);
  67999. }
  68000. }
  68001. return Math.max(v, 3);
  68002. };
  68003. /**
  68004. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68005. * @param x The point on the Gaussian distribution to sample.
  68006. * @return the value of the Gaussian function at x.
  68007. */
  68008. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68009. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68010. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68011. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68012. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68013. // truncated at around 1.3% of peak strength.
  68014. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68015. var sigma = (1 / 3);
  68016. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68017. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68018. var weight = (1.0 / denominator) * Math.exp(exponent);
  68019. return weight;
  68020. };
  68021. /**
  68022. * Generates a string that can be used as a floating point number in GLSL.
  68023. * @param x Value to print.
  68024. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68025. * @return GLSL float string.
  68026. */
  68027. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68028. if (decimalFigures === void 0) { decimalFigures = 8; }
  68029. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68030. };
  68031. return BlurPostProcess;
  68032. }(BABYLON.PostProcess));
  68033. BABYLON.BlurPostProcess = BlurPostProcess;
  68034. })(BABYLON || (BABYLON = {}));
  68035. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68036. var BABYLON;
  68037. (function (BABYLON) {
  68038. /**
  68039. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68040. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68041. * based on samples that have a large difference in distance than the center pixel.
  68042. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68043. */
  68044. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68045. __extends(DepthOfFieldBlurPostProcess, _super);
  68046. /**
  68047. * Creates a new instance of @see CircleOfConfusionPostProcess
  68048. * @param name The name of the effect.
  68049. * @param scene The scene the effect belongs to.
  68050. * @param direction The direction the blur should be applied.
  68051. * @param kernel The size of the kernel used to blur.
  68052. * @param options The required width/height ratio to downsize to before computing the render pass.
  68053. * @param camera The camera to apply the render pass to.
  68054. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68055. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68056. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68057. * @param engine The engine which the post process will be applied. (default: current engine)
  68058. * @param reusable If the post process can be reused on the same frame. (default: false)
  68059. * @param textureType Type of textures used when performing the post process. (default: 0)
  68060. */
  68061. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  68062. if (imageToBlur === void 0) { imageToBlur = null; }
  68063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68065. 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") || this;
  68066. _this.direction = direction;
  68067. _this.onApplyObservable.add(function (effect) {
  68068. if (imageToBlur != null) {
  68069. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68070. }
  68071. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68072. if (scene.activeCamera) {
  68073. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68074. }
  68075. });
  68076. return _this;
  68077. }
  68078. return DepthOfFieldBlurPostProcess;
  68079. }(BABYLON.BlurPostProcess));
  68080. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68081. })(BABYLON || (BABYLON = {}));
  68082. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68083. var BABYLON;
  68084. (function (BABYLON) {
  68085. /**
  68086. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68087. */
  68088. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68089. __extends(DepthOfFieldMergePostProcess, _super);
  68090. /**
  68091. * Creates a new instance of @see CircleOfConfusionPostProcess
  68092. * @param name The name of the effect.
  68093. * @param original The non-blurred image to be modified
  68094. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68095. * @param blurSteps Incrimental bluring post processes.
  68096. * @param options The required width/height ratio to downsize to before computing the render pass.
  68097. * @param camera The camera to apply the render pass to.
  68098. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68099. * @param engine The engine which the post process will be applied. (default: current engine)
  68100. * @param reusable If the post process can be reused on the same frame. (default: false)
  68101. * @param textureType Type of textures used when performing the post process. (default: 0)
  68102. */
  68103. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68104. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68105. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68106. _this.onApplyObservable.add(function (effect) {
  68107. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68108. effect.setTextureFromPostProcess("originalSampler", original);
  68109. blurSteps.forEach(function (step, index) {
  68110. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68111. });
  68112. });
  68113. return _this;
  68114. }
  68115. return DepthOfFieldMergePostProcess;
  68116. }(BABYLON.PostProcess));
  68117. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68118. })(BABYLON || (BABYLON = {}));
  68119. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68120. var BABYLON;
  68121. (function (BABYLON) {
  68122. /**
  68123. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68124. */
  68125. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68126. __extends(CircleOfConfusionPostProcess, _super);
  68127. /**
  68128. * Creates a new instance of @see CircleOfConfusionPostProcess
  68129. * @param name The name of the effect.
  68130. * @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.
  68131. * @param options The required width/height ratio to downsize to before computing the render pass.
  68132. * @param camera The camera to apply the render pass to.
  68133. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68134. * @param engine The engine which the post process will be applied. (default: current engine)
  68135. * @param reusable If the post process can be reused on the same frame. (default: false)
  68136. * @param textureType Type of textures used when performing the post process. (default: 0)
  68137. */
  68138. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68139. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68140. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68141. /**
  68142. * 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.
  68143. */
  68144. _this.lensSize = 50;
  68145. /**
  68146. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68147. */
  68148. _this.fStop = 1.4;
  68149. /**
  68150. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68151. */
  68152. _this.focusDistance = 2000;
  68153. /**
  68154. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68155. */
  68156. _this.focalLength = 50;
  68157. _this._depthTexture = null;
  68158. _this._depthTexture = depthTexture;
  68159. _this.onApplyObservable.add(function (effect) {
  68160. if (!_this._depthTexture) {
  68161. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68162. return;
  68163. }
  68164. effect.setTexture("depthSampler", _this._depthTexture);
  68165. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68166. var aperture = _this.lensSize / _this.fStop;
  68167. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68168. effect.setFloat('focusDistance', _this.focusDistance);
  68169. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68170. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68171. });
  68172. return _this;
  68173. }
  68174. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68175. /**
  68176. * 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.
  68177. */
  68178. set: function (value) {
  68179. this._depthTexture = value;
  68180. },
  68181. enumerable: true,
  68182. configurable: true
  68183. });
  68184. return CircleOfConfusionPostProcess;
  68185. }(BABYLON.PostProcess));
  68186. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68187. })(BABYLON || (BABYLON = {}));
  68188. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68189. var BABYLON;
  68190. (function (BABYLON) {
  68191. /**
  68192. * Specifies the level of max blur that should be applied when using the depth of field effect
  68193. */
  68194. var DepthOfFieldEffectBlurLevel;
  68195. (function (DepthOfFieldEffectBlurLevel) {
  68196. /**
  68197. * Subtle blur
  68198. */
  68199. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68200. /**
  68201. * Medium blur
  68202. */
  68203. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68204. /**
  68205. * Large blur
  68206. */
  68207. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68208. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68209. ;
  68210. /**
  68211. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68212. */
  68213. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68214. __extends(DepthOfFieldEffect, _super);
  68215. /**
  68216. * Creates a new instance of @see DepthOfFieldEffect
  68217. * @param scene The scene the effect belongs to.
  68218. * @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.
  68219. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68220. */
  68221. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68222. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68223. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68224. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68225. return _this._effects;
  68226. }, true) || this;
  68227. _this._effects = [];
  68228. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68229. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68230. // Capture circle of confusion texture
  68231. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68232. _this._depthOfFieldPass.autoClear = false;
  68233. // 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)
  68234. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68235. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68236. _this._depthOfFieldBlurY = [];
  68237. _this._depthOfFieldBlurX = [];
  68238. var blurCount = 1;
  68239. var kernelSize = 15;
  68240. switch (blurLevel) {
  68241. case DepthOfFieldEffectBlurLevel.High: {
  68242. blurCount = 3;
  68243. kernelSize = 51;
  68244. break;
  68245. }
  68246. case DepthOfFieldEffectBlurLevel.Medium: {
  68247. blurCount = 2;
  68248. kernelSize = 31;
  68249. break;
  68250. }
  68251. default: {
  68252. kernelSize = 15;
  68253. blurCount = 1;
  68254. break;
  68255. }
  68256. }
  68257. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68258. for (var i = 0; i < blurCount; i++) {
  68259. 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);
  68260. blurY.autoClear = false;
  68261. 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);
  68262. blurX.autoClear = false;
  68263. _this._depthOfFieldBlurY.push(blurY);
  68264. _this._depthOfFieldBlurX.push(blurX);
  68265. }
  68266. // Merge blurred images with original image based on circleOfConfusion
  68267. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68268. _this._depthOfFieldMerge.autoClear = false;
  68269. // Set all post processes on the effect.
  68270. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68271. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68272. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68273. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68274. }
  68275. _this._effects.push(_this._depthOfFieldMerge);
  68276. return _this;
  68277. }
  68278. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68279. get: function () {
  68280. return this._circleOfConfusion.focalLength;
  68281. },
  68282. /**
  68283. * The focal the length of the camera used in the effect
  68284. */
  68285. set: function (value) {
  68286. this._circleOfConfusion.focalLength = value;
  68287. },
  68288. enumerable: true,
  68289. configurable: true
  68290. });
  68291. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68292. get: function () {
  68293. return this._circleOfConfusion.fStop;
  68294. },
  68295. /**
  68296. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68297. */
  68298. set: function (value) {
  68299. this._circleOfConfusion.fStop = value;
  68300. },
  68301. enumerable: true,
  68302. configurable: true
  68303. });
  68304. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68305. get: function () {
  68306. return this._circleOfConfusion.focusDistance;
  68307. },
  68308. /**
  68309. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68310. */
  68311. set: function (value) {
  68312. this._circleOfConfusion.focusDistance = value;
  68313. },
  68314. enumerable: true,
  68315. configurable: true
  68316. });
  68317. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68318. get: function () {
  68319. return this._circleOfConfusion.lensSize;
  68320. },
  68321. /**
  68322. * 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.
  68323. */
  68324. set: function (value) {
  68325. this._circleOfConfusion.lensSize = value;
  68326. },
  68327. enumerable: true,
  68328. configurable: true
  68329. });
  68330. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  68331. /**
  68332. * 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.
  68333. */
  68334. set: function (value) {
  68335. this._circleOfConfusion.depthTexture = value;
  68336. },
  68337. enumerable: true,
  68338. configurable: true
  68339. });
  68340. /**
  68341. * Disposes each of the internal effects for a given camera.
  68342. * @param camera The camera to dispose the effect on.
  68343. */
  68344. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68345. this._depthOfFieldPass.dispose(camera);
  68346. this._circleOfConfusion.dispose(camera);
  68347. this._depthOfFieldBlurX.forEach(function (element) {
  68348. element.dispose(camera);
  68349. });
  68350. this._depthOfFieldBlurY.forEach(function (element) {
  68351. element.dispose(camera);
  68352. });
  68353. this._depthOfFieldMerge.dispose(camera);
  68354. };
  68355. return DepthOfFieldEffect;
  68356. }(BABYLON.PostProcessRenderEffect));
  68357. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68358. })(BABYLON || (BABYLON = {}));
  68359. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68360. var BABYLON;
  68361. (function (BABYLON) {
  68362. /**
  68363. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68364. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68365. */
  68366. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68367. __extends(DefaultRenderingPipeline, _super);
  68368. /**
  68369. * @constructor
  68370. * @param {string} name - The rendering pipeline name
  68371. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68372. * @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)
  68373. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68374. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68375. */
  68376. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68377. if (automaticBuild === void 0) { automaticBuild = true; }
  68378. var _this = _super.call(this, scene.getEngine(), name) || this;
  68379. _this._originalCameras = [];
  68380. /**
  68381. * ID of the sharpen post process,
  68382. */
  68383. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68384. /**
  68385. * ID of the pass post process used for bloom,
  68386. */
  68387. _this.PassPostProcessId = "PassPostProcessEffect";
  68388. /**
  68389. * ID of the highlight post process used for bloom,
  68390. */
  68391. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68392. /**
  68393. * ID of the blurX post process used for bloom,
  68394. */
  68395. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68396. /**
  68397. * ID of the blurY post process used for bloom,
  68398. */
  68399. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68400. /**
  68401. * ID of the copy back post process used for bloom,
  68402. */
  68403. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68404. /**
  68405. * ID of the image processing post process;
  68406. */
  68407. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68408. /**
  68409. * ID of the Fast Approximate Anti-Aliasing post process;
  68410. */
  68411. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68412. /**
  68413. * ID of the final merge post process;
  68414. */
  68415. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68416. /**
  68417. * ID of the chromatic aberration post process,
  68418. */
  68419. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68420. /**
  68421. * Animations which can be used to tweak settings over a period of time
  68422. */
  68423. _this.animations = [];
  68424. // Values
  68425. _this._sharpenEnabled = false;
  68426. _this._bloomEnabled = false;
  68427. _this._depthOfFieldEnabled = false;
  68428. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68429. _this._fxaaEnabled = false;
  68430. _this._msaaEnabled = false;
  68431. _this._imageProcessingEnabled = true;
  68432. _this._bloomScale = 0.6;
  68433. _this._chromaticAberrationEnabled = false;
  68434. _this._buildAllowed = true;
  68435. /**
  68436. * Specifies the size of the bloom blur kernel, relative to the final output size
  68437. */
  68438. _this.bloomKernel = 64;
  68439. /**
  68440. * Specifies the weight of the bloom in the final rendering
  68441. */
  68442. _this._bloomWeight = 0.15;
  68443. _this._prevPostProcess = null;
  68444. _this._prevPrevPostProcess = null;
  68445. _this._cameras = cameras || [];
  68446. _this._originalCameras = _this._cameras.slice();
  68447. _this._buildAllowed = automaticBuild;
  68448. // Initialize
  68449. _this._scene = scene;
  68450. var caps = _this._scene.getEngine().getCaps();
  68451. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68452. // Misc
  68453. if (_this._hdr) {
  68454. if (caps.textureHalfFloatRender) {
  68455. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68456. }
  68457. else if (caps.textureFloatRender) {
  68458. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68459. }
  68460. }
  68461. else {
  68462. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68463. }
  68464. // Attach
  68465. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68466. var engine = _this._scene.getEngine();
  68467. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  68468. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68469. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType);
  68470. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  68471. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68472. _this._buildPipeline();
  68473. return _this;
  68474. }
  68475. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68476. get: function () {
  68477. return this._sharpenEnabled;
  68478. },
  68479. /**
  68480. * Enable or disable the sharpen process from the pipeline
  68481. */
  68482. set: function (enabled) {
  68483. if (this._sharpenEnabled === enabled) {
  68484. return;
  68485. }
  68486. this._sharpenEnabled = enabled;
  68487. this._buildPipeline();
  68488. },
  68489. enumerable: true,
  68490. configurable: true
  68491. });
  68492. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68493. get: function () {
  68494. return this._bloomWeight;
  68495. },
  68496. /**
  68497. * The strength of the bloom.
  68498. */
  68499. set: function (value) {
  68500. if (this._bloomWeight === value) {
  68501. return;
  68502. }
  68503. this._bloomWeight = value;
  68504. if (this._hdr && this.copyBack) {
  68505. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68506. }
  68507. },
  68508. enumerable: true,
  68509. configurable: true
  68510. });
  68511. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68512. get: function () {
  68513. return this._bloomScale;
  68514. },
  68515. /**
  68516. * The scale of the bloom, lower value will provide better performance.
  68517. */
  68518. set: function (value) {
  68519. if (this._bloomScale === value) {
  68520. return;
  68521. }
  68522. this._bloomScale = value;
  68523. this._buildPipeline();
  68524. },
  68525. enumerable: true,
  68526. configurable: true
  68527. });
  68528. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68529. get: function () {
  68530. return this._bloomEnabled;
  68531. },
  68532. /**
  68533. * Enable or disable the bloom from the pipeline
  68534. */
  68535. set: function (enabled) {
  68536. if (this._bloomEnabled === enabled) {
  68537. return;
  68538. }
  68539. this._bloomEnabled = enabled;
  68540. this._buildPipeline();
  68541. },
  68542. enumerable: true,
  68543. configurable: true
  68544. });
  68545. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68546. /**
  68547. * If the depth of field is enabled.
  68548. */
  68549. get: function () {
  68550. return this._depthOfFieldEnabled;
  68551. },
  68552. set: function (enabled) {
  68553. if (this._depthOfFieldEnabled === enabled) {
  68554. return;
  68555. }
  68556. this._depthOfFieldEnabled = enabled;
  68557. this._buildPipeline();
  68558. },
  68559. enumerable: true,
  68560. configurable: true
  68561. });
  68562. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68563. /**
  68564. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68565. */
  68566. get: function () {
  68567. return this._depthOfFieldBlurLevel;
  68568. },
  68569. set: function (value) {
  68570. if (this._depthOfFieldBlurLevel === value) {
  68571. return;
  68572. }
  68573. this._depthOfFieldBlurLevel = value;
  68574. // recreate dof and dispose old as this setting is not dynamic
  68575. var oldDof = this.depthOfField;
  68576. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68577. this.depthOfField.focalLength = oldDof.focalLength;
  68578. this.depthOfField.focusDistance = oldDof.focusDistance;
  68579. this.depthOfField.fStop = oldDof.fStop;
  68580. this.depthOfField.lensSize = oldDof.lensSize;
  68581. for (var i = 0; i < this._cameras.length; i++) {
  68582. oldDof.disposeEffects(this._cameras[i]);
  68583. }
  68584. this._buildPipeline();
  68585. },
  68586. enumerable: true,
  68587. configurable: true
  68588. });
  68589. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68590. get: function () {
  68591. return this._fxaaEnabled;
  68592. },
  68593. /**
  68594. * If the anti aliasing is enabled.
  68595. */
  68596. set: function (enabled) {
  68597. if (this._fxaaEnabled === enabled) {
  68598. return;
  68599. }
  68600. this._fxaaEnabled = enabled;
  68601. this._buildPipeline();
  68602. },
  68603. enumerable: true,
  68604. configurable: true
  68605. });
  68606. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68607. get: function () {
  68608. return this._msaaEnabled;
  68609. },
  68610. /**
  68611. * If the multisample anti-aliasing is enabled.
  68612. */
  68613. set: function (enabled) {
  68614. if (this._msaaEnabled === enabled) {
  68615. return;
  68616. }
  68617. this._msaaEnabled = enabled;
  68618. this._buildPipeline();
  68619. },
  68620. enumerable: true,
  68621. configurable: true
  68622. });
  68623. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68624. get: function () {
  68625. return this._imageProcessingEnabled;
  68626. },
  68627. /**
  68628. * If image processing is enabled.
  68629. */
  68630. set: function (enabled) {
  68631. if (this._imageProcessingEnabled === enabled) {
  68632. return;
  68633. }
  68634. this._imageProcessingEnabled = enabled;
  68635. this._buildPipeline();
  68636. },
  68637. enumerable: true,
  68638. configurable: true
  68639. });
  68640. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68641. get: function () {
  68642. return this._chromaticAberrationEnabled;
  68643. },
  68644. /**
  68645. * Enable or disable the chromaticAberration process from the pipeline
  68646. */
  68647. set: function (enabled) {
  68648. if (this._chromaticAberrationEnabled === enabled) {
  68649. return;
  68650. }
  68651. this._chromaticAberrationEnabled = enabled;
  68652. this._buildPipeline();
  68653. },
  68654. enumerable: true,
  68655. configurable: true
  68656. });
  68657. /**
  68658. * Force the compilation of the entire pipeline.
  68659. */
  68660. DefaultRenderingPipeline.prototype.prepare = function () {
  68661. var previousState = this._buildAllowed;
  68662. this._buildAllowed = true;
  68663. this._buildPipeline();
  68664. this._buildAllowed = previousState;
  68665. };
  68666. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68667. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68668. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68669. postProcess.autoClear = false;
  68670. }
  68671. else {
  68672. postProcess.autoClear = true;
  68673. }
  68674. if (!skipTextureSharing) {
  68675. if (this._prevPrevPostProcess) {
  68676. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68677. }
  68678. else {
  68679. postProcess.useOwnOutput();
  68680. }
  68681. if (this._prevPostProcess) {
  68682. this._prevPrevPostProcess = this._prevPostProcess;
  68683. }
  68684. this._prevPostProcess = postProcess;
  68685. }
  68686. };
  68687. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68688. var _this = this;
  68689. if (!this._buildAllowed) {
  68690. return;
  68691. }
  68692. var engine = this._scene.getEngine();
  68693. this._disposePostProcesses();
  68694. if (this._cameras !== null) {
  68695. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68696. // get back cameras to be used to reattach pipeline
  68697. this._cameras = this._originalCameras.slice();
  68698. }
  68699. this._reset();
  68700. this._prevPostProcess = null;
  68701. this._prevPrevPostProcess = null;
  68702. if (this.sharpenEnabled) {
  68703. this.addEffect(this._sharpenEffect);
  68704. this._setAutoClearAndTextureSharing(this.sharpen);
  68705. }
  68706. if (this.depthOfFieldEnabled) {
  68707. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68708. this.depthOfField.depthTexture = depthTexture;
  68709. this.addEffect(this.depthOfField);
  68710. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68711. }
  68712. if (this.bloomEnabled) {
  68713. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68714. this._setAutoClearAndTextureSharing(this.pass, true);
  68715. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68716. if (!this._hdr) {
  68717. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68718. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68719. this.highlights.autoClear = false;
  68720. this.highlights.alwaysForcePOT = true;
  68721. }
  68722. 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);
  68723. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68724. this.blurX.alwaysForcePOT = true;
  68725. this.blurX.autoClear = false;
  68726. this.blurX.onActivateObservable.add(function () {
  68727. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68728. _this.blurX.kernel = _this.bloomKernel * dw;
  68729. });
  68730. 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);
  68731. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68732. this.blurY.alwaysForcePOT = true;
  68733. this.blurY.autoClear = false;
  68734. this.blurY.onActivateObservable.add(function () {
  68735. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68736. _this.blurY.kernel = _this.bloomKernel * dh;
  68737. });
  68738. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68739. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68740. this.copyBack.alwaysForcePOT = true;
  68741. if (this._hdr) {
  68742. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68743. var w = this.bloomWeight;
  68744. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68745. }
  68746. else {
  68747. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68748. }
  68749. this.copyBack.autoClear = false;
  68750. }
  68751. if (this._imageProcessingEnabled) {
  68752. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68753. if (this._hdr) {
  68754. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68755. }
  68756. else {
  68757. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68758. }
  68759. }
  68760. if (this._hdr && this.imageProcessing) {
  68761. this.finalMerge = this.imageProcessing;
  68762. }
  68763. else {
  68764. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68765. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68766. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  68767. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68768. }
  68769. if (this.bloomEnabled) {
  68770. if (this._hdr) {
  68771. this.copyBack.shareOutputWith(this.blurX);
  68772. if (this.imageProcessing) {
  68773. this.imageProcessing.shareOutputWith(this.pass);
  68774. this.imageProcessing.autoClear = false;
  68775. }
  68776. else {
  68777. this.finalMerge.shareOutputWith(this.pass);
  68778. }
  68779. }
  68780. else {
  68781. this.finalMerge.shareOutputWith(this.pass);
  68782. }
  68783. }
  68784. if (this.fxaaEnabled) {
  68785. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68786. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68787. this._setAutoClearAndTextureSharing(this.fxaa);
  68788. }
  68789. if (this.chromaticAberrationEnabled) {
  68790. this.addEffect(this._chromaticAberrationEffect);
  68791. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  68792. }
  68793. if (this._cameras !== null) {
  68794. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68795. }
  68796. if (this.msaaEnabled) {
  68797. if (!this._enableMSAAOnFirstPostProcess()) {
  68798. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68799. }
  68800. }
  68801. };
  68802. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  68803. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  68804. for (var i = 0; i < this._cameras.length; i++) {
  68805. var camera = this._cameras[i];
  68806. if (this.pass) {
  68807. this.pass.dispose(camera);
  68808. }
  68809. if (this.highlights) {
  68810. this.highlights.dispose(camera);
  68811. }
  68812. if (this.blurX) {
  68813. this.blurX.dispose(camera);
  68814. }
  68815. if (this.blurY) {
  68816. this.blurY.dispose(camera);
  68817. }
  68818. if (this.copyBack) {
  68819. this.copyBack.dispose(camera);
  68820. }
  68821. if (this.imageProcessing) {
  68822. this.imageProcessing.dispose(camera);
  68823. }
  68824. if (this.fxaa) {
  68825. this.fxaa.dispose(camera);
  68826. }
  68827. if (this.finalMerge) {
  68828. this.finalMerge.dispose(camera);
  68829. }
  68830. // These are created in the constructor and should not be disposed on every pipeline change
  68831. if (disposeNonRecreated) {
  68832. if (this.sharpen) {
  68833. this.sharpen.dispose(camera);
  68834. }
  68835. if (this.depthOfField) {
  68836. this.depthOfField.disposeEffects(camera);
  68837. }
  68838. if (this.chromaticAberration) {
  68839. this.chromaticAberration.dispose(camera);
  68840. }
  68841. }
  68842. }
  68843. this.pass = null;
  68844. this.highlights = null;
  68845. this.blurX = null;
  68846. this.blurY = null;
  68847. this.copyBack = null;
  68848. this.imageProcessing = null;
  68849. this.fxaa = null;
  68850. this.finalMerge = null;
  68851. if (disposeNonRecreated) {
  68852. this.sharpen = null;
  68853. this.depthOfField = null;
  68854. this.chromaticAberration = null;
  68855. }
  68856. };
  68857. /**
  68858. * Dispose of the pipeline and stop all post processes
  68859. */
  68860. DefaultRenderingPipeline.prototype.dispose = function () {
  68861. this._disposePostProcesses(true);
  68862. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68863. _super.prototype.dispose.call(this);
  68864. };
  68865. /**
  68866. * Serialize the rendering pipeline (Used when exporting)
  68867. * @returns the serialized object
  68868. */
  68869. DefaultRenderingPipeline.prototype.serialize = function () {
  68870. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68871. serializationObject.customType = "DefaultRenderingPipeline";
  68872. return serializationObject;
  68873. };
  68874. /**
  68875. * Parse the serialized pipeline
  68876. * @param source Source pipeline.
  68877. * @param scene The scene to load the pipeline to.
  68878. * @param rootUrl The URL of the serialized pipeline.
  68879. * @returns An instantiated pipeline from the serialized object.
  68880. */
  68881. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68882. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68883. };
  68884. __decorate([
  68885. BABYLON.serialize()
  68886. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68887. __decorate([
  68888. BABYLON.serialize()
  68889. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68890. __decorate([
  68891. BABYLON.serialize()
  68892. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68893. __decorate([
  68894. BABYLON.serialize()
  68895. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68896. __decorate([
  68897. BABYLON.serialize()
  68898. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68899. __decorate([
  68900. BABYLON.serialize()
  68901. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68902. __decorate([
  68903. BABYLON.serialize()
  68904. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68905. __decorate([
  68906. BABYLON.serialize()
  68907. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68908. __decorate([
  68909. BABYLON.serialize()
  68910. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68911. __decorate([
  68912. BABYLON.serialize()
  68913. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68914. __decorate([
  68915. BABYLON.serialize()
  68916. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68917. __decorate([
  68918. BABYLON.serialize()
  68919. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68920. __decorate([
  68921. BABYLON.serialize()
  68922. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  68923. return DefaultRenderingPipeline;
  68924. }(BABYLON.PostProcessRenderPipeline));
  68925. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68926. })(BABYLON || (BABYLON = {}));
  68927. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68928. var BABYLON;
  68929. (function (BABYLON) {
  68930. /**
  68931. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68932. */
  68933. var GeometryBufferRenderer = /** @class */ (function () {
  68934. /**
  68935. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68936. * @param scene The scene the buffer belongs to
  68937. * @param ratio How big is the buffer related to the main canvas.
  68938. */
  68939. function GeometryBufferRenderer(scene, ratio) {
  68940. if (ratio === void 0) { ratio = 1; }
  68941. this._enablePosition = false;
  68942. this._scene = scene;
  68943. this._ratio = ratio;
  68944. // Render target
  68945. this._createRenderTargets();
  68946. }
  68947. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68948. /**
  68949. * Set the render list (meshes to be rendered) used in the G buffer.
  68950. */
  68951. set: function (meshes) {
  68952. this._multiRenderTarget.renderList = meshes;
  68953. },
  68954. enumerable: true,
  68955. configurable: true
  68956. });
  68957. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68958. /**
  68959. * Gets wether or not G buffer are supported by the running hardware.
  68960. * This requires draw buffer supports
  68961. */
  68962. get: function () {
  68963. return this._multiRenderTarget.isSupported;
  68964. },
  68965. enumerable: true,
  68966. configurable: true
  68967. });
  68968. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68969. /**
  68970. * Gets wether or not position are enabled for the G buffer.
  68971. */
  68972. get: function () {
  68973. return this._enablePosition;
  68974. },
  68975. /**
  68976. * Sets wether or not position are enabled for the G buffer.
  68977. */
  68978. set: function (enable) {
  68979. this._enablePosition = enable;
  68980. this.dispose();
  68981. this._createRenderTargets();
  68982. },
  68983. enumerable: true,
  68984. configurable: true
  68985. });
  68986. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68987. /**
  68988. * Gets the scene associated with the buffer.
  68989. */
  68990. get: function () {
  68991. return this._scene;
  68992. },
  68993. enumerable: true,
  68994. configurable: true
  68995. });
  68996. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68997. /**
  68998. * Gets the ratio used by the buffer during its creation.
  68999. * How big is the buffer related to the main canvas.
  69000. */
  69001. get: function () {
  69002. return this._ratio;
  69003. },
  69004. enumerable: true,
  69005. configurable: true
  69006. });
  69007. /**
  69008. * Checks wether everything is ready to render a submesh to the G buffer.
  69009. * @param subMesh the submesh to check readiness for
  69010. * @param useInstances is the mesh drawn using instance or not
  69011. * @returns true if ready otherwise false
  69012. */
  69013. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69014. var material = subMesh.getMaterial();
  69015. if (material && material.disableDepthWrite) {
  69016. return false;
  69017. }
  69018. var defines = [];
  69019. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69020. var mesh = subMesh.getMesh();
  69021. // Alpha test
  69022. if (material && material.needAlphaTesting()) {
  69023. defines.push("#define ALPHATEST");
  69024. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69025. attribs.push(BABYLON.VertexBuffer.UVKind);
  69026. defines.push("#define UV1");
  69027. }
  69028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69030. defines.push("#define UV2");
  69031. }
  69032. }
  69033. // Buffers
  69034. if (this._enablePosition) {
  69035. defines.push("#define POSITION");
  69036. }
  69037. // Bones
  69038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69041. if (mesh.numBoneInfluencers > 4) {
  69042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69044. }
  69045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69046. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69047. }
  69048. else {
  69049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69050. }
  69051. // Instances
  69052. if (useInstances) {
  69053. defines.push("#define INSTANCES");
  69054. attribs.push("world0");
  69055. attribs.push("world1");
  69056. attribs.push("world2");
  69057. attribs.push("world3");
  69058. }
  69059. // Get correct effect
  69060. var join = defines.join("\n");
  69061. if (this._cachedDefines !== join) {
  69062. this._cachedDefines = join;
  69063. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69064. }
  69065. return this._effect.isReady();
  69066. };
  69067. /**
  69068. * Gets the current underlying G Buffer.
  69069. * @returns the buffer
  69070. */
  69071. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69072. return this._multiRenderTarget;
  69073. };
  69074. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69075. /**
  69076. * Gets the number of samples used to render the buffer (anti aliasing).
  69077. */
  69078. get: function () {
  69079. return this._multiRenderTarget.samples;
  69080. },
  69081. /**
  69082. * Sets the number of samples used to render the buffer (anti aliasing).
  69083. */
  69084. set: function (value) {
  69085. this._multiRenderTarget.samples = value;
  69086. },
  69087. enumerable: true,
  69088. configurable: true
  69089. });
  69090. /**
  69091. * Disposes the renderer and frees up associated resources.
  69092. */
  69093. GeometryBufferRenderer.prototype.dispose = function () {
  69094. this.getGBuffer().dispose();
  69095. };
  69096. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69097. var _this = this;
  69098. var engine = this._scene.getEngine();
  69099. var count = this._enablePosition ? 3 : 2;
  69100. 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 });
  69101. if (!this.isSupported) {
  69102. return;
  69103. }
  69104. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69105. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69106. this._multiRenderTarget.refreshRate = 1;
  69107. this._multiRenderTarget.renderParticles = false;
  69108. this._multiRenderTarget.renderList = null;
  69109. // set default depth value to 1.0 (far away)
  69110. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69111. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69112. });
  69113. // Custom render function
  69114. var renderSubMesh = function (subMesh) {
  69115. var mesh = subMesh.getRenderingMesh();
  69116. var scene = _this._scene;
  69117. var engine = scene.getEngine();
  69118. var material = subMesh.getMaterial();
  69119. if (!material) {
  69120. return;
  69121. }
  69122. // Culling
  69123. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69124. // Managing instances
  69125. var batch = mesh._getInstancesRenderList(subMesh._id);
  69126. if (batch.mustReturn) {
  69127. return;
  69128. }
  69129. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69130. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69131. engine.enableEffect(_this._effect);
  69132. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69133. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69134. _this._effect.setMatrix("view", scene.getViewMatrix());
  69135. // Alpha test
  69136. if (material && material.needAlphaTesting()) {
  69137. var alphaTexture = material.getAlphaTestTexture();
  69138. if (alphaTexture) {
  69139. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69140. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69141. }
  69142. }
  69143. // Bones
  69144. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69145. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69146. }
  69147. // Draw
  69148. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69149. }
  69150. };
  69151. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69152. var index;
  69153. if (depthOnlySubMeshes.length) {
  69154. engine.setColorWrite(false);
  69155. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69156. renderSubMesh(depthOnlySubMeshes.data[index]);
  69157. }
  69158. engine.setColorWrite(true);
  69159. }
  69160. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69161. renderSubMesh(opaqueSubMeshes.data[index]);
  69162. }
  69163. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69164. renderSubMesh(alphaTestSubMeshes.data[index]);
  69165. }
  69166. };
  69167. };
  69168. return GeometryBufferRenderer;
  69169. }());
  69170. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69171. })(BABYLON || (BABYLON = {}));
  69172. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69173. var BABYLON;
  69174. (function (BABYLON) {
  69175. var RefractionPostProcess = /** @class */ (function (_super) {
  69176. __extends(RefractionPostProcess, _super);
  69177. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69178. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69179. _this.color = color;
  69180. _this.depth = depth;
  69181. _this.colorLevel = colorLevel;
  69182. _this._ownRefractionTexture = true;
  69183. _this.onActivateObservable.add(function (cam) {
  69184. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69185. });
  69186. _this.onApplyObservable.add(function (effect) {
  69187. effect.setColor3("baseColor", _this.color);
  69188. effect.setFloat("depth", _this.depth);
  69189. effect.setFloat("colorLevel", _this.colorLevel);
  69190. effect.setTexture("refractionSampler", _this._refTexture);
  69191. });
  69192. return _this;
  69193. }
  69194. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69195. /**
  69196. * Gets or sets the refraction texture
  69197. * Please note that you are responsible for disposing the texture if you set it manually
  69198. */
  69199. get: function () {
  69200. return this._refTexture;
  69201. },
  69202. set: function (value) {
  69203. if (this._refTexture && this._ownRefractionTexture) {
  69204. this._refTexture.dispose();
  69205. }
  69206. this._refTexture = value;
  69207. this._ownRefractionTexture = false;
  69208. },
  69209. enumerable: true,
  69210. configurable: true
  69211. });
  69212. // Methods
  69213. RefractionPostProcess.prototype.dispose = function (camera) {
  69214. if (this._refTexture && this._ownRefractionTexture) {
  69215. this._refTexture.dispose();
  69216. this._refTexture = null;
  69217. }
  69218. _super.prototype.dispose.call(this, camera);
  69219. };
  69220. return RefractionPostProcess;
  69221. }(BABYLON.PostProcess));
  69222. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69223. })(BABYLON || (BABYLON = {}));
  69224. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69225. var BABYLON;
  69226. (function (BABYLON) {
  69227. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69228. __extends(BlackAndWhitePostProcess, _super);
  69229. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69230. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69231. _this.degree = 1;
  69232. _this.onApplyObservable.add(function (effect) {
  69233. effect.setFloat("degree", _this.degree);
  69234. });
  69235. return _this;
  69236. }
  69237. return BlackAndWhitePostProcess;
  69238. }(BABYLON.PostProcess));
  69239. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69240. })(BABYLON || (BABYLON = {}));
  69241. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69242. var BABYLON;
  69243. (function (BABYLON) {
  69244. /**
  69245. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69246. * input texture to perform effects such as edge detection or sharpening
  69247. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69248. */
  69249. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69250. __extends(ConvolutionPostProcess, _super);
  69251. /**
  69252. * Creates a new instance of @see ConvolutionPostProcess
  69253. * @param name The name of the effect.
  69254. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69255. * @param options The required width/height ratio to downsize to before computing the render pass.
  69256. * @param camera The camera to apply the render pass to.
  69257. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69258. * @param engine The engine which the post process will be applied. (default: current engine)
  69259. * @param reusable If the post process can be reused on the same frame. (default: false)
  69260. * @param textureType Type of textures used when performing the post process. (default: 0)
  69261. */
  69262. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69264. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69265. _this.kernel = kernel;
  69266. _this.onApply = function (effect) {
  69267. effect.setFloat2("screenSize", _this.width, _this.height);
  69268. effect.setArray("kernel", _this.kernel);
  69269. };
  69270. return _this;
  69271. }
  69272. // Statics
  69273. /**
  69274. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69275. */
  69276. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69277. /**
  69278. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69279. */
  69280. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69281. /**
  69282. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69283. */
  69284. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69285. /**
  69286. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69287. */
  69288. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69289. /**
  69290. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69291. */
  69292. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69293. /**
  69294. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69295. */
  69296. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69297. return ConvolutionPostProcess;
  69298. }(BABYLON.PostProcess));
  69299. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69300. })(BABYLON || (BABYLON = {}));
  69301. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69302. var BABYLON;
  69303. (function (BABYLON) {
  69304. var FilterPostProcess = /** @class */ (function (_super) {
  69305. __extends(FilterPostProcess, _super);
  69306. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69307. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69308. _this.kernelMatrix = kernelMatrix;
  69309. _this.onApply = function (effect) {
  69310. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69311. };
  69312. return _this;
  69313. }
  69314. return FilterPostProcess;
  69315. }(BABYLON.PostProcess));
  69316. BABYLON.FilterPostProcess = FilterPostProcess;
  69317. })(BABYLON || (BABYLON = {}));
  69318. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69319. var BABYLON;
  69320. (function (BABYLON) {
  69321. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69322. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69323. __extends(VolumetricLightScatteringPostProcess, _super);
  69324. /**
  69325. * @constructor
  69326. * @param {string} name - The post-process name
  69327. * @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)
  69328. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69329. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69330. * @param {number} samples - The post-process quality, default 100
  69331. * @param {number} samplingMode - The post-process filtering mode
  69332. * @param {BABYLON.Engine} engine - The babylon engine
  69333. * @param {boolean} reusable - If the post-process is reusable
  69334. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69335. */
  69336. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69337. if (samples === void 0) { samples = 100; }
  69338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69339. 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;
  69340. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69341. /**
  69342. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69343. * @type {Vector3}
  69344. */
  69345. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69346. /**
  69347. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69348. * @type {boolean}
  69349. */
  69350. _this.useCustomMeshPosition = false;
  69351. /**
  69352. * If the post-process should inverse the light scattering direction
  69353. * @type {boolean}
  69354. */
  69355. _this.invert = true;
  69356. /**
  69357. * Array containing the excluded meshes not rendered in the internal pass
  69358. */
  69359. _this.excludedMeshes = new Array();
  69360. /**
  69361. * Controls the overall intensity of the post-process
  69362. * @type {number}
  69363. */
  69364. _this.exposure = 0.3;
  69365. /**
  69366. * Dissipates each sample's contribution in range [0, 1]
  69367. * @type {number}
  69368. */
  69369. _this.decay = 0.96815;
  69370. /**
  69371. * Controls the overall intensity of each sample
  69372. * @type {number}
  69373. */
  69374. _this.weight = 0.58767;
  69375. /**
  69376. * Controls the density of each sample
  69377. * @type {number}
  69378. */
  69379. _this.density = 0.926;
  69380. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69381. engine = scene.getEngine();
  69382. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69383. // Configure mesh
  69384. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69385. // Configure
  69386. _this._createPass(scene, ratio.passRatio || ratio);
  69387. _this.onActivate = function (camera) {
  69388. if (!_this.isSupported) {
  69389. _this.dispose(camera);
  69390. }
  69391. _this.onActivate = null;
  69392. };
  69393. _this.onApplyObservable.add(function (effect) {
  69394. _this._updateMeshScreenCoordinates(scene);
  69395. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69396. effect.setFloat("exposure", _this.exposure);
  69397. effect.setFloat("decay", _this.decay);
  69398. effect.setFloat("weight", _this.weight);
  69399. effect.setFloat("density", _this.density);
  69400. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69401. });
  69402. return _this;
  69403. }
  69404. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69405. get: function () {
  69406. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69407. return false;
  69408. },
  69409. set: function (useDiffuseColor) {
  69410. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69411. },
  69412. enumerable: true,
  69413. configurable: true
  69414. });
  69415. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69416. return "VolumetricLightScatteringPostProcess";
  69417. };
  69418. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69419. var mesh = subMesh.getMesh();
  69420. // Render this.mesh as default
  69421. if (mesh === this.mesh && mesh.material) {
  69422. return mesh.material.isReady(mesh);
  69423. }
  69424. var defines = [];
  69425. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69426. var material = subMesh.getMaterial();
  69427. // Alpha test
  69428. if (material) {
  69429. if (material.needAlphaTesting()) {
  69430. defines.push("#define ALPHATEST");
  69431. }
  69432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69433. attribs.push(BABYLON.VertexBuffer.UVKind);
  69434. defines.push("#define UV1");
  69435. }
  69436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69437. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69438. defines.push("#define UV2");
  69439. }
  69440. }
  69441. // Bones
  69442. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69443. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69444. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69445. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69446. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69447. }
  69448. else {
  69449. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69450. }
  69451. // Instances
  69452. if (useInstances) {
  69453. defines.push("#define INSTANCES");
  69454. attribs.push("world0");
  69455. attribs.push("world1");
  69456. attribs.push("world2");
  69457. attribs.push("world3");
  69458. }
  69459. // Get correct effect
  69460. var join = defines.join("\n");
  69461. if (this._cachedDefines !== join) {
  69462. this._cachedDefines = join;
  69463. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69464. }
  69465. return this._volumetricLightScatteringPass.isReady();
  69466. };
  69467. /**
  69468. * Sets the new light position for light scattering effect
  69469. * @param {BABYLON.Vector3} The new custom light position
  69470. */
  69471. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69472. this.customMeshPosition = position;
  69473. };
  69474. /**
  69475. * Returns the light position for light scattering effect
  69476. * @return {BABYLON.Vector3} The custom light position
  69477. */
  69478. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69479. return this.customMeshPosition;
  69480. };
  69481. /**
  69482. * Disposes the internal assets and detaches the post-process from the camera
  69483. */
  69484. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69485. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69486. if (rttIndex !== -1) {
  69487. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69488. }
  69489. this._volumetricLightScatteringRTT.dispose();
  69490. _super.prototype.dispose.call(this, camera);
  69491. };
  69492. /**
  69493. * Returns the render target texture used by the post-process
  69494. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69495. */
  69496. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69497. return this._volumetricLightScatteringRTT;
  69498. };
  69499. // Private methods
  69500. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69501. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69502. return true;
  69503. }
  69504. return false;
  69505. };
  69506. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69507. var _this = this;
  69508. var engine = scene.getEngine();
  69509. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69510. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69511. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69512. this._volumetricLightScatteringRTT.renderList = null;
  69513. this._volumetricLightScatteringRTT.renderParticles = false;
  69514. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69515. var camera = this.getCamera();
  69516. if (camera) {
  69517. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69518. }
  69519. else {
  69520. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69521. }
  69522. // Custom render function for submeshes
  69523. var renderSubMesh = function (subMesh) {
  69524. var mesh = subMesh.getRenderingMesh();
  69525. if (_this._meshExcluded(mesh)) {
  69526. return;
  69527. }
  69528. var material = subMesh.getMaterial();
  69529. if (!material) {
  69530. return;
  69531. }
  69532. var scene = mesh.getScene();
  69533. var engine = scene.getEngine();
  69534. // Culling
  69535. engine.setState(material.backFaceCulling);
  69536. // Managing instances
  69537. var batch = mesh._getInstancesRenderList(subMesh._id);
  69538. if (batch.mustReturn) {
  69539. return;
  69540. }
  69541. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69542. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69543. var effect = _this._volumetricLightScatteringPass;
  69544. if (mesh === _this.mesh) {
  69545. if (subMesh.effect) {
  69546. effect = subMesh.effect;
  69547. }
  69548. else {
  69549. effect = material.getEffect();
  69550. }
  69551. }
  69552. engine.enableEffect(effect);
  69553. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69554. if (mesh === _this.mesh) {
  69555. material.bind(mesh.getWorldMatrix(), mesh);
  69556. }
  69557. else {
  69558. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69559. // Alpha test
  69560. if (material && material.needAlphaTesting()) {
  69561. var alphaTexture = material.getAlphaTestTexture();
  69562. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69563. if (alphaTexture) {
  69564. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69565. }
  69566. }
  69567. // Bones
  69568. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69569. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69570. }
  69571. }
  69572. // Draw
  69573. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69574. }
  69575. };
  69576. // Render target texture callbacks
  69577. var savedSceneClearColor;
  69578. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69579. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69580. savedSceneClearColor = scene.clearColor;
  69581. scene.clearColor = sceneClearColor;
  69582. });
  69583. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69584. scene.clearColor = savedSceneClearColor;
  69585. });
  69586. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69587. var engine = scene.getEngine();
  69588. var index;
  69589. if (depthOnlySubMeshes.length) {
  69590. engine.setColorWrite(false);
  69591. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69592. renderSubMesh(depthOnlySubMeshes.data[index]);
  69593. }
  69594. engine.setColorWrite(true);
  69595. }
  69596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69597. renderSubMesh(opaqueSubMeshes.data[index]);
  69598. }
  69599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69600. renderSubMesh(alphaTestSubMeshes.data[index]);
  69601. }
  69602. if (transparentSubMeshes.length) {
  69603. // Sort sub meshes
  69604. for (index = 0; index < transparentSubMeshes.length; index++) {
  69605. var submesh = transparentSubMeshes.data[index];
  69606. var boundingInfo = submesh.getBoundingInfo();
  69607. if (boundingInfo && scene.activeCamera) {
  69608. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69609. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69610. }
  69611. }
  69612. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69613. sortedArray.sort(function (a, b) {
  69614. // Alpha index first
  69615. if (a._alphaIndex > b._alphaIndex) {
  69616. return 1;
  69617. }
  69618. if (a._alphaIndex < b._alphaIndex) {
  69619. return -1;
  69620. }
  69621. // Then distance to camera
  69622. if (a._distanceToCamera < b._distanceToCamera) {
  69623. return 1;
  69624. }
  69625. if (a._distanceToCamera > b._distanceToCamera) {
  69626. return -1;
  69627. }
  69628. return 0;
  69629. });
  69630. // Render sub meshes
  69631. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69632. for (index = 0; index < sortedArray.length; index++) {
  69633. renderSubMesh(sortedArray[index]);
  69634. }
  69635. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69636. }
  69637. };
  69638. };
  69639. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69640. var transform = scene.getTransformMatrix();
  69641. var meshPosition;
  69642. if (this.useCustomMeshPosition) {
  69643. meshPosition = this.customMeshPosition;
  69644. }
  69645. else if (this.attachedNode) {
  69646. meshPosition = this.attachedNode.position;
  69647. }
  69648. else {
  69649. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69650. }
  69651. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69652. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69653. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69654. if (this.invert)
  69655. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69656. };
  69657. // Static methods
  69658. /**
  69659. * Creates a default mesh for the Volumeric Light Scattering post-process
  69660. * @param {string} The mesh name
  69661. * @param {BABYLON.Scene} The scene where to create the mesh
  69662. * @return {BABYLON.Mesh} the default mesh
  69663. */
  69664. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69665. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69666. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69667. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69668. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69669. mesh.material = material;
  69670. return mesh;
  69671. };
  69672. __decorate([
  69673. BABYLON.serializeAsVector3()
  69674. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69675. __decorate([
  69676. BABYLON.serialize()
  69677. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69678. __decorate([
  69679. BABYLON.serialize()
  69680. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69681. __decorate([
  69682. BABYLON.serializeAsMeshReference()
  69683. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69684. __decorate([
  69685. BABYLON.serialize()
  69686. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69687. __decorate([
  69688. BABYLON.serialize()
  69689. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69690. __decorate([
  69691. BABYLON.serialize()
  69692. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69693. __decorate([
  69694. BABYLON.serialize()
  69695. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69696. __decorate([
  69697. BABYLON.serialize()
  69698. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69699. return VolumetricLightScatteringPostProcess;
  69700. }(BABYLON.PostProcess));
  69701. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69702. })(BABYLON || (BABYLON = {}));
  69703. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69704. //
  69705. // This post-process allows the modification of rendered colors by using
  69706. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69707. //
  69708. // The object needs to be provided an url to a texture containing the color
  69709. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69710. // Use an image editing software to tweak the LUT to match your needs.
  69711. //
  69712. // For an example of a color LUT, see here:
  69713. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69714. // For explanations on color grading, see here:
  69715. // http://udn.epicgames.com/Three/ColorGrading.html
  69716. //
  69717. var BABYLON;
  69718. (function (BABYLON) {
  69719. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69720. __extends(ColorCorrectionPostProcess, _super);
  69721. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69722. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69723. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69724. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69725. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69726. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69727. _this.onApply = function (effect) {
  69728. effect.setTexture("colorTable", _this._colorTableTexture);
  69729. };
  69730. return _this;
  69731. }
  69732. return ColorCorrectionPostProcess;
  69733. }(BABYLON.PostProcess));
  69734. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69735. })(BABYLON || (BABYLON = {}));
  69736. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69737. var BABYLON;
  69738. (function (BABYLON) {
  69739. var TonemappingOperator;
  69740. (function (TonemappingOperator) {
  69741. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69742. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69743. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69744. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69745. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69746. ;
  69747. var TonemapPostProcess = /** @class */ (function (_super) {
  69748. __extends(TonemapPostProcess, _super);
  69749. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69751. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69752. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69753. _this._operator = _operator;
  69754. _this.exposureAdjustment = exposureAdjustment;
  69755. var defines = "#define ";
  69756. if (_this._operator === TonemappingOperator.Hable)
  69757. defines += "HABLE_TONEMAPPING";
  69758. else if (_this._operator === TonemappingOperator.Reinhard)
  69759. defines += "REINHARD_TONEMAPPING";
  69760. else if (_this._operator === TonemappingOperator.HejiDawson)
  69761. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69762. else if (_this._operator === TonemappingOperator.Photographic)
  69763. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69764. //sadly a second call to create the effect.
  69765. _this.updateEffect(defines);
  69766. _this.onApply = function (effect) {
  69767. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69768. };
  69769. return _this;
  69770. }
  69771. return TonemapPostProcess;
  69772. }(BABYLON.PostProcess));
  69773. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69774. })(BABYLON || (BABYLON = {}));
  69775. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69776. var BABYLON;
  69777. (function (BABYLON) {
  69778. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69779. __extends(DisplayPassPostProcess, _super);
  69780. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69781. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69782. }
  69783. return DisplayPassPostProcess;
  69784. }(BABYLON.PostProcess));
  69785. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69786. })(BABYLON || (BABYLON = {}));
  69787. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69788. var BABYLON;
  69789. (function (BABYLON) {
  69790. var HighlightsPostProcess = /** @class */ (function (_super) {
  69791. __extends(HighlightsPostProcess, _super);
  69792. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69793. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69794. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69795. }
  69796. return HighlightsPostProcess;
  69797. }(BABYLON.PostProcess));
  69798. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69799. })(BABYLON || (BABYLON = {}));
  69800. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69801. var BABYLON;
  69802. (function (BABYLON) {
  69803. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69804. __extends(ImageProcessingPostProcess, _super);
  69805. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69806. if (camera === void 0) { camera = null; }
  69807. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69808. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69809. _this._fromLinearSpace = true;
  69810. /**
  69811. * Defines cache preventing GC.
  69812. */
  69813. _this._defines = {
  69814. IMAGEPROCESSING: false,
  69815. VIGNETTE: false,
  69816. VIGNETTEBLENDMODEMULTIPLY: false,
  69817. VIGNETTEBLENDMODEOPAQUE: false,
  69818. TONEMAPPING: false,
  69819. CONTRAST: false,
  69820. COLORCURVES: false,
  69821. COLORGRADING: false,
  69822. COLORGRADING3D: false,
  69823. FROMLINEARSPACE: false,
  69824. SAMPLER3DGREENDEPTH: false,
  69825. SAMPLER3DBGRMAP: false,
  69826. IMAGEPROCESSINGPOSTPROCESS: false,
  69827. EXPOSURE: false,
  69828. GRAIN: false,
  69829. };
  69830. // Setup the configuration as forced by the constructor. This would then not force the
  69831. // scene materials output in linear space and let untouched the default forward pass.
  69832. if (imageProcessingConfiguration) {
  69833. imageProcessingConfiguration.applyByPostProcess = true;
  69834. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69835. // This will cause the shader to be compiled
  69836. _this.fromLinearSpace = false;
  69837. }
  69838. else {
  69839. _this._attachImageProcessingConfiguration(null, true);
  69840. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69841. }
  69842. _this.onApply = function (effect) {
  69843. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69844. };
  69845. return _this;
  69846. }
  69847. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69848. /**
  69849. * Gets the image processing configuration used either in this material.
  69850. */
  69851. get: function () {
  69852. return this._imageProcessingConfiguration;
  69853. },
  69854. /**
  69855. * Sets the Default image processing configuration used either in the this material.
  69856. *
  69857. * If sets to null, the scene one is in use.
  69858. */
  69859. set: function (value) {
  69860. this._attachImageProcessingConfiguration(value);
  69861. },
  69862. enumerable: true,
  69863. configurable: true
  69864. });
  69865. /**
  69866. * Attaches a new image processing configuration to the PBR Material.
  69867. * @param configuration
  69868. */
  69869. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69870. var _this = this;
  69871. if (doNotBuild === void 0) { doNotBuild = false; }
  69872. if (configuration === this._imageProcessingConfiguration) {
  69873. return;
  69874. }
  69875. // Detaches observer.
  69876. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69877. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69878. }
  69879. // Pick the scene configuration if needed.
  69880. if (!configuration) {
  69881. var scene = null;
  69882. var engine = this.getEngine();
  69883. var camera = this.getCamera();
  69884. if (camera) {
  69885. scene = camera.getScene();
  69886. }
  69887. else if (engine && engine.scenes) {
  69888. var scenes = engine.scenes;
  69889. scene = scenes[scenes.length - 1];
  69890. }
  69891. else {
  69892. scene = BABYLON.Engine.LastCreatedScene;
  69893. }
  69894. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69895. }
  69896. else {
  69897. this._imageProcessingConfiguration = configuration;
  69898. }
  69899. // Attaches observer.
  69900. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69901. _this._updateParameters();
  69902. });
  69903. // Ensure the effect will be rebuilt.
  69904. if (!doNotBuild) {
  69905. this._updateParameters();
  69906. }
  69907. };
  69908. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69909. /**
  69910. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69911. */
  69912. get: function () {
  69913. return this.imageProcessingConfiguration.colorCurves;
  69914. },
  69915. /**
  69916. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69917. */
  69918. set: function (value) {
  69919. this.imageProcessingConfiguration.colorCurves = value;
  69920. },
  69921. enumerable: true,
  69922. configurable: true
  69923. });
  69924. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69925. /**
  69926. * Gets wether the color curves effect is enabled.
  69927. */
  69928. get: function () {
  69929. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69930. },
  69931. /**
  69932. * Sets wether the color curves effect is enabled.
  69933. */
  69934. set: function (value) {
  69935. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69936. },
  69937. enumerable: true,
  69938. configurable: true
  69939. });
  69940. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69941. /**
  69942. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69943. */
  69944. get: function () {
  69945. return this.imageProcessingConfiguration.colorGradingTexture;
  69946. },
  69947. /**
  69948. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69949. */
  69950. set: function (value) {
  69951. this.imageProcessingConfiguration.colorGradingTexture = value;
  69952. },
  69953. enumerable: true,
  69954. configurable: true
  69955. });
  69956. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69957. /**
  69958. * Gets wether the color grading effect is enabled.
  69959. */
  69960. get: function () {
  69961. return this.imageProcessingConfiguration.colorGradingEnabled;
  69962. },
  69963. /**
  69964. * Gets wether the color grading effect is enabled.
  69965. */
  69966. set: function (value) {
  69967. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69968. },
  69969. enumerable: true,
  69970. configurable: true
  69971. });
  69972. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69973. /**
  69974. * Gets exposure used in the effect.
  69975. */
  69976. get: function () {
  69977. return this.imageProcessingConfiguration.exposure;
  69978. },
  69979. /**
  69980. * Sets exposure used in the effect.
  69981. */
  69982. set: function (value) {
  69983. this.imageProcessingConfiguration.exposure = value;
  69984. },
  69985. enumerable: true,
  69986. configurable: true
  69987. });
  69988. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69989. /**
  69990. * Gets wether tonemapping is enabled or not.
  69991. */
  69992. get: function () {
  69993. return this._imageProcessingConfiguration.toneMappingEnabled;
  69994. },
  69995. /**
  69996. * Sets wether tonemapping is enabled or not
  69997. */
  69998. set: function (value) {
  69999. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70000. },
  70001. enumerable: true,
  70002. configurable: true
  70003. });
  70004. ;
  70005. ;
  70006. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70007. /**
  70008. * Gets contrast used in the effect.
  70009. */
  70010. get: function () {
  70011. return this.imageProcessingConfiguration.contrast;
  70012. },
  70013. /**
  70014. * Sets contrast used in the effect.
  70015. */
  70016. set: function (value) {
  70017. this.imageProcessingConfiguration.contrast = value;
  70018. },
  70019. enumerable: true,
  70020. configurable: true
  70021. });
  70022. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70023. /**
  70024. * Gets Vignette stretch size.
  70025. */
  70026. get: function () {
  70027. return this.imageProcessingConfiguration.vignetteStretch;
  70028. },
  70029. /**
  70030. * Sets Vignette stretch size.
  70031. */
  70032. set: function (value) {
  70033. this.imageProcessingConfiguration.vignetteStretch = value;
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70039. /**
  70040. * Gets Vignette centre X Offset.
  70041. */
  70042. get: function () {
  70043. return this.imageProcessingConfiguration.vignetteCentreX;
  70044. },
  70045. /**
  70046. * Sets Vignette centre X Offset.
  70047. */
  70048. set: function (value) {
  70049. this.imageProcessingConfiguration.vignetteCentreX = value;
  70050. },
  70051. enumerable: true,
  70052. configurable: true
  70053. });
  70054. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70055. /**
  70056. * Gets Vignette centre Y Offset.
  70057. */
  70058. get: function () {
  70059. return this.imageProcessingConfiguration.vignetteCentreY;
  70060. },
  70061. /**
  70062. * Sets Vignette centre Y Offset.
  70063. */
  70064. set: function (value) {
  70065. this.imageProcessingConfiguration.vignetteCentreY = value;
  70066. },
  70067. enumerable: true,
  70068. configurable: true
  70069. });
  70070. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70071. /**
  70072. * Gets Vignette weight or intensity of the vignette effect.
  70073. */
  70074. get: function () {
  70075. return this.imageProcessingConfiguration.vignetteWeight;
  70076. },
  70077. /**
  70078. * Sets Vignette weight or intensity of the vignette effect.
  70079. */
  70080. set: function (value) {
  70081. this.imageProcessingConfiguration.vignetteWeight = value;
  70082. },
  70083. enumerable: true,
  70084. configurable: true
  70085. });
  70086. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70087. /**
  70088. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70089. * if vignetteEnabled is set to true.
  70090. */
  70091. get: function () {
  70092. return this.imageProcessingConfiguration.vignetteColor;
  70093. },
  70094. /**
  70095. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70096. * if vignetteEnabled is set to true.
  70097. */
  70098. set: function (value) {
  70099. this.imageProcessingConfiguration.vignetteColor = value;
  70100. },
  70101. enumerable: true,
  70102. configurable: true
  70103. });
  70104. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70105. /**
  70106. * Gets Camera field of view used by the Vignette effect.
  70107. */
  70108. get: function () {
  70109. return this.imageProcessingConfiguration.vignetteCameraFov;
  70110. },
  70111. /**
  70112. * Sets Camera field of view used by the Vignette effect.
  70113. */
  70114. set: function (value) {
  70115. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70116. },
  70117. enumerable: true,
  70118. configurable: true
  70119. });
  70120. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70121. /**
  70122. * Gets the vignette blend mode allowing different kind of effect.
  70123. */
  70124. get: function () {
  70125. return this.imageProcessingConfiguration.vignetteBlendMode;
  70126. },
  70127. /**
  70128. * Sets the vignette blend mode allowing different kind of effect.
  70129. */
  70130. set: function (value) {
  70131. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70132. },
  70133. enumerable: true,
  70134. configurable: true
  70135. });
  70136. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70137. /**
  70138. * Gets wether the vignette effect is enabled.
  70139. */
  70140. get: function () {
  70141. return this.imageProcessingConfiguration.vignetteEnabled;
  70142. },
  70143. /**
  70144. * Sets wether the vignette effect is enabled.
  70145. */
  70146. set: function (value) {
  70147. this.imageProcessingConfiguration.vignetteEnabled = value;
  70148. },
  70149. enumerable: true,
  70150. configurable: true
  70151. });
  70152. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70153. /**
  70154. * Gets wether the grain effect is enabled.
  70155. */
  70156. get: function () {
  70157. return this.imageProcessingConfiguration.grainEnabled;
  70158. },
  70159. /**
  70160. * Sets wether the grain effect is enabled.
  70161. */
  70162. set: function (value) {
  70163. this.imageProcessingConfiguration.grainEnabled = value;
  70164. },
  70165. enumerable: true,
  70166. configurable: true
  70167. });
  70168. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70169. /**
  70170. * Gets the grain effect's intensity.
  70171. */
  70172. get: function () {
  70173. return this.imageProcessingConfiguration.grainIntensity;
  70174. },
  70175. /**
  70176. * Sets the grain effect's intensity.
  70177. */
  70178. set: function (value) {
  70179. this.imageProcessingConfiguration.grainIntensity = value;
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70185. /**
  70186. * Gets wether the grain effect is animated.
  70187. */
  70188. get: function () {
  70189. return this.imageProcessingConfiguration.grainAnimated;
  70190. },
  70191. /**
  70192. * Sets wether the grain effect is animated.
  70193. */
  70194. set: function (value) {
  70195. this.imageProcessingConfiguration.grainAnimated = value;
  70196. },
  70197. enumerable: true,
  70198. configurable: true
  70199. });
  70200. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70201. /**
  70202. * Gets wether the input of the processing is in Gamma or Linear Space.
  70203. */
  70204. get: function () {
  70205. return this._fromLinearSpace;
  70206. },
  70207. /**
  70208. * Sets wether the input of the processing is in Gamma or Linear Space.
  70209. */
  70210. set: function (value) {
  70211. if (this._fromLinearSpace === value) {
  70212. return;
  70213. }
  70214. this._fromLinearSpace = value;
  70215. this._updateParameters();
  70216. },
  70217. enumerable: true,
  70218. configurable: true
  70219. });
  70220. ImageProcessingPostProcess.prototype.getClassName = function () {
  70221. return "ImageProcessingPostProcess";
  70222. };
  70223. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70224. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70225. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70226. var defines = "";
  70227. for (var define in this._defines) {
  70228. if (this._defines[define]) {
  70229. defines += "#define " + define + ";\r\n";
  70230. }
  70231. }
  70232. var samplers = ["textureSampler"];
  70233. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70234. var uniforms = ["scale"];
  70235. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70236. this.updateEffect(defines, uniforms, samplers);
  70237. };
  70238. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70239. _super.prototype.dispose.call(this, camera);
  70240. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70241. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70242. }
  70243. this.imageProcessingConfiguration.applyByPostProcess = false;
  70244. };
  70245. __decorate([
  70246. BABYLON.serialize()
  70247. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70248. return ImageProcessingPostProcess;
  70249. }(BABYLON.PostProcess));
  70250. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70251. })(BABYLON || (BABYLON = {}));
  70252. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70253. var BABYLON;
  70254. (function (BABYLON) {
  70255. var Bone = /** @class */ (function (_super) {
  70256. __extends(Bone, _super);
  70257. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70258. if (parentBone === void 0) { parentBone = null; }
  70259. if (localMatrix === void 0) { localMatrix = null; }
  70260. if (restPose === void 0) { restPose = null; }
  70261. if (baseMatrix === void 0) { baseMatrix = null; }
  70262. if (index === void 0) { index = null; }
  70263. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70264. _this.name = name;
  70265. _this.children = new Array();
  70266. _this.animations = new Array();
  70267. // Set this value to map this bone to a different index in the transform matrices.
  70268. // Set this value to -1 to exclude the bone from the transform matrices.
  70269. _this._index = null;
  70270. _this._worldTransform = new BABYLON.Matrix();
  70271. _this._absoluteTransform = new BABYLON.Matrix();
  70272. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70273. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70274. _this._scaleVector = BABYLON.Vector3.One();
  70275. _this._negateScaleChildren = BABYLON.Vector3.One();
  70276. _this._scalingDeterminant = 1;
  70277. _this._skeleton = skeleton;
  70278. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70279. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70280. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70281. _this._index = index;
  70282. skeleton.bones.push(_this);
  70283. _this.setParent(parentBone, false);
  70284. _this._updateDifferenceMatrix();
  70285. return _this;
  70286. }
  70287. Object.defineProperty(Bone.prototype, "_matrix", {
  70288. get: function () {
  70289. return this._localMatrix;
  70290. },
  70291. set: function (val) {
  70292. if (this._localMatrix) {
  70293. this._localMatrix.copyFrom(val);
  70294. }
  70295. else {
  70296. this._localMatrix = val;
  70297. }
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. // Members
  70303. Bone.prototype.getSkeleton = function () {
  70304. return this._skeleton;
  70305. };
  70306. Bone.prototype.getParent = function () {
  70307. return this._parent;
  70308. };
  70309. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70310. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70311. if (this._parent === parent) {
  70312. return;
  70313. }
  70314. if (this._parent) {
  70315. var index = this._parent.children.indexOf(this);
  70316. if (index !== -1) {
  70317. this._parent.children.splice(index, 1);
  70318. }
  70319. }
  70320. this._parent = parent;
  70321. if (this._parent) {
  70322. this._parent.children.push(this);
  70323. }
  70324. if (updateDifferenceMatrix) {
  70325. this._updateDifferenceMatrix();
  70326. }
  70327. };
  70328. Bone.prototype.getLocalMatrix = function () {
  70329. return this._localMatrix;
  70330. };
  70331. Bone.prototype.getBaseMatrix = function () {
  70332. return this._baseMatrix;
  70333. };
  70334. Bone.prototype.getRestPose = function () {
  70335. return this._restPose;
  70336. };
  70337. Bone.prototype.returnToRest = function () {
  70338. this.updateMatrix(this._restPose.clone());
  70339. };
  70340. Bone.prototype.getWorldMatrix = function () {
  70341. return this._worldTransform;
  70342. };
  70343. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70344. return this._invertedAbsoluteTransform;
  70345. };
  70346. Bone.prototype.getAbsoluteTransform = function () {
  70347. return this._absoluteTransform;
  70348. };
  70349. Object.defineProperty(Bone.prototype, "position", {
  70350. // Properties (matches AbstractMesh properties)
  70351. get: function () {
  70352. return this.getPosition();
  70353. },
  70354. set: function (newPosition) {
  70355. this.setPosition(newPosition);
  70356. },
  70357. enumerable: true,
  70358. configurable: true
  70359. });
  70360. Object.defineProperty(Bone.prototype, "rotation", {
  70361. get: function () {
  70362. return this.getRotation();
  70363. },
  70364. set: function (newRotation) {
  70365. this.setRotation(newRotation);
  70366. },
  70367. enumerable: true,
  70368. configurable: true
  70369. });
  70370. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70371. get: function () {
  70372. return this.getRotationQuaternion();
  70373. },
  70374. set: function (newRotation) {
  70375. this.setRotationQuaternion(newRotation);
  70376. },
  70377. enumerable: true,
  70378. configurable: true
  70379. });
  70380. Object.defineProperty(Bone.prototype, "scaling", {
  70381. get: function () {
  70382. return this.getScale();
  70383. },
  70384. set: function (newScaling) {
  70385. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70386. },
  70387. enumerable: true,
  70388. configurable: true
  70389. });
  70390. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70391. /**
  70392. * Gets the animation properties override
  70393. */
  70394. get: function () {
  70395. return this._skeleton.animationPropertiesOverride;
  70396. },
  70397. enumerable: true,
  70398. configurable: true
  70399. });
  70400. // Methods
  70401. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70402. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70403. this._baseMatrix = matrix.clone();
  70404. this._localMatrix = matrix.clone();
  70405. this._skeleton._markAsDirty();
  70406. if (updateDifferenceMatrix) {
  70407. this._updateDifferenceMatrix();
  70408. }
  70409. };
  70410. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70411. if (!rootMatrix) {
  70412. rootMatrix = this._baseMatrix;
  70413. }
  70414. if (this._parent) {
  70415. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70416. }
  70417. else {
  70418. this._absoluteTransform.copyFrom(rootMatrix);
  70419. }
  70420. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70421. for (var index = 0; index < this.children.length; index++) {
  70422. this.children[index]._updateDifferenceMatrix();
  70423. }
  70424. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70425. };
  70426. Bone.prototype.markAsDirty = function () {
  70427. this._currentRenderId++;
  70428. this._skeleton._markAsDirty();
  70429. };
  70430. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70431. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70432. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70433. // all animation may be coming from a library skeleton, so may need to create animation
  70434. if (this.animations.length === 0) {
  70435. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70436. this.animations[0].setKeys([]);
  70437. }
  70438. // get animation info / verify there is such a range from the source bone
  70439. var sourceRange = source.animations[0].getRange(rangeName);
  70440. if (!sourceRange) {
  70441. return false;
  70442. }
  70443. var from = sourceRange.from;
  70444. var to = sourceRange.to;
  70445. var sourceKeys = source.animations[0].getKeys();
  70446. // rescaling prep
  70447. var sourceBoneLength = source.length;
  70448. var sourceParent = source.getParent();
  70449. var parent = this.getParent();
  70450. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70451. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70452. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70453. var destKeys = this.animations[0].getKeys();
  70454. // loop vars declaration
  70455. var orig;
  70456. var origTranslation;
  70457. var mat;
  70458. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70459. orig = sourceKeys[key];
  70460. if (orig.frame >= from && orig.frame <= to) {
  70461. if (rescaleAsRequired) {
  70462. mat = orig.value.clone();
  70463. // scale based on parent ratio, when bone has parent
  70464. if (parentScalingReqd) {
  70465. origTranslation = mat.getTranslation();
  70466. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70467. // scale based on skeleton dimension ratio when root bone, and value is passed
  70468. }
  70469. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70470. origTranslation = mat.getTranslation();
  70471. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70472. // use original when root bone, and no data for skelDimensionsRatio
  70473. }
  70474. else {
  70475. mat = orig.value;
  70476. }
  70477. }
  70478. else {
  70479. mat = orig.value;
  70480. }
  70481. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70482. }
  70483. }
  70484. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70485. return true;
  70486. };
  70487. /**
  70488. * Translate the bone in local or world space.
  70489. * @param vec The amount to translate the bone.
  70490. * @param space The space that the translation is in.
  70491. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70492. */
  70493. Bone.prototype.translate = function (vec, space, mesh) {
  70494. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70495. var lm = this.getLocalMatrix();
  70496. if (space == BABYLON.Space.LOCAL) {
  70497. lm.m[12] += vec.x;
  70498. lm.m[13] += vec.y;
  70499. lm.m[14] += vec.z;
  70500. }
  70501. else {
  70502. var wm = null;
  70503. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70504. if (mesh) {
  70505. wm = mesh.getWorldMatrix();
  70506. }
  70507. this._skeleton.computeAbsoluteTransforms();
  70508. var tmat = Bone._tmpMats[0];
  70509. var tvec = Bone._tmpVecs[0];
  70510. if (this._parent) {
  70511. if (mesh && wm) {
  70512. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70513. tmat.multiplyToRef(wm, tmat);
  70514. }
  70515. else {
  70516. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70517. }
  70518. }
  70519. tmat.m[12] = 0;
  70520. tmat.m[13] = 0;
  70521. tmat.m[14] = 0;
  70522. tmat.invert();
  70523. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70524. lm.m[12] += tvec.x;
  70525. lm.m[13] += tvec.y;
  70526. lm.m[14] += tvec.z;
  70527. }
  70528. this.markAsDirty();
  70529. };
  70530. /**
  70531. * Set the postion of the bone in local or world space.
  70532. * @param position The position to set the bone.
  70533. * @param space The space that the position is in.
  70534. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70535. */
  70536. Bone.prototype.setPosition = function (position, space, mesh) {
  70537. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70538. var lm = this.getLocalMatrix();
  70539. if (space == BABYLON.Space.LOCAL) {
  70540. lm.m[12] = position.x;
  70541. lm.m[13] = position.y;
  70542. lm.m[14] = position.z;
  70543. }
  70544. else {
  70545. var wm = null;
  70546. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70547. if (mesh) {
  70548. wm = mesh.getWorldMatrix();
  70549. }
  70550. this._skeleton.computeAbsoluteTransforms();
  70551. var tmat = Bone._tmpMats[0];
  70552. var vec = Bone._tmpVecs[0];
  70553. if (this._parent) {
  70554. if (mesh && wm) {
  70555. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70556. tmat.multiplyToRef(wm, tmat);
  70557. }
  70558. else {
  70559. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70560. }
  70561. }
  70562. tmat.invert();
  70563. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70564. lm.m[12] = vec.x;
  70565. lm.m[13] = vec.y;
  70566. lm.m[14] = vec.z;
  70567. }
  70568. this.markAsDirty();
  70569. };
  70570. /**
  70571. * Set the absolute postion of the bone (world space).
  70572. * @param position The position to set the bone.
  70573. * @param mesh The mesh that this bone is attached to.
  70574. */
  70575. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70576. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70577. };
  70578. /**
  70579. * Set the scale of the bone on the x, y and z axes.
  70580. * @param x The scale of the bone on the x axis.
  70581. * @param x The scale of the bone on the y axis.
  70582. * @param z The scale of the bone on the z axis.
  70583. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70584. */
  70585. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70586. if (scaleChildren === void 0) { scaleChildren = false; }
  70587. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70588. if (!scaleChildren) {
  70589. this._negateScaleChildren.x = 1 / x;
  70590. this._negateScaleChildren.y = 1 / y;
  70591. this._negateScaleChildren.z = 1 / z;
  70592. }
  70593. this._syncScaleVector();
  70594. }
  70595. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70596. };
  70597. /**
  70598. * Scale the bone on the x, y and z axes.
  70599. * @param x The amount to scale the bone on the x axis.
  70600. * @param x The amount to scale the bone on the y axis.
  70601. * @param z The amount to scale the bone on the z axis.
  70602. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70603. */
  70604. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70605. if (scaleChildren === void 0) { scaleChildren = false; }
  70606. var locMat = this.getLocalMatrix();
  70607. var origLocMat = Bone._tmpMats[0];
  70608. origLocMat.copyFrom(locMat);
  70609. var origLocMatInv = Bone._tmpMats[1];
  70610. origLocMatInv.copyFrom(origLocMat);
  70611. origLocMatInv.invert();
  70612. var scaleMat = Bone._tmpMats[2];
  70613. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70614. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70615. this._scaleVector.x *= x;
  70616. this._scaleVector.y *= y;
  70617. this._scaleVector.z *= z;
  70618. locMat.multiplyToRef(origLocMatInv, locMat);
  70619. locMat.multiplyToRef(scaleMat, locMat);
  70620. locMat.multiplyToRef(origLocMat, locMat);
  70621. var parent = this.getParent();
  70622. if (parent) {
  70623. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70624. }
  70625. else {
  70626. this.getAbsoluteTransform().copyFrom(locMat);
  70627. }
  70628. var len = this.children.length;
  70629. scaleMat.invert();
  70630. for (var i = 0; i < len; i++) {
  70631. var child = this.children[i];
  70632. var cm = child.getLocalMatrix();
  70633. cm.multiplyToRef(scaleMat, cm);
  70634. var lm = child.getLocalMatrix();
  70635. lm.m[12] *= x;
  70636. lm.m[13] *= y;
  70637. lm.m[14] *= z;
  70638. }
  70639. this.computeAbsoluteTransforms();
  70640. if (scaleChildren) {
  70641. for (var i = 0; i < len; i++) {
  70642. this.children[i].scale(x, y, z, scaleChildren);
  70643. }
  70644. }
  70645. this.markAsDirty();
  70646. };
  70647. /**
  70648. * Set the yaw, pitch, and roll of the bone in local or world space.
  70649. * @param yaw The rotation of the bone on the y axis.
  70650. * @param pitch The rotation of the bone on the x axis.
  70651. * @param roll The rotation of the bone on the z axis.
  70652. * @param space The space that the axes of rotation are in.
  70653. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70654. */
  70655. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70657. var rotMat = Bone._tmpMats[0];
  70658. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70659. var rotMatInv = Bone._tmpMats[1];
  70660. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70661. rotMatInv.multiplyToRef(rotMat, rotMat);
  70662. this._rotateWithMatrix(rotMat, space, mesh);
  70663. };
  70664. /**
  70665. * Rotate the bone on an axis in local or world space.
  70666. * @param axis The axis to rotate the bone on.
  70667. * @param amount The amount to rotate the bone.
  70668. * @param space The space that the axis is in.
  70669. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70670. */
  70671. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70673. var rmat = Bone._tmpMats[0];
  70674. rmat.m[12] = 0;
  70675. rmat.m[13] = 0;
  70676. rmat.m[14] = 0;
  70677. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70678. this._rotateWithMatrix(rmat, space, mesh);
  70679. };
  70680. /**
  70681. * Set the rotation of the bone to a particular axis angle in local or world space.
  70682. * @param axis The axis to rotate the bone on.
  70683. * @param angle The angle that the bone should be rotated to.
  70684. * @param space The space that the axis is in.
  70685. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70686. */
  70687. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70689. var rotMat = Bone._tmpMats[0];
  70690. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70691. var rotMatInv = Bone._tmpMats[1];
  70692. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70693. rotMatInv.multiplyToRef(rotMat, rotMat);
  70694. this._rotateWithMatrix(rotMat, space, mesh);
  70695. };
  70696. /**
  70697. * Set the euler rotation of the bone in local of world space.
  70698. * @param rotation The euler rotation that the bone should be set to.
  70699. * @param space The space that the rotation is in.
  70700. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70701. */
  70702. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70704. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70705. };
  70706. /**
  70707. * Set the quaternion rotation of the bone in local of world space.
  70708. * @param quat The quaternion rotation that the bone should be set to.
  70709. * @param space The space that the rotation is in.
  70710. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70711. */
  70712. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70713. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70714. var rotMatInv = Bone._tmpMats[0];
  70715. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70716. var rotMat = Bone._tmpMats[1];
  70717. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70718. rotMatInv.multiplyToRef(rotMat, rotMat);
  70719. this._rotateWithMatrix(rotMat, space, mesh);
  70720. };
  70721. /**
  70722. * Set the rotation matrix of the bone in local of world space.
  70723. * @param rotMat The rotation matrix that the bone should be set to.
  70724. * @param space The space that the rotation is in.
  70725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70726. */
  70727. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70729. var rotMatInv = Bone._tmpMats[0];
  70730. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70731. var rotMat2 = Bone._tmpMats[1];
  70732. rotMat2.copyFrom(rotMat);
  70733. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70734. this._rotateWithMatrix(rotMat2, space, mesh);
  70735. };
  70736. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70737. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70738. var lmat = this.getLocalMatrix();
  70739. var lx = lmat.m[12];
  70740. var ly = lmat.m[13];
  70741. var lz = lmat.m[14];
  70742. var parent = this.getParent();
  70743. var parentScale = Bone._tmpMats[3];
  70744. var parentScaleInv = Bone._tmpMats[4];
  70745. if (parent) {
  70746. if (space == BABYLON.Space.WORLD) {
  70747. if (mesh) {
  70748. parentScale.copyFrom(mesh.getWorldMatrix());
  70749. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70750. }
  70751. else {
  70752. parentScale.copyFrom(parent.getAbsoluteTransform());
  70753. }
  70754. }
  70755. else {
  70756. parentScale = parent._scaleMatrix;
  70757. }
  70758. parentScaleInv.copyFrom(parentScale);
  70759. parentScaleInv.invert();
  70760. lmat.multiplyToRef(parentScale, lmat);
  70761. lmat.multiplyToRef(rmat, lmat);
  70762. lmat.multiplyToRef(parentScaleInv, lmat);
  70763. }
  70764. else {
  70765. if (space == BABYLON.Space.WORLD && mesh) {
  70766. parentScale.copyFrom(mesh.getWorldMatrix());
  70767. parentScaleInv.copyFrom(parentScale);
  70768. parentScaleInv.invert();
  70769. lmat.multiplyToRef(parentScale, lmat);
  70770. lmat.multiplyToRef(rmat, lmat);
  70771. lmat.multiplyToRef(parentScaleInv, lmat);
  70772. }
  70773. else {
  70774. lmat.multiplyToRef(rmat, lmat);
  70775. }
  70776. }
  70777. lmat.m[12] = lx;
  70778. lmat.m[13] = ly;
  70779. lmat.m[14] = lz;
  70780. this.computeAbsoluteTransforms();
  70781. this.markAsDirty();
  70782. };
  70783. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70785. if (space == BABYLON.Space.WORLD) {
  70786. var scaleMatrix = Bone._tmpMats[2];
  70787. scaleMatrix.copyFrom(this._scaleMatrix);
  70788. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70789. if (mesh) {
  70790. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70791. var meshScale = Bone._tmpMats[3];
  70792. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70793. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70794. }
  70795. rotMatInv.invert();
  70796. scaleMatrix.m[0] *= this._scalingDeterminant;
  70797. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70798. }
  70799. else {
  70800. rotMatInv.copyFrom(this.getLocalMatrix());
  70801. rotMatInv.invert();
  70802. var scaleMatrix = Bone._tmpMats[2];
  70803. scaleMatrix.copyFrom(this._scaleMatrix);
  70804. if (this._parent) {
  70805. var pscaleMatrix = Bone._tmpMats[3];
  70806. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70807. pscaleMatrix.invert();
  70808. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70809. }
  70810. else {
  70811. scaleMatrix.m[0] *= this._scalingDeterminant;
  70812. }
  70813. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70814. }
  70815. };
  70816. /**
  70817. * Get the scale of the bone
  70818. * @returns the scale of the bone
  70819. */
  70820. Bone.prototype.getScale = function () {
  70821. return this._scaleVector.clone();
  70822. };
  70823. /**
  70824. * Copy the scale of the bone to a vector3.
  70825. * @param result The vector3 to copy the scale to
  70826. */
  70827. Bone.prototype.getScaleToRef = function (result) {
  70828. result.copyFrom(this._scaleVector);
  70829. };
  70830. /**
  70831. * Get the position of the bone in local or world space.
  70832. * @param space The space that the returned position is in.
  70833. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70834. * @returns The position of the bone
  70835. */
  70836. Bone.prototype.getPosition = function (space, mesh) {
  70837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70838. if (mesh === void 0) { mesh = null; }
  70839. var pos = BABYLON.Vector3.Zero();
  70840. this.getPositionToRef(space, mesh, pos);
  70841. return pos;
  70842. };
  70843. /**
  70844. * Copy the position of the bone to a vector3 in local or world space.
  70845. * @param space The space that the returned position is in.
  70846. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70847. * @param result The vector3 to copy the position to.
  70848. */
  70849. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70850. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70851. if (space == BABYLON.Space.LOCAL) {
  70852. var lm = this.getLocalMatrix();
  70853. result.x = lm.m[12];
  70854. result.y = lm.m[13];
  70855. result.z = lm.m[14];
  70856. }
  70857. else {
  70858. var wm = null;
  70859. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70860. if (mesh) {
  70861. wm = mesh.getWorldMatrix();
  70862. }
  70863. this._skeleton.computeAbsoluteTransforms();
  70864. var tmat = Bone._tmpMats[0];
  70865. if (mesh && wm) {
  70866. tmat.copyFrom(this.getAbsoluteTransform());
  70867. tmat.multiplyToRef(wm, tmat);
  70868. }
  70869. else {
  70870. tmat = this.getAbsoluteTransform();
  70871. }
  70872. result.x = tmat.m[12];
  70873. result.y = tmat.m[13];
  70874. result.z = tmat.m[14];
  70875. }
  70876. };
  70877. /**
  70878. * Get the absolute position of the bone (world space).
  70879. * @param mesh The mesh that this bone is attached to.
  70880. * @returns The absolute position of the bone
  70881. */
  70882. Bone.prototype.getAbsolutePosition = function (mesh) {
  70883. if (mesh === void 0) { mesh = null; }
  70884. var pos = BABYLON.Vector3.Zero();
  70885. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70886. return pos;
  70887. };
  70888. /**
  70889. * Copy the absolute position of the bone (world space) to the result param.
  70890. * @param mesh The mesh that this bone is attached to.
  70891. * @param result The vector3 to copy the absolute position to.
  70892. */
  70893. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70894. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70895. };
  70896. /**
  70897. * Compute the absolute transforms of this bone and its children.
  70898. */
  70899. Bone.prototype.computeAbsoluteTransforms = function () {
  70900. if (this._parent) {
  70901. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70902. }
  70903. else {
  70904. this._absoluteTransform.copyFrom(this._localMatrix);
  70905. var poseMatrix = this._skeleton.getPoseMatrix();
  70906. if (poseMatrix) {
  70907. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70908. }
  70909. }
  70910. var children = this.children;
  70911. var len = children.length;
  70912. for (var i = 0; i < len; i++) {
  70913. children[i].computeAbsoluteTransforms();
  70914. }
  70915. };
  70916. Bone.prototype._syncScaleVector = function () {
  70917. var lm = this.getLocalMatrix();
  70918. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70919. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70920. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70921. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70922. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70923. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70924. this._scaleVector.x = xs * Math.sqrt(xsq);
  70925. this._scaleVector.y = ys * Math.sqrt(ysq);
  70926. this._scaleVector.z = zs * Math.sqrt(zsq);
  70927. if (this._parent) {
  70928. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70929. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70930. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70931. }
  70932. 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);
  70933. };
  70934. /**
  70935. * Get the world direction from an axis that is in the local space of the bone.
  70936. * @param localAxis The local direction that is used to compute the world direction.
  70937. * @param mesh The mesh that this bone is attached to.
  70938. * @returns The world direction
  70939. */
  70940. Bone.prototype.getDirection = function (localAxis, mesh) {
  70941. if (mesh === void 0) { mesh = null; }
  70942. var result = BABYLON.Vector3.Zero();
  70943. this.getDirectionToRef(localAxis, mesh, result);
  70944. return result;
  70945. };
  70946. /**
  70947. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70948. * @param localAxis The local direction that is used to compute the world direction.
  70949. * @param mesh The mesh that this bone is attached to.
  70950. * @param result The vector3 that the world direction will be copied to.
  70951. */
  70952. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70953. if (mesh === void 0) { mesh = null; }
  70954. var wm = null;
  70955. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70956. if (mesh) {
  70957. wm = mesh.getWorldMatrix();
  70958. }
  70959. this._skeleton.computeAbsoluteTransforms();
  70960. var mat = Bone._tmpMats[0];
  70961. mat.copyFrom(this.getAbsoluteTransform());
  70962. if (mesh && wm) {
  70963. mat.multiplyToRef(wm, mat);
  70964. }
  70965. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70966. result.normalize();
  70967. };
  70968. /**
  70969. * Get the euler rotation of the bone in local or world space.
  70970. * @param space The space that the rotation should be in.
  70971. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70972. * @returns The euler rotation
  70973. */
  70974. Bone.prototype.getRotation = function (space, mesh) {
  70975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70976. if (mesh === void 0) { mesh = null; }
  70977. var result = BABYLON.Vector3.Zero();
  70978. this.getRotationToRef(space, mesh, result);
  70979. return result;
  70980. };
  70981. /**
  70982. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70983. * @param space The space that the rotation should be in.
  70984. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70985. * @param result The vector3 that the rotation should be copied to.
  70986. */
  70987. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70989. if (mesh === void 0) { mesh = null; }
  70990. var quat = Bone._tmpQuat;
  70991. this.getRotationQuaternionToRef(space, mesh, quat);
  70992. quat.toEulerAnglesToRef(result);
  70993. };
  70994. /**
  70995. * Get the quaternion rotation of the bone in either local or world space.
  70996. * @param space The space that the rotation should be in.
  70997. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70998. * @returns The quaternion rotation
  70999. */
  71000. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71002. if (mesh === void 0) { mesh = null; }
  71003. var result = BABYLON.Quaternion.Identity();
  71004. this.getRotationQuaternionToRef(space, mesh, result);
  71005. return result;
  71006. };
  71007. /**
  71008. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71009. * @param space The space that the rotation should be in.
  71010. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71011. * @param result The quaternion that the rotation should be copied to.
  71012. */
  71013. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71015. if (mesh === void 0) { mesh = null; }
  71016. if (space == BABYLON.Space.LOCAL) {
  71017. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71018. }
  71019. else {
  71020. var mat = Bone._tmpMats[0];
  71021. var amat = this.getAbsoluteTransform();
  71022. if (mesh) {
  71023. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71024. }
  71025. else {
  71026. mat.copyFrom(amat);
  71027. }
  71028. mat.m[0] *= this._scalingDeterminant;
  71029. mat.m[1] *= this._scalingDeterminant;
  71030. mat.m[2] *= this._scalingDeterminant;
  71031. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71032. }
  71033. };
  71034. /**
  71035. * Get the rotation matrix of the bone in local or world space.
  71036. * @param space The space that the rotation should be in.
  71037. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71038. * @returns The rotation matrix
  71039. */
  71040. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71042. var result = BABYLON.Matrix.Identity();
  71043. this.getRotationMatrixToRef(space, mesh, result);
  71044. return result;
  71045. };
  71046. /**
  71047. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71048. * @param space The space that the rotation should be in.
  71049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71050. * @param result The quaternion that the rotation should be copied to.
  71051. */
  71052. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71054. if (space == BABYLON.Space.LOCAL) {
  71055. this.getLocalMatrix().getRotationMatrixToRef(result);
  71056. }
  71057. else {
  71058. var mat = Bone._tmpMats[0];
  71059. var amat = this.getAbsoluteTransform();
  71060. if (mesh) {
  71061. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71062. }
  71063. else {
  71064. mat.copyFrom(amat);
  71065. }
  71066. mat.m[0] *= this._scalingDeterminant;
  71067. mat.m[1] *= this._scalingDeterminant;
  71068. mat.m[2] *= this._scalingDeterminant;
  71069. mat.getRotationMatrixToRef(result);
  71070. }
  71071. };
  71072. /**
  71073. * Get the world position of a point that is in the local space of the bone.
  71074. * @param position The local position
  71075. * @param mesh The mesh that this bone is attached to.
  71076. * @returns The world position
  71077. */
  71078. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71079. if (mesh === void 0) { mesh = null; }
  71080. var result = BABYLON.Vector3.Zero();
  71081. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71082. return result;
  71083. };
  71084. /**
  71085. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71086. * @param position The local position
  71087. * @param mesh The mesh that this bone is attached to.
  71088. * @param result The vector3 that the world position should be copied to.
  71089. */
  71090. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71091. if (mesh === void 0) { mesh = null; }
  71092. var wm = null;
  71093. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71094. if (mesh) {
  71095. wm = mesh.getWorldMatrix();
  71096. }
  71097. this._skeleton.computeAbsoluteTransforms();
  71098. var tmat = Bone._tmpMats[0];
  71099. if (mesh && wm) {
  71100. tmat.copyFrom(this.getAbsoluteTransform());
  71101. tmat.multiplyToRef(wm, tmat);
  71102. }
  71103. else {
  71104. tmat = this.getAbsoluteTransform();
  71105. }
  71106. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71107. };
  71108. /**
  71109. * Get the local position of a point that is in world space.
  71110. * @param position The world position
  71111. * @param mesh The mesh that this bone is attached to.
  71112. * @returns The local position
  71113. */
  71114. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71115. if (mesh === void 0) { mesh = null; }
  71116. var result = BABYLON.Vector3.Zero();
  71117. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71118. return result;
  71119. };
  71120. /**
  71121. * Get the local position of a point that is in world space and copy it to the result param.
  71122. * @param position The world position
  71123. * @param mesh The mesh that this bone is attached to.
  71124. * @param result The vector3 that the local position should be copied to.
  71125. */
  71126. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71127. if (mesh === void 0) { mesh = null; }
  71128. var wm = null;
  71129. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71130. if (mesh) {
  71131. wm = mesh.getWorldMatrix();
  71132. }
  71133. this._skeleton.computeAbsoluteTransforms();
  71134. var tmat = Bone._tmpMats[0];
  71135. tmat.copyFrom(this.getAbsoluteTransform());
  71136. if (mesh && wm) {
  71137. tmat.multiplyToRef(wm, tmat);
  71138. }
  71139. tmat.invert();
  71140. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71141. };
  71142. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71143. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71144. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71145. return Bone;
  71146. }(BABYLON.Node));
  71147. BABYLON.Bone = Bone;
  71148. })(BABYLON || (BABYLON = {}));
  71149. //# sourceMappingURL=babylon.bone.js.map
  71150. var BABYLON;
  71151. (function (BABYLON) {
  71152. var BoneIKController = /** @class */ (function () {
  71153. function BoneIKController(mesh, bone, options) {
  71154. this.targetPosition = BABYLON.Vector3.Zero();
  71155. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71156. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71157. this.poleAngle = 0;
  71158. this.slerpAmount = 1;
  71159. this._bone1Quat = BABYLON.Quaternion.Identity();
  71160. this._bone1Mat = BABYLON.Matrix.Identity();
  71161. this._bone2Ang = Math.PI;
  71162. this._maxAngle = Math.PI;
  71163. this._rightHandedSystem = false;
  71164. this._bendAxis = BABYLON.Vector3.Right();
  71165. this._slerping = false;
  71166. this._adjustRoll = 0;
  71167. this._bone2 = bone;
  71168. this._bone1 = bone.getParent();
  71169. if (!this._bone1) {
  71170. return;
  71171. }
  71172. this.mesh = mesh;
  71173. var bonePos = bone.getPosition();
  71174. if (bone.getAbsoluteTransform().determinant() > 0) {
  71175. this._rightHandedSystem = true;
  71176. this._bendAxis.x = 0;
  71177. this._bendAxis.y = 0;
  71178. this._bendAxis.z = -1;
  71179. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71180. this._adjustRoll = Math.PI * .5;
  71181. this._bendAxis.z = 1;
  71182. }
  71183. }
  71184. if (this._bone1.length) {
  71185. var boneScale1 = this._bone1.getScale();
  71186. var boneScale2 = this._bone2.getScale();
  71187. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71188. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71189. }
  71190. else if (this._bone1.children[0]) {
  71191. mesh.computeWorldMatrix(true);
  71192. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71193. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71194. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71195. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71196. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71197. }
  71198. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71199. this.maxAngle = Math.PI;
  71200. if (options) {
  71201. if (options.targetMesh) {
  71202. this.targetMesh = options.targetMesh;
  71203. this.targetMesh.computeWorldMatrix(true);
  71204. }
  71205. if (options.poleTargetMesh) {
  71206. this.poleTargetMesh = options.poleTargetMesh;
  71207. this.poleTargetMesh.computeWorldMatrix(true);
  71208. }
  71209. else if (options.poleTargetBone) {
  71210. this.poleTargetBone = options.poleTargetBone;
  71211. }
  71212. else if (this._bone1.getParent()) {
  71213. this.poleTargetBone = this._bone1.getParent();
  71214. }
  71215. if (options.poleTargetLocalOffset) {
  71216. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71217. }
  71218. if (options.poleAngle) {
  71219. this.poleAngle = options.poleAngle;
  71220. }
  71221. if (options.bendAxis) {
  71222. this._bendAxis.copyFrom(options.bendAxis);
  71223. }
  71224. if (options.maxAngle) {
  71225. this.maxAngle = options.maxAngle;
  71226. }
  71227. if (options.slerpAmount) {
  71228. this.slerpAmount = options.slerpAmount;
  71229. }
  71230. }
  71231. }
  71232. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71233. get: function () {
  71234. return this._maxAngle;
  71235. },
  71236. set: function (value) {
  71237. this._setMaxAngle(value);
  71238. },
  71239. enumerable: true,
  71240. configurable: true
  71241. });
  71242. BoneIKController.prototype._setMaxAngle = function (ang) {
  71243. if (ang < 0) {
  71244. ang = 0;
  71245. }
  71246. if (ang > Math.PI || ang == undefined) {
  71247. ang = Math.PI;
  71248. }
  71249. this._maxAngle = ang;
  71250. var a = this._bone1Length;
  71251. var b = this._bone2Length;
  71252. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71253. };
  71254. BoneIKController.prototype.update = function () {
  71255. var bone1 = this._bone1;
  71256. if (!bone1) {
  71257. return;
  71258. }
  71259. var target = this.targetPosition;
  71260. var poleTarget = this.poleTargetPosition;
  71261. var mat1 = BoneIKController._tmpMats[0];
  71262. var mat2 = BoneIKController._tmpMats[1];
  71263. if (this.targetMesh) {
  71264. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71265. }
  71266. if (this.poleTargetBone) {
  71267. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71268. }
  71269. else if (this.poleTargetMesh) {
  71270. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71271. }
  71272. var bonePos = BoneIKController._tmpVecs[0];
  71273. var zaxis = BoneIKController._tmpVecs[1];
  71274. var xaxis = BoneIKController._tmpVecs[2];
  71275. var yaxis = BoneIKController._tmpVecs[3];
  71276. var upAxis = BoneIKController._tmpVecs[4];
  71277. var _tmpQuat = BoneIKController._tmpQuat;
  71278. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71279. poleTarget.subtractToRef(bonePos, upAxis);
  71280. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71281. upAxis.y = 1;
  71282. }
  71283. else {
  71284. upAxis.normalize();
  71285. }
  71286. target.subtractToRef(bonePos, yaxis);
  71287. yaxis.normalize();
  71288. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71289. zaxis.normalize();
  71290. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71291. xaxis.normalize();
  71292. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71293. var a = this._bone1Length;
  71294. var b = this._bone2Length;
  71295. var c = BABYLON.Vector3.Distance(bonePos, target);
  71296. if (this._maxReach > 0) {
  71297. c = Math.min(this._maxReach, c);
  71298. }
  71299. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71300. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71301. if (acosa > 1) {
  71302. acosa = 1;
  71303. }
  71304. if (acosb > 1) {
  71305. acosb = 1;
  71306. }
  71307. if (acosa < -1) {
  71308. acosa = -1;
  71309. }
  71310. if (acosb < -1) {
  71311. acosb = -1;
  71312. }
  71313. var angA = Math.acos(acosa);
  71314. var angB = Math.acos(acosb);
  71315. var angC = -angA - angB;
  71316. if (this._rightHandedSystem) {
  71317. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71318. mat2.multiplyToRef(mat1, mat1);
  71319. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71320. mat2.multiplyToRef(mat1, mat1);
  71321. }
  71322. else {
  71323. var _tmpVec = BoneIKController._tmpVecs[5];
  71324. _tmpVec.copyFrom(this._bendAxis);
  71325. _tmpVec.x *= -1;
  71326. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71327. mat2.multiplyToRef(mat1, mat1);
  71328. }
  71329. if (this.poleAngle) {
  71330. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71331. mat1.multiplyToRef(mat2, mat1);
  71332. }
  71333. if (this._bone1) {
  71334. if (this.slerpAmount < 1) {
  71335. if (!this._slerping) {
  71336. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71337. }
  71338. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71339. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71340. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71341. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71342. this._slerping = true;
  71343. }
  71344. else {
  71345. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71346. this._bone1Mat.copyFrom(mat1);
  71347. this._slerping = false;
  71348. }
  71349. }
  71350. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71351. this._bone2Ang = angC;
  71352. };
  71353. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71354. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71355. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71356. return BoneIKController;
  71357. }());
  71358. BABYLON.BoneIKController = BoneIKController;
  71359. })(BABYLON || (BABYLON = {}));
  71360. //# sourceMappingURL=babylon.boneIKController.js.map
  71361. var BABYLON;
  71362. (function (BABYLON) {
  71363. var BoneLookController = /** @class */ (function () {
  71364. /**
  71365. * Create a BoneLookController
  71366. * @param mesh the mesh that the bone belongs to
  71367. * @param bone the bone that will be looking to the target
  71368. * @param target the target Vector3 to look at
  71369. * @param settings optional settings:
  71370. * - maxYaw: the maximum angle the bone will yaw to
  71371. * - minYaw: the minimum angle the bone will yaw to
  71372. * - maxPitch: the maximum angle the bone will pitch to
  71373. * - minPitch: the minimum angle the bone will yaw to
  71374. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71375. * - upAxis: the up axis of the coordinate system
  71376. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71377. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71378. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71379. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71380. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71381. * - adjustRoll: used to make an adjustment to the roll of the bone
  71382. **/
  71383. function BoneLookController(mesh, bone, target, options) {
  71384. /**
  71385. * The up axis of the coordinate system that is used when the bone is rotated.
  71386. */
  71387. this.upAxis = BABYLON.Vector3.Up();
  71388. /**
  71389. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71390. */
  71391. this.upAxisSpace = BABYLON.Space.LOCAL;
  71392. /**
  71393. * Used to make an adjustment to the yaw of the bone.
  71394. */
  71395. this.adjustYaw = 0;
  71396. /**
  71397. * Used to make an adjustment to the pitch of the bone.
  71398. */
  71399. this.adjustPitch = 0;
  71400. /**
  71401. * Used to make an adjustment to the roll of the bone.
  71402. */
  71403. this.adjustRoll = 0;
  71404. /**
  71405. * 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).
  71406. */
  71407. this.slerpAmount = 1;
  71408. this._boneQuat = BABYLON.Quaternion.Identity();
  71409. this._slerping = false;
  71410. this._firstFrameSkipped = false;
  71411. this._fowardAxis = BABYLON.Vector3.Forward();
  71412. this.mesh = mesh;
  71413. this.bone = bone;
  71414. this.target = target;
  71415. if (options) {
  71416. if (options.adjustYaw) {
  71417. this.adjustYaw = options.adjustYaw;
  71418. }
  71419. if (options.adjustPitch) {
  71420. this.adjustPitch = options.adjustPitch;
  71421. }
  71422. if (options.adjustRoll) {
  71423. this.adjustRoll = options.adjustRoll;
  71424. }
  71425. if (options.maxYaw != null) {
  71426. this.maxYaw = options.maxYaw;
  71427. }
  71428. else {
  71429. this.maxYaw = Math.PI;
  71430. }
  71431. if (options.minYaw != null) {
  71432. this.minYaw = options.minYaw;
  71433. }
  71434. else {
  71435. this.minYaw = -Math.PI;
  71436. }
  71437. if (options.maxPitch != null) {
  71438. this.maxPitch = options.maxPitch;
  71439. }
  71440. else {
  71441. this.maxPitch = Math.PI;
  71442. }
  71443. if (options.minPitch != null) {
  71444. this.minPitch = options.minPitch;
  71445. }
  71446. else {
  71447. this.minPitch = -Math.PI;
  71448. }
  71449. if (options.slerpAmount != null) {
  71450. this.slerpAmount = options.slerpAmount;
  71451. }
  71452. if (options.upAxis != null) {
  71453. this.upAxis = options.upAxis;
  71454. }
  71455. if (options.upAxisSpace != null) {
  71456. this.upAxisSpace = options.upAxisSpace;
  71457. }
  71458. if (options.yawAxis != null || options.pitchAxis != null) {
  71459. var newYawAxis = BABYLON.Axis.Y;
  71460. var newPitchAxis = BABYLON.Axis.X;
  71461. if (options.yawAxis != null) {
  71462. newYawAxis = options.yawAxis.clone();
  71463. newYawAxis.normalize();
  71464. }
  71465. if (options.pitchAxis != null) {
  71466. newPitchAxis = options.pitchAxis.clone();
  71467. newPitchAxis.normalize();
  71468. }
  71469. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71470. this._transformYawPitch = BABYLON.Matrix.Identity();
  71471. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71472. this._transformYawPitchInv = this._transformYawPitch.clone();
  71473. this._transformYawPitch.invert();
  71474. }
  71475. }
  71476. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71477. this.upAxisSpace = BABYLON.Space.LOCAL;
  71478. }
  71479. }
  71480. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71481. /**
  71482. * Get/set the minimum yaw angle that the bone can look to.
  71483. */
  71484. get: function () {
  71485. return this._minYaw;
  71486. },
  71487. set: function (value) {
  71488. this._minYaw = value;
  71489. this._minYawSin = Math.sin(value);
  71490. this._minYawCos = Math.cos(value);
  71491. if (this._maxYaw != null) {
  71492. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71493. this._yawRange = this._maxYaw - this._minYaw;
  71494. }
  71495. },
  71496. enumerable: true,
  71497. configurable: true
  71498. });
  71499. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71500. /**
  71501. * Get/set the maximum yaw angle that the bone can look to.
  71502. */
  71503. get: function () {
  71504. return this._maxYaw;
  71505. },
  71506. set: function (value) {
  71507. this._maxYaw = value;
  71508. this._maxYawSin = Math.sin(value);
  71509. this._maxYawCos = Math.cos(value);
  71510. if (this._minYaw != null) {
  71511. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71512. this._yawRange = this._maxYaw - this._minYaw;
  71513. }
  71514. },
  71515. enumerable: true,
  71516. configurable: true
  71517. });
  71518. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71519. /**
  71520. * Get/set the minimum pitch angle that the bone can look to.
  71521. */
  71522. get: function () {
  71523. return this._minPitch;
  71524. },
  71525. set: function (value) {
  71526. this._minPitch = value;
  71527. this._minPitchTan = Math.tan(value);
  71528. },
  71529. enumerable: true,
  71530. configurable: true
  71531. });
  71532. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71533. /**
  71534. * Get/set the maximum pitch angle that the bone can look to.
  71535. */
  71536. get: function () {
  71537. return this._maxPitch;
  71538. },
  71539. set: function (value) {
  71540. this._maxPitch = value;
  71541. this._maxPitchTan = Math.tan(value);
  71542. },
  71543. enumerable: true,
  71544. configurable: true
  71545. });
  71546. /**
  71547. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71548. */
  71549. BoneLookController.prototype.update = function () {
  71550. //skip the first frame when slerping so that the mesh rotation is correct
  71551. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71552. this._firstFrameSkipped = true;
  71553. return;
  71554. }
  71555. var bone = this.bone;
  71556. var bonePos = BoneLookController._tmpVecs[0];
  71557. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71558. var target = this.target;
  71559. var _tmpMat1 = BoneLookController._tmpMats[0];
  71560. var _tmpMat2 = BoneLookController._tmpMats[1];
  71561. var mesh = this.mesh;
  71562. var parentBone = bone.getParent();
  71563. var upAxis = BoneLookController._tmpVecs[1];
  71564. upAxis.copyFrom(this.upAxis);
  71565. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71566. if (this._transformYawPitch) {
  71567. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71568. }
  71569. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71570. }
  71571. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71572. mesh.getDirectionToRef(upAxis, upAxis);
  71573. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71574. upAxis.normalize();
  71575. }
  71576. }
  71577. var checkYaw = false;
  71578. var checkPitch = false;
  71579. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71580. checkYaw = true;
  71581. }
  71582. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71583. checkPitch = true;
  71584. }
  71585. if (checkYaw || checkPitch) {
  71586. var spaceMat = BoneLookController._tmpMats[2];
  71587. var spaceMatInv = BoneLookController._tmpMats[3];
  71588. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71589. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71590. }
  71591. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71592. spaceMat.copyFrom(mesh.getWorldMatrix());
  71593. }
  71594. else {
  71595. var forwardAxis = BoneLookController._tmpVecs[2];
  71596. forwardAxis.copyFrom(this._fowardAxis);
  71597. if (this._transformYawPitch) {
  71598. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71599. }
  71600. if (parentBone) {
  71601. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71602. }
  71603. else {
  71604. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71605. }
  71606. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71607. rightAxis.normalize();
  71608. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71609. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71610. }
  71611. spaceMat.invertToRef(spaceMatInv);
  71612. var xzlen = null;
  71613. if (checkPitch) {
  71614. var localTarget = BoneLookController._tmpVecs[3];
  71615. target.subtractToRef(bonePos, localTarget);
  71616. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71617. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71618. var pitch = Math.atan2(localTarget.y, xzlen);
  71619. var newPitch = pitch;
  71620. if (pitch > this._maxPitch) {
  71621. localTarget.y = this._maxPitchTan * xzlen;
  71622. newPitch = this._maxPitch;
  71623. }
  71624. else if (pitch < this._minPitch) {
  71625. localTarget.y = this._minPitchTan * xzlen;
  71626. newPitch = this._minPitch;
  71627. }
  71628. if (pitch != newPitch) {
  71629. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71630. localTarget.addInPlace(bonePos);
  71631. target = localTarget;
  71632. }
  71633. }
  71634. if (checkYaw) {
  71635. var localTarget = BoneLookController._tmpVecs[4];
  71636. target.subtractToRef(bonePos, localTarget);
  71637. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71638. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71639. var newYaw = yaw;
  71640. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71641. if (xzlen == null) {
  71642. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71643. }
  71644. if (this._yawRange > Math.PI) {
  71645. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71646. localTarget.z = this._maxYawCos * xzlen;
  71647. localTarget.x = this._maxYawSin * xzlen;
  71648. newYaw = this._maxYaw;
  71649. }
  71650. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71651. localTarget.z = this._minYawCos * xzlen;
  71652. localTarget.x = this._minYawSin * xzlen;
  71653. newYaw = this._minYaw;
  71654. }
  71655. }
  71656. else {
  71657. if (yaw > this._maxYaw) {
  71658. localTarget.z = this._maxYawCos * xzlen;
  71659. localTarget.x = this._maxYawSin * xzlen;
  71660. newYaw = this._maxYaw;
  71661. }
  71662. else if (yaw < this._minYaw) {
  71663. localTarget.z = this._minYawCos * xzlen;
  71664. localTarget.x = this._minYawSin * xzlen;
  71665. newYaw = this._minYaw;
  71666. }
  71667. }
  71668. }
  71669. if (this._slerping && this._yawRange > Math.PI) {
  71670. //are we going to be crossing into the min/max region?
  71671. var boneFwd = BoneLookController._tmpVecs[8];
  71672. boneFwd.copyFrom(BABYLON.Axis.Z);
  71673. if (this._transformYawPitch) {
  71674. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71675. }
  71676. var boneRotMat = BoneLookController._tmpMats[4];
  71677. this._boneQuat.toRotationMatrix(boneRotMat);
  71678. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71679. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71680. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71681. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71682. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71683. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71684. if (angBtwTar > angBtwMidYaw) {
  71685. if (xzlen == null) {
  71686. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71687. }
  71688. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71689. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71690. if (angBtwMin < angBtwMax) {
  71691. newYaw = boneYaw + Math.PI * .75;
  71692. localTarget.z = Math.cos(newYaw) * xzlen;
  71693. localTarget.x = Math.sin(newYaw) * xzlen;
  71694. }
  71695. else {
  71696. newYaw = boneYaw - Math.PI * .75;
  71697. localTarget.z = Math.cos(newYaw) * xzlen;
  71698. localTarget.x = Math.sin(newYaw) * xzlen;
  71699. }
  71700. }
  71701. }
  71702. if (yaw != newYaw) {
  71703. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71704. localTarget.addInPlace(bonePos);
  71705. target = localTarget;
  71706. }
  71707. }
  71708. }
  71709. var zaxis = BoneLookController._tmpVecs[5];
  71710. var xaxis = BoneLookController._tmpVecs[6];
  71711. var yaxis = BoneLookController._tmpVecs[7];
  71712. var _tmpQuat = BoneLookController._tmpQuat;
  71713. target.subtractToRef(bonePos, zaxis);
  71714. zaxis.normalize();
  71715. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71716. xaxis.normalize();
  71717. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71718. yaxis.normalize();
  71719. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71720. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71721. return;
  71722. }
  71723. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71724. return;
  71725. }
  71726. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71727. return;
  71728. }
  71729. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71730. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71731. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71732. }
  71733. if (this.slerpAmount < 1) {
  71734. if (!this._slerping) {
  71735. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71736. }
  71737. if (this._transformYawPitch) {
  71738. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71739. }
  71740. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71741. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71742. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71743. this._slerping = true;
  71744. }
  71745. else {
  71746. if (this._transformYawPitch) {
  71747. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71748. }
  71749. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71750. this._slerping = false;
  71751. }
  71752. };
  71753. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71754. var angDiff = ang2 - ang1;
  71755. angDiff %= Math.PI * 2;
  71756. if (angDiff > Math.PI) {
  71757. angDiff -= Math.PI * 2;
  71758. }
  71759. else if (angDiff < -Math.PI) {
  71760. angDiff += Math.PI * 2;
  71761. }
  71762. return angDiff;
  71763. };
  71764. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71765. ang1 %= (2 * Math.PI);
  71766. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71767. ang2 %= (2 * Math.PI);
  71768. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71769. var ab = 0;
  71770. if (ang1 < ang2) {
  71771. ab = ang2 - ang1;
  71772. }
  71773. else {
  71774. ab = ang1 - ang2;
  71775. }
  71776. if (ab > Math.PI) {
  71777. ab = Math.PI * 2 - ab;
  71778. }
  71779. return ab;
  71780. };
  71781. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71782. ang %= (2 * Math.PI);
  71783. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71784. ang1 %= (2 * Math.PI);
  71785. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71786. ang2 %= (2 * Math.PI);
  71787. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71788. if (ang1 < ang2) {
  71789. if (ang > ang1 && ang < ang2) {
  71790. return true;
  71791. }
  71792. }
  71793. else {
  71794. if (ang > ang2 && ang < ang1) {
  71795. return true;
  71796. }
  71797. }
  71798. return false;
  71799. };
  71800. 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()];
  71801. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71802. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71803. return BoneLookController;
  71804. }());
  71805. BABYLON.BoneLookController = BoneLookController;
  71806. })(BABYLON || (BABYLON = {}));
  71807. //# sourceMappingURL=babylon.boneLookController.js.map
  71808. var BABYLON;
  71809. (function (BABYLON) {
  71810. var Skeleton = /** @class */ (function () {
  71811. function Skeleton(name, id, scene) {
  71812. this.name = name;
  71813. this.id = id;
  71814. this.bones = new Array();
  71815. this.needInitialSkinMatrix = false;
  71816. this._isDirty = true;
  71817. this._meshesWithPoseMatrix = new Array();
  71818. this._identity = BABYLON.Matrix.Identity();
  71819. this._ranges = {};
  71820. this._lastAbsoluteTransformsUpdateId = -1;
  71821. /**
  71822. * Specifies if the skeleton should be serialized.
  71823. */
  71824. this.doNotSerialize = false;
  71825. // Events
  71826. /**
  71827. * An event triggered before computing the skeleton's matrices
  71828. * @type {BABYLON.Observable}
  71829. */
  71830. this.onBeforeComputeObservable = new BABYLON.Observable();
  71831. this.bones = [];
  71832. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71833. scene.skeletons.push(this);
  71834. //make sure it will recalculate the matrix next time prepare is called.
  71835. this._isDirty = true;
  71836. }
  71837. // Members
  71838. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71839. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71840. return mesh._bonesTransformMatrices;
  71841. }
  71842. if (!this._transformMatrices) {
  71843. this.prepare();
  71844. }
  71845. return this._transformMatrices;
  71846. };
  71847. Skeleton.prototype.getScene = function () {
  71848. return this._scene;
  71849. };
  71850. // Methods
  71851. /**
  71852. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71853. */
  71854. Skeleton.prototype.toString = function (fullDetails) {
  71855. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71856. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71857. if (fullDetails) {
  71858. ret += ", Ranges: {";
  71859. var first = true;
  71860. for (var name_1 in this._ranges) {
  71861. if (first) {
  71862. ret += ", ";
  71863. first = false;
  71864. }
  71865. ret += name_1;
  71866. }
  71867. ret += "}";
  71868. }
  71869. return ret;
  71870. };
  71871. /**
  71872. * Get bone's index searching by name
  71873. * @param {string} name is bone's name to search for
  71874. * @return {number} Indice of the bone. Returns -1 if not found
  71875. */
  71876. Skeleton.prototype.getBoneIndexByName = function (name) {
  71877. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71878. if (this.bones[boneIndex].name === name) {
  71879. return boneIndex;
  71880. }
  71881. }
  71882. return -1;
  71883. };
  71884. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71885. // check name not already in use
  71886. if (!this._ranges[name]) {
  71887. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71888. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71889. if (this.bones[i].animations[0]) {
  71890. this.bones[i].animations[0].createRange(name, from, to);
  71891. }
  71892. }
  71893. }
  71894. };
  71895. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71896. if (deleteFrames === void 0) { deleteFrames = true; }
  71897. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71898. if (this.bones[i].animations[0]) {
  71899. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71900. }
  71901. }
  71902. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71903. };
  71904. Skeleton.prototype.getAnimationRange = function (name) {
  71905. return this._ranges[name];
  71906. };
  71907. /**
  71908. * Returns as an Array, all AnimationRanges defined on this skeleton
  71909. */
  71910. Skeleton.prototype.getAnimationRanges = function () {
  71911. var animationRanges = [];
  71912. var name;
  71913. var i = 0;
  71914. for (name in this._ranges) {
  71915. animationRanges[i] = this._ranges[name];
  71916. i++;
  71917. }
  71918. return animationRanges;
  71919. };
  71920. /**
  71921. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71922. */
  71923. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71924. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71925. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71926. return false;
  71927. }
  71928. var ret = true;
  71929. var frameOffset = this._getHighestAnimationFrame() + 1;
  71930. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71931. var boneDict = {};
  71932. var sourceBones = source.bones;
  71933. var nBones;
  71934. var i;
  71935. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71936. boneDict[sourceBones[i].name] = sourceBones[i];
  71937. }
  71938. if (this.bones.length !== sourceBones.length) {
  71939. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71940. ret = false;
  71941. }
  71942. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71943. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71944. var boneName = this.bones[i].name;
  71945. var sourceBone = boneDict[boneName];
  71946. if (sourceBone) {
  71947. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71948. }
  71949. else {
  71950. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71951. ret = false;
  71952. }
  71953. }
  71954. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71955. var range = source.getAnimationRange(name);
  71956. if (range) {
  71957. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71958. }
  71959. return ret;
  71960. };
  71961. Skeleton.prototype.returnToRest = function () {
  71962. for (var index = 0; index < this.bones.length; index++) {
  71963. this.bones[index].returnToRest();
  71964. }
  71965. };
  71966. Skeleton.prototype._getHighestAnimationFrame = function () {
  71967. var ret = 0;
  71968. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71969. if (this.bones[i].animations[0]) {
  71970. var highest = this.bones[i].animations[0].getHighestFrame();
  71971. if (ret < highest) {
  71972. ret = highest;
  71973. }
  71974. }
  71975. }
  71976. return ret;
  71977. };
  71978. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71979. var range = this.getAnimationRange(name);
  71980. if (!range) {
  71981. return null;
  71982. }
  71983. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71984. };
  71985. Skeleton.prototype._markAsDirty = function () {
  71986. this._isDirty = true;
  71987. };
  71988. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71989. this._meshesWithPoseMatrix.push(mesh);
  71990. };
  71991. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71992. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71993. if (index > -1) {
  71994. this._meshesWithPoseMatrix.splice(index, 1);
  71995. }
  71996. };
  71997. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71998. this.onBeforeComputeObservable.notifyObservers(this);
  71999. for (var index = 0; index < this.bones.length; index++) {
  72000. var bone = this.bones[index];
  72001. var parentBone = bone.getParent();
  72002. if (parentBone) {
  72003. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72004. }
  72005. else {
  72006. if (initialSkinMatrix) {
  72007. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72008. }
  72009. else {
  72010. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72011. }
  72012. }
  72013. if (bone._index !== -1) {
  72014. var mappedIndex = bone._index === null ? index : bone._index;
  72015. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72016. }
  72017. }
  72018. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72019. };
  72020. Skeleton.prototype.prepare = function () {
  72021. if (!this._isDirty) {
  72022. return;
  72023. }
  72024. if (this.needInitialSkinMatrix) {
  72025. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72026. var mesh = this._meshesWithPoseMatrix[index];
  72027. var poseMatrix = mesh.getPoseMatrix();
  72028. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72029. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72030. }
  72031. if (this._synchronizedWithMesh !== mesh) {
  72032. this._synchronizedWithMesh = mesh;
  72033. // Prepare bones
  72034. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72035. var bone = this.bones[boneIndex];
  72036. if (!bone.getParent()) {
  72037. var matrix = bone.getBaseMatrix();
  72038. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72039. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72040. }
  72041. }
  72042. }
  72043. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72044. }
  72045. }
  72046. else {
  72047. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72048. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72049. }
  72050. this._computeTransformMatrices(this._transformMatrices, null);
  72051. }
  72052. this._isDirty = false;
  72053. this._scene._activeBones.addCount(this.bones.length, false);
  72054. };
  72055. Skeleton.prototype.getAnimatables = function () {
  72056. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72057. this._animatables = [];
  72058. for (var index = 0; index < this.bones.length; index++) {
  72059. this._animatables.push(this.bones[index]);
  72060. }
  72061. }
  72062. return this._animatables;
  72063. };
  72064. Skeleton.prototype.clone = function (name, id) {
  72065. var result = new Skeleton(name, id || name, this._scene);
  72066. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72067. for (var index = 0; index < this.bones.length; index++) {
  72068. var source = this.bones[index];
  72069. var parentBone = null;
  72070. var parent_1 = source.getParent();
  72071. if (parent_1) {
  72072. var parentIndex = this.bones.indexOf(parent_1);
  72073. parentBone = result.bones[parentIndex];
  72074. }
  72075. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72076. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72077. }
  72078. if (this._ranges) {
  72079. result._ranges = {};
  72080. for (var rangeName in this._ranges) {
  72081. var range = this._ranges[rangeName];
  72082. if (range) {
  72083. result._ranges[rangeName] = range.clone();
  72084. }
  72085. }
  72086. }
  72087. this._isDirty = true;
  72088. return result;
  72089. };
  72090. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72091. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72092. this.bones.forEach(function (bone) {
  72093. bone.animations.forEach(function (animation) {
  72094. animation.enableBlending = true;
  72095. animation.blendingSpeed = blendingSpeed;
  72096. });
  72097. });
  72098. };
  72099. Skeleton.prototype.dispose = function () {
  72100. this._meshesWithPoseMatrix = [];
  72101. // Animations
  72102. this.getScene().stopAnimation(this);
  72103. // Remove from scene
  72104. this.getScene().removeSkeleton(this);
  72105. };
  72106. Skeleton.prototype.serialize = function () {
  72107. var serializationObject = {};
  72108. serializationObject.name = this.name;
  72109. serializationObject.id = this.id;
  72110. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72111. serializationObject.bones = [];
  72112. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72113. for (var index = 0; index < this.bones.length; index++) {
  72114. var bone = this.bones[index];
  72115. var parent_2 = bone.getParent();
  72116. var serializedBone = {
  72117. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72118. name: bone.name,
  72119. matrix: bone.getBaseMatrix().toArray(),
  72120. rest: bone.getRestPose().toArray()
  72121. };
  72122. serializationObject.bones.push(serializedBone);
  72123. if (bone.length) {
  72124. serializedBone.length = bone.length;
  72125. }
  72126. if (bone.animations && bone.animations.length > 0) {
  72127. serializedBone.animation = bone.animations[0].serialize();
  72128. }
  72129. serializationObject.ranges = [];
  72130. for (var name in this._ranges) {
  72131. var source = this._ranges[name];
  72132. if (!source) {
  72133. continue;
  72134. }
  72135. var range = {};
  72136. range.name = name;
  72137. range.from = source.from;
  72138. range.to = source.to;
  72139. serializationObject.ranges.push(range);
  72140. }
  72141. }
  72142. return serializationObject;
  72143. };
  72144. Skeleton.Parse = function (parsedSkeleton, scene) {
  72145. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72146. if (parsedSkeleton.dimensionsAtRest) {
  72147. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72148. }
  72149. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72150. var index;
  72151. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72152. var parsedBone = parsedSkeleton.bones[index];
  72153. var parentBone = null;
  72154. if (parsedBone.parentBoneIndex > -1) {
  72155. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72156. }
  72157. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72158. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72159. if (parsedBone.length) {
  72160. bone.length = parsedBone.length;
  72161. }
  72162. if (parsedBone.animation) {
  72163. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72164. }
  72165. }
  72166. // placed after bones, so createAnimationRange can cascade down
  72167. if (parsedSkeleton.ranges) {
  72168. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72169. var data = parsedSkeleton.ranges[index];
  72170. skeleton.createAnimationRange(data.name, data.from, data.to);
  72171. }
  72172. }
  72173. return skeleton;
  72174. };
  72175. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72176. if (forceUpdate === void 0) { forceUpdate = false; }
  72177. var renderId = this._scene.getRenderId();
  72178. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72179. this.bones[0].computeAbsoluteTransforms();
  72180. this._lastAbsoluteTransformsUpdateId = renderId;
  72181. }
  72182. };
  72183. Skeleton.prototype.getPoseMatrix = function () {
  72184. var poseMatrix = null;
  72185. if (this._meshesWithPoseMatrix.length > 0) {
  72186. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72187. }
  72188. return poseMatrix;
  72189. };
  72190. Skeleton.prototype.sortBones = function () {
  72191. var bones = new Array();
  72192. var visited = new Array(this.bones.length);
  72193. for (var index = 0; index < this.bones.length; index++) {
  72194. this._sortBones(index, bones, visited);
  72195. }
  72196. this.bones = bones;
  72197. };
  72198. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72199. if (visited[index]) {
  72200. return;
  72201. }
  72202. visited[index] = true;
  72203. var bone = this.bones[index];
  72204. if (bone._index === undefined) {
  72205. bone._index = index;
  72206. }
  72207. var parentBone = bone.getParent();
  72208. if (parentBone) {
  72209. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72210. }
  72211. bones.push(bone);
  72212. };
  72213. return Skeleton;
  72214. }());
  72215. BABYLON.Skeleton = Skeleton;
  72216. })(BABYLON || (BABYLON = {}));
  72217. //# sourceMappingURL=babylon.skeleton.js.map
  72218. var BABYLON;
  72219. (function (BABYLON) {
  72220. var SphericalPolynomial = /** @class */ (function () {
  72221. function SphericalPolynomial() {
  72222. this.x = BABYLON.Vector3.Zero();
  72223. this.y = BABYLON.Vector3.Zero();
  72224. this.z = BABYLON.Vector3.Zero();
  72225. this.xx = BABYLON.Vector3.Zero();
  72226. this.yy = BABYLON.Vector3.Zero();
  72227. this.zz = BABYLON.Vector3.Zero();
  72228. this.xy = BABYLON.Vector3.Zero();
  72229. this.yz = BABYLON.Vector3.Zero();
  72230. this.zx = BABYLON.Vector3.Zero();
  72231. }
  72232. SphericalPolynomial.prototype.addAmbient = function (color) {
  72233. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72234. this.xx = this.xx.add(colorVector);
  72235. this.yy = this.yy.add(colorVector);
  72236. this.zz = this.zz.add(colorVector);
  72237. };
  72238. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72239. var result = new SphericalPolynomial();
  72240. result.x = harmonics.L11.scale(1.02333);
  72241. result.y = harmonics.L1_1.scale(1.02333);
  72242. result.z = harmonics.L10.scale(1.02333);
  72243. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72244. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72245. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72246. result.yz = harmonics.L2_1.scale(0.858086);
  72247. result.zx = harmonics.L21.scale(0.858086);
  72248. result.xy = harmonics.L2_2.scale(0.858086);
  72249. result.scale(1.0 / Math.PI);
  72250. return result;
  72251. };
  72252. SphericalPolynomial.prototype.scale = function (scale) {
  72253. this.x = this.x.scale(scale);
  72254. this.y = this.y.scale(scale);
  72255. this.z = this.z.scale(scale);
  72256. this.xx = this.xx.scale(scale);
  72257. this.yy = this.yy.scale(scale);
  72258. this.zz = this.zz.scale(scale);
  72259. this.yz = this.yz.scale(scale);
  72260. this.zx = this.zx.scale(scale);
  72261. this.xy = this.xy.scale(scale);
  72262. };
  72263. return SphericalPolynomial;
  72264. }());
  72265. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72266. var SphericalHarmonics = /** @class */ (function () {
  72267. function SphericalHarmonics() {
  72268. this.L00 = BABYLON.Vector3.Zero();
  72269. this.L1_1 = BABYLON.Vector3.Zero();
  72270. this.L10 = BABYLON.Vector3.Zero();
  72271. this.L11 = BABYLON.Vector3.Zero();
  72272. this.L2_2 = BABYLON.Vector3.Zero();
  72273. this.L2_1 = BABYLON.Vector3.Zero();
  72274. this.L20 = BABYLON.Vector3.Zero();
  72275. this.L21 = BABYLON.Vector3.Zero();
  72276. this.L22 = BABYLON.Vector3.Zero();
  72277. }
  72278. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72279. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72280. var c = colorVector.scale(deltaSolidAngle);
  72281. this.L00 = this.L00.add(c.scale(0.282095));
  72282. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72283. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72284. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72285. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72286. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72287. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72288. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72289. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72290. };
  72291. SphericalHarmonics.prototype.scale = function (scale) {
  72292. this.L00 = this.L00.scale(scale);
  72293. this.L1_1 = this.L1_1.scale(scale);
  72294. this.L10 = this.L10.scale(scale);
  72295. this.L11 = this.L11.scale(scale);
  72296. this.L2_2 = this.L2_2.scale(scale);
  72297. this.L2_1 = this.L2_1.scale(scale);
  72298. this.L20 = this.L20.scale(scale);
  72299. this.L21 = this.L21.scale(scale);
  72300. this.L22 = this.L22.scale(scale);
  72301. };
  72302. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72303. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72304. //
  72305. // E_lm = A_l * L_lm
  72306. //
  72307. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72308. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72309. // the scaling factors are given in equation 9.
  72310. // Constant (Band 0)
  72311. this.L00 = this.L00.scale(3.141593);
  72312. // Linear (Band 1)
  72313. this.L1_1 = this.L1_1.scale(2.094395);
  72314. this.L10 = this.L10.scale(2.094395);
  72315. this.L11 = this.L11.scale(2.094395);
  72316. // Quadratic (Band 2)
  72317. this.L2_2 = this.L2_2.scale(0.785398);
  72318. this.L2_1 = this.L2_1.scale(0.785398);
  72319. this.L20 = this.L20.scale(0.785398);
  72320. this.L21 = this.L21.scale(0.785398);
  72321. this.L22 = this.L22.scale(0.785398);
  72322. };
  72323. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72324. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72325. // L = (1/pi) * E * rho
  72326. //
  72327. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72328. this.scale(1.0 / Math.PI);
  72329. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72330. // (The pixel shader must apply albedo after texture fetches, etc).
  72331. };
  72332. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72333. var result = new SphericalHarmonics();
  72334. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72335. result.L1_1 = polynomial.y.scale(0.977204);
  72336. result.L10 = polynomial.z.scale(0.977204);
  72337. result.L11 = polynomial.x.scale(0.977204);
  72338. result.L2_2 = polynomial.xy.scale(1.16538);
  72339. result.L2_1 = polynomial.yz.scale(1.16538);
  72340. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72341. result.L21 = polynomial.zx.scale(1.16538);
  72342. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72343. result.scale(Math.PI);
  72344. return result;
  72345. };
  72346. return SphericalHarmonics;
  72347. }());
  72348. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72349. })(BABYLON || (BABYLON = {}));
  72350. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72351. var BABYLON;
  72352. (function (BABYLON) {
  72353. var FileFaceOrientation = /** @class */ (function () {
  72354. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72355. this.name = name;
  72356. this.worldAxisForNormal = worldAxisForNormal;
  72357. this.worldAxisForFileX = worldAxisForFileX;
  72358. this.worldAxisForFileY = worldAxisForFileY;
  72359. }
  72360. return FileFaceOrientation;
  72361. }());
  72362. ;
  72363. /**
  72364. * Helper class dealing with the extraction of spherical polynomial dataArray
  72365. * from a cube map.
  72366. */
  72367. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72368. function CubeMapToSphericalPolynomialTools() {
  72369. }
  72370. /**
  72371. * Converts a texture to the according Spherical Polynomial data.
  72372. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72373. *
  72374. * @param texture The texture to extract the information from.
  72375. * @return The Spherical Polynomial data.
  72376. */
  72377. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72378. if (!texture.isCube) {
  72379. // Only supports cube Textures currently.
  72380. return null;
  72381. }
  72382. var size = texture.getSize().width;
  72383. var right = texture.readPixels(0);
  72384. var left = texture.readPixels(1);
  72385. var up;
  72386. var down;
  72387. if (texture.isRenderTarget) {
  72388. up = texture.readPixels(3);
  72389. down = texture.readPixels(2);
  72390. }
  72391. else {
  72392. up = texture.readPixels(2);
  72393. down = texture.readPixels(3);
  72394. }
  72395. var front = texture.readPixels(4);
  72396. var back = texture.readPixels(5);
  72397. var gammaSpace = texture.gammaSpace;
  72398. // Always read as RGBA.
  72399. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72400. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72401. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72402. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72403. }
  72404. var cubeInfo = {
  72405. size: size,
  72406. right: right,
  72407. left: left,
  72408. up: up,
  72409. down: down,
  72410. front: front,
  72411. back: back,
  72412. format: format,
  72413. type: type,
  72414. gammaSpace: gammaSpace,
  72415. };
  72416. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72417. };
  72418. /**
  72419. * Converts a cubemap to the according Spherical Polynomial data.
  72420. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72421. *
  72422. * @param cubeInfo The Cube map to extract the information from.
  72423. * @return The Spherical Polynomial data.
  72424. */
  72425. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72426. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72427. var totalSolidAngle = 0.0;
  72428. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72429. var du = 2.0 / cubeInfo.size;
  72430. var dv = du;
  72431. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72432. var minUV = du * 0.5 - 1.0;
  72433. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72434. var fileFace = this.FileFaces[faceIndex];
  72435. var dataArray = cubeInfo[fileFace.name];
  72436. var v = minUV;
  72437. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72438. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72439. // Because SP is still linear, so summation is fine in that basis.
  72440. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72441. for (var y = 0; y < cubeInfo.size; y++) {
  72442. var u = minUV;
  72443. for (var x = 0; x < cubeInfo.size; x++) {
  72444. // World direction (not normalised)
  72445. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72446. worldDirection.normalize();
  72447. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72448. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72449. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72450. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72451. // Handle Integer types.
  72452. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72453. r /= 255;
  72454. g /= 255;
  72455. b /= 255;
  72456. }
  72457. // Handle Gamma space textures.
  72458. if (cubeInfo.gammaSpace) {
  72459. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72460. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72461. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72462. }
  72463. var color = new BABYLON.Color3(r, g, b);
  72464. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72465. totalSolidAngle += deltaSolidAngle;
  72466. u += du;
  72467. }
  72468. v += dv;
  72469. }
  72470. }
  72471. // Solid angle for entire sphere is 4*pi
  72472. var sphereSolidAngle = 4.0 * Math.PI;
  72473. // Adjust the solid angle to allow for how many faces we processed.
  72474. var facesProcessed = 6.0;
  72475. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72476. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72477. // This is needed because the numerical integration over the cube uses a
  72478. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72479. // and also to compensate for accumulative error due to float precision in the summation.
  72480. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72481. sphericalHarmonics.scale(correctionFactor);
  72482. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72483. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72484. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72485. };
  72486. CubeMapToSphericalPolynomialTools.FileFaces = [
  72487. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72488. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72489. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72490. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72491. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72492. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72493. ];
  72494. return CubeMapToSphericalPolynomialTools;
  72495. }());
  72496. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72497. })(BABYLON || (BABYLON = {}));
  72498. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72499. var BABYLON;
  72500. (function (BABYLON) {
  72501. /**
  72502. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72503. */
  72504. var PanoramaToCubeMapTools = /** @class */ (function () {
  72505. function PanoramaToCubeMapTools() {
  72506. }
  72507. /**
  72508. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72509. *
  72510. * @param float32Array The source data.
  72511. * @param inputWidth The width of the input panorama.
  72512. * @param inputhHeight The height of the input panorama.
  72513. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72514. * @return The cubemap data
  72515. */
  72516. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72517. if (!float32Array) {
  72518. throw "ConvertPanoramaToCubemap: input cannot be null";
  72519. }
  72520. if (float32Array.length != inputWidth * inputHeight * 3) {
  72521. throw "ConvertPanoramaToCubemap: input size is wrong";
  72522. }
  72523. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72524. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72525. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72526. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72527. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72528. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72529. return {
  72530. front: textureFront,
  72531. back: textureBack,
  72532. left: textureLeft,
  72533. right: textureRight,
  72534. up: textureUp,
  72535. down: textureDown,
  72536. size: size,
  72537. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72538. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72539. gammaSpace: false,
  72540. };
  72541. };
  72542. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72543. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72544. var textureArray = new Float32Array(buffer);
  72545. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72546. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72547. var dy = 1 / texSize;
  72548. var fy = 0;
  72549. for (var y = 0; y < texSize; y++) {
  72550. var xv1 = faceData[0];
  72551. var xv2 = faceData[2];
  72552. for (var x = 0; x < texSize; x++) {
  72553. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72554. v.normalize();
  72555. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72556. // 3 channels per pixels
  72557. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72558. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72559. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72560. xv1 = xv1.add(rotDX1);
  72561. xv2 = xv2.add(rotDX2);
  72562. }
  72563. fy += dy;
  72564. }
  72565. return textureArray;
  72566. };
  72567. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72568. var theta = Math.atan2(vDir.z, vDir.x);
  72569. var phi = Math.acos(vDir.y);
  72570. while (theta < -Math.PI)
  72571. theta += 2 * Math.PI;
  72572. while (theta > Math.PI)
  72573. theta -= 2 * Math.PI;
  72574. var dx = theta / Math.PI;
  72575. var dy = phi / Math.PI;
  72576. // recenter.
  72577. dx = dx * 0.5 + 0.5;
  72578. var px = Math.round(dx * inputWidth);
  72579. if (px < 0)
  72580. px = 0;
  72581. else if (px >= inputWidth)
  72582. px = inputWidth - 1;
  72583. var py = Math.round(dy * inputHeight);
  72584. if (py < 0)
  72585. py = 0;
  72586. else if (py >= inputHeight)
  72587. py = inputHeight - 1;
  72588. var inputY = (inputHeight - py - 1);
  72589. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72590. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72591. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72592. return {
  72593. r: r,
  72594. g: g,
  72595. b: b
  72596. };
  72597. };
  72598. PanoramaToCubeMapTools.FACE_FRONT = [
  72599. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72600. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72601. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72602. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72603. ];
  72604. PanoramaToCubeMapTools.FACE_BACK = [
  72605. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72606. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72607. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72608. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72609. ];
  72610. PanoramaToCubeMapTools.FACE_RIGHT = [
  72611. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72612. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72613. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72614. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72615. ];
  72616. PanoramaToCubeMapTools.FACE_LEFT = [
  72617. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72618. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72619. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72620. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72621. ];
  72622. PanoramaToCubeMapTools.FACE_DOWN = [
  72623. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72624. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72625. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72626. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72627. ];
  72628. PanoramaToCubeMapTools.FACE_UP = [
  72629. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72630. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72631. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72632. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72633. ];
  72634. return PanoramaToCubeMapTools;
  72635. }());
  72636. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72637. })(BABYLON || (BABYLON = {}));
  72638. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72639. var BABYLON;
  72640. (function (BABYLON) {
  72641. ;
  72642. /**
  72643. * This groups tools to convert HDR texture to native colors array.
  72644. */
  72645. var HDRTools = /** @class */ (function () {
  72646. function HDRTools() {
  72647. }
  72648. HDRTools.Ldexp = function (mantissa, exponent) {
  72649. if (exponent > 1023) {
  72650. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72651. }
  72652. if (exponent < -1074) {
  72653. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72654. }
  72655. return mantissa * Math.pow(2, exponent);
  72656. };
  72657. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72658. if (exponent > 0) {
  72659. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72660. float32array[index + 0] = red * exponent;
  72661. float32array[index + 1] = green * exponent;
  72662. float32array[index + 2] = blue * exponent;
  72663. }
  72664. else {
  72665. float32array[index + 0] = 0;
  72666. float32array[index + 1] = 0;
  72667. float32array[index + 2] = 0;
  72668. }
  72669. };
  72670. HDRTools.readStringLine = function (uint8array, startIndex) {
  72671. var line = "";
  72672. var character = "";
  72673. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72674. character = String.fromCharCode(uint8array[i]);
  72675. if (character == "\n") {
  72676. break;
  72677. }
  72678. line += character;
  72679. }
  72680. return line;
  72681. };
  72682. /**
  72683. * Reads header information from an RGBE texture stored in a native array.
  72684. * More information on this format are available here:
  72685. * https://en.wikipedia.org/wiki/RGBE_image_format
  72686. *
  72687. * @param uint8array The binary file stored in native array.
  72688. * @return The header information.
  72689. */
  72690. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72691. var height = 0;
  72692. var width = 0;
  72693. var line = this.readStringLine(uint8array, 0);
  72694. if (line[0] != '#' || line[1] != '?') {
  72695. throw "Bad HDR Format.";
  72696. }
  72697. var endOfHeader = false;
  72698. var findFormat = false;
  72699. var lineIndex = 0;
  72700. do {
  72701. lineIndex += (line.length + 1);
  72702. line = this.readStringLine(uint8array, lineIndex);
  72703. if (line == "FORMAT=32-bit_rle_rgbe") {
  72704. findFormat = true;
  72705. }
  72706. else if (line.length == 0) {
  72707. endOfHeader = true;
  72708. }
  72709. } while (!endOfHeader);
  72710. if (!findFormat) {
  72711. throw "HDR Bad header format, unsupported FORMAT";
  72712. }
  72713. lineIndex += (line.length + 1);
  72714. line = this.readStringLine(uint8array, lineIndex);
  72715. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72716. var match = sizeRegexp.exec(line);
  72717. // TODO. Support +Y and -X if needed.
  72718. if (!match || match.length < 3) {
  72719. throw "HDR Bad header format, no size";
  72720. }
  72721. width = parseInt(match[2]);
  72722. height = parseInt(match[1]);
  72723. if (width < 8 || width > 0x7fff) {
  72724. throw "HDR Bad header format, unsupported size";
  72725. }
  72726. lineIndex += (line.length + 1);
  72727. return {
  72728. height: height,
  72729. width: width,
  72730. dataPosition: lineIndex
  72731. };
  72732. };
  72733. /**
  72734. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72735. * This RGBE texture needs to store the information as a panorama.
  72736. *
  72737. * More information on this format are available here:
  72738. * https://en.wikipedia.org/wiki/RGBE_image_format
  72739. *
  72740. * @param buffer The binary file stored in an array buffer.
  72741. * @param size The expected size of the extracted cubemap.
  72742. * @return The Cube Map information.
  72743. */
  72744. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72745. var uint8array = new Uint8Array(buffer);
  72746. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72747. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72748. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72749. return cubeMapData;
  72750. };
  72751. /**
  72752. * Returns the pixels data extracted from an RGBE texture.
  72753. * This pixels will be stored left to right up to down in the R G B order in one array.
  72754. *
  72755. * More information on this format are available here:
  72756. * https://en.wikipedia.org/wiki/RGBE_image_format
  72757. *
  72758. * @param uint8array The binary file stored in an array buffer.
  72759. * @param hdrInfo The header information of the file.
  72760. * @return The pixels data in RGB right to left up to down order.
  72761. */
  72762. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72763. // Keep for multi format supports.
  72764. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72765. };
  72766. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72767. var num_scanlines = hdrInfo.height;
  72768. var scanline_width = hdrInfo.width;
  72769. var a, b, c, d, count;
  72770. var dataIndex = hdrInfo.dataPosition;
  72771. var index = 0, endIndex = 0, i = 0;
  72772. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72773. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72774. // 3 channels of 4 bytes per pixel in float.
  72775. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72776. var resultArray = new Float32Array(resultBuffer);
  72777. // read in each successive scanline
  72778. while (num_scanlines > 0) {
  72779. a = uint8array[dataIndex++];
  72780. b = uint8array[dataIndex++];
  72781. c = uint8array[dataIndex++];
  72782. d = uint8array[dataIndex++];
  72783. if (a != 2 || b != 2 || (c & 0x80)) {
  72784. // this file is not run length encoded
  72785. throw "HDR Bad header format, not RLE";
  72786. }
  72787. if (((c << 8) | d) != scanline_width) {
  72788. throw "HDR Bad header format, wrong scan line width";
  72789. }
  72790. index = 0;
  72791. // read each of the four channels for the scanline into the buffer
  72792. for (i = 0; i < 4; i++) {
  72793. endIndex = (i + 1) * scanline_width;
  72794. while (index < endIndex) {
  72795. a = uint8array[dataIndex++];
  72796. b = uint8array[dataIndex++];
  72797. if (a > 128) {
  72798. // a run of the same value
  72799. count = a - 128;
  72800. if ((count == 0) || (count > endIndex - index)) {
  72801. throw "HDR Bad Format, bad scanline data (run)";
  72802. }
  72803. while (count-- > 0) {
  72804. scanLineArray[index++] = b;
  72805. }
  72806. }
  72807. else {
  72808. // a non-run
  72809. count = a;
  72810. if ((count == 0) || (count > endIndex - index)) {
  72811. throw "HDR Bad Format, bad scanline data (non-run)";
  72812. }
  72813. scanLineArray[index++] = b;
  72814. if (--count > 0) {
  72815. for (var j = 0; j < count; j++) {
  72816. scanLineArray[index++] = uint8array[dataIndex++];
  72817. }
  72818. }
  72819. }
  72820. }
  72821. }
  72822. // now convert data from buffer into floats
  72823. for (i = 0; i < scanline_width; i++) {
  72824. a = scanLineArray[i];
  72825. b = scanLineArray[i + scanline_width];
  72826. c = scanLineArray[i + 2 * scanline_width];
  72827. d = scanLineArray[i + 3 * scanline_width];
  72828. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72829. }
  72830. num_scanlines--;
  72831. }
  72832. return resultArray;
  72833. };
  72834. return HDRTools;
  72835. }());
  72836. BABYLON.HDRTools = HDRTools;
  72837. })(BABYLON || (BABYLON = {}));
  72838. //# sourceMappingURL=babylon.hdr.js.map
  72839. var BABYLON;
  72840. (function (BABYLON) {
  72841. /**
  72842. * This represents a texture coming from an HDR input.
  72843. *
  72844. * The only supported format is currently panorama picture stored in RGBE format.
  72845. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72846. */
  72847. var HDRCubeTexture = /** @class */ (function (_super) {
  72848. __extends(HDRCubeTexture, _super);
  72849. /**
  72850. * Instantiates an HDRTexture from the following parameters.
  72851. *
  72852. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72853. * @param scene The scene the texture will be used in
  72854. * @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.
  72855. * @param noMipmap Forces to not generate the mipmap if true
  72856. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72857. * @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)
  72858. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72859. */
  72860. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72861. if (noMipmap === void 0) { noMipmap = false; }
  72862. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72863. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72864. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72865. if (onLoad === void 0) { onLoad = null; }
  72866. if (onError === void 0) { onError = null; }
  72867. var _this = _super.call(this, scene) || this;
  72868. _this._useInGammaSpace = false;
  72869. _this._generateHarmonics = true;
  72870. _this._isBABYLONPreprocessed = false;
  72871. _this._onLoad = null;
  72872. _this._onError = null;
  72873. /**
  72874. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72875. */
  72876. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72877. /**
  72878. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72879. * This is usefull at run time to apply the good shader.
  72880. */
  72881. _this.isPMREM = false;
  72882. _this._isBlocking = true;
  72883. /**
  72884. * Gets or sets the center of the bounding box associated with the cube texture
  72885. * It must define where the camera used to render the texture was set
  72886. */
  72887. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72888. if (!url) {
  72889. return _this;
  72890. }
  72891. _this.name = url;
  72892. _this.url = url;
  72893. _this.hasAlpha = false;
  72894. _this.isCube = true;
  72895. _this._textureMatrix = BABYLON.Matrix.Identity();
  72896. _this._onLoad = onLoad;
  72897. _this._onError = onError;
  72898. _this.gammaSpace = false;
  72899. var caps = scene.getEngine().getCaps();
  72900. if (size) {
  72901. _this._isBABYLONPreprocessed = false;
  72902. _this._noMipmap = noMipmap;
  72903. _this._size = size;
  72904. _this._useInGammaSpace = useInGammaSpace;
  72905. _this._usePMREMGenerator = usePMREMGenerator &&
  72906. caps.textureLOD &&
  72907. caps.textureFloat &&
  72908. !_this._useInGammaSpace;
  72909. }
  72910. else {
  72911. _this._isBABYLONPreprocessed = true;
  72912. _this._noMipmap = false;
  72913. _this._useInGammaSpace = false;
  72914. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72915. !_this._useInGammaSpace;
  72916. }
  72917. _this.isPMREM = _this._usePMREMGenerator;
  72918. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72919. if (!_this._texture) {
  72920. if (!scene.useDelayedTextureLoading) {
  72921. _this.loadTexture();
  72922. }
  72923. else {
  72924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72925. }
  72926. }
  72927. return _this;
  72928. }
  72929. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72930. /**
  72931. * Gets wether or not the texture is blocking during loading.
  72932. */
  72933. get: function () {
  72934. return this._isBlocking;
  72935. },
  72936. /**
  72937. * Sets wether or not the texture is blocking during loading.
  72938. */
  72939. set: function (value) {
  72940. this._isBlocking = value;
  72941. },
  72942. enumerable: true,
  72943. configurable: true
  72944. });
  72945. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72946. get: function () {
  72947. return this._boundingBoxSize;
  72948. },
  72949. /**
  72950. * Gets or sets the size of the bounding box associated with the cube texture
  72951. * When defined, the cubemap will switch to local mode
  72952. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72953. * @example https://www.babylonjs-playground.com/#RNASML
  72954. */
  72955. set: function (value) {
  72956. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72957. return;
  72958. }
  72959. this._boundingBoxSize = value;
  72960. var scene = this.getScene();
  72961. if (scene) {
  72962. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72963. }
  72964. },
  72965. enumerable: true,
  72966. configurable: true
  72967. });
  72968. /**
  72969. * Occurs when the file is a preprocessed .babylon.hdr file.
  72970. */
  72971. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72972. var _this = this;
  72973. var mipLevels = 0;
  72974. var floatArrayView = null;
  72975. var scene = this.getScene();
  72976. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72977. var mips = new Array();
  72978. if (!floatArrayView) {
  72979. return mips;
  72980. }
  72981. var startIndex = 30;
  72982. for (var level = 0; level < mipLevels; level++) {
  72983. mips.push([]);
  72984. // Fill each pixel of the mip level.
  72985. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72987. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72988. mips[level].push(faceData);
  72989. startIndex += faceSize;
  72990. }
  72991. }
  72992. return mips;
  72993. } : null;
  72994. var callback = function (buffer) {
  72995. var scene = _this.getScene();
  72996. if (!scene) {
  72997. return null;
  72998. }
  72999. // Create Native Array Views
  73000. var intArrayView = new Int32Array(buffer);
  73001. floatArrayView = new Float32Array(buffer);
  73002. // Fill header.
  73003. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73004. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73005. // Update Texture Information.
  73006. if (!_this._texture) {
  73007. return null;
  73008. }
  73009. _this._texture.updateSize(_this._size, _this._size);
  73010. // Fill polynomial information.
  73011. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73012. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73013. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73014. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73015. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73016. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73017. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73018. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73019. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73020. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73021. _this.sphericalPolynomial = sphericalPolynomial;
  73022. // Fill pixel data.
  73023. mipLevels = intArrayView[29]; // Number of mip levels.
  73024. var startIndex = 30;
  73025. var data = [];
  73026. var faceSize = Math.pow(_this._size, 2) * 3;
  73027. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73028. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73029. startIndex += faceSize;
  73030. }
  73031. var results = [];
  73032. var byteArray = null;
  73033. // Push each faces.
  73034. for (var k = 0; k < 6; k++) {
  73035. var dataFace = null;
  73036. // To be deprecated.
  73037. if (version === 1) {
  73038. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73039. dataFace = data[j];
  73040. }
  73041. // If special cases.
  73042. if (!mipmapGenerator && dataFace) {
  73043. if (!scene.getEngine().getCaps().textureFloat) {
  73044. // 3 channels of 1 bytes per pixel in bytes.
  73045. var byteBuffer = new ArrayBuffer(faceSize);
  73046. byteArray = new Uint8Array(byteBuffer);
  73047. }
  73048. for (var i = 0; i < _this._size * _this._size; i++) {
  73049. // Put in gamma space if requested.
  73050. if (_this._useInGammaSpace) {
  73051. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73052. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73053. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73054. }
  73055. // Convert to int texture for fallback.
  73056. if (byteArray) {
  73057. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73058. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73059. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73060. // May use luminance instead if the result is not accurate.
  73061. var max = Math.max(Math.max(r, g), b);
  73062. if (max > 255) {
  73063. var scale = 255 / max;
  73064. r *= scale;
  73065. g *= scale;
  73066. b *= scale;
  73067. }
  73068. byteArray[(i * 3) + 0] = r;
  73069. byteArray[(i * 3) + 1] = g;
  73070. byteArray[(i * 3) + 2] = b;
  73071. }
  73072. }
  73073. }
  73074. // Fill the array accordingly.
  73075. if (byteArray) {
  73076. results.push(byteArray);
  73077. }
  73078. else {
  73079. results.push(dataFace);
  73080. }
  73081. }
  73082. return results;
  73083. };
  73084. if (scene) {
  73085. 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);
  73086. }
  73087. };
  73088. /**
  73089. * Occurs when the file is raw .hdr file.
  73090. */
  73091. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73092. var _this = this;
  73093. var callback = function (buffer) {
  73094. var scene = _this.getScene();
  73095. if (!scene) {
  73096. return null;
  73097. }
  73098. // Extract the raw linear data.
  73099. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73100. // Generate harmonics if needed.
  73101. if (_this._generateHarmonics) {
  73102. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73103. _this.sphericalPolynomial = sphericalPolynomial;
  73104. }
  73105. var results = [];
  73106. var byteArray = null;
  73107. // Push each faces.
  73108. for (var j = 0; j < 6; j++) {
  73109. // Create uintarray fallback.
  73110. if (!scene.getEngine().getCaps().textureFloat) {
  73111. // 3 channels of 1 bytes per pixel in bytes.
  73112. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73113. byteArray = new Uint8Array(byteBuffer);
  73114. }
  73115. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73116. // If special cases.
  73117. if (_this._useInGammaSpace || byteArray) {
  73118. for (var i = 0; i < _this._size * _this._size; i++) {
  73119. // Put in gamma space if requested.
  73120. if (_this._useInGammaSpace) {
  73121. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73122. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73123. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73124. }
  73125. // Convert to int texture for fallback.
  73126. if (byteArray) {
  73127. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73128. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73129. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73130. // May use luminance instead if the result is not accurate.
  73131. var max = Math.max(Math.max(r, g), b);
  73132. if (max > 255) {
  73133. var scale = 255 / max;
  73134. r *= scale;
  73135. g *= scale;
  73136. b *= scale;
  73137. }
  73138. byteArray[(i * 3) + 0] = r;
  73139. byteArray[(i * 3) + 1] = g;
  73140. byteArray[(i * 3) + 2] = b;
  73141. }
  73142. }
  73143. }
  73144. if (byteArray) {
  73145. results.push(byteArray);
  73146. }
  73147. else {
  73148. results.push(dataFace);
  73149. }
  73150. }
  73151. return results;
  73152. };
  73153. var mipmapGenerator = null;
  73154. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73155. // if (!this._noMipmap &&
  73156. // this._usePMREMGenerator) {
  73157. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73158. // // Custom setup of the generator matching with the PBR shader values.
  73159. // var generator = new BABYLON.PMREMGenerator(data,
  73160. // this._size,
  73161. // this._size,
  73162. // 0,
  73163. // 3,
  73164. // this.getScene().getEngine().getCaps().textureFloat,
  73165. // 2048,
  73166. // 0.25,
  73167. // false,
  73168. // true);
  73169. // return generator.filterCubeMap();
  73170. // };
  73171. // }
  73172. var scene = this.getScene();
  73173. if (scene) {
  73174. 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);
  73175. }
  73176. };
  73177. /**
  73178. * Starts the loading process of the texture.
  73179. */
  73180. HDRCubeTexture.prototype.loadTexture = function () {
  73181. if (this._isBABYLONPreprocessed) {
  73182. this.loadBabylonTexture();
  73183. }
  73184. else {
  73185. this.loadHDRTexture();
  73186. }
  73187. };
  73188. HDRCubeTexture.prototype.clone = function () {
  73189. var scene = this.getScene();
  73190. if (!scene) {
  73191. return this;
  73192. }
  73193. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73194. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73195. // Base texture
  73196. newTexture.level = this.level;
  73197. newTexture.wrapU = this.wrapU;
  73198. newTexture.wrapV = this.wrapV;
  73199. newTexture.coordinatesIndex = this.coordinatesIndex;
  73200. newTexture.coordinatesMode = this.coordinatesMode;
  73201. return newTexture;
  73202. };
  73203. // Methods
  73204. HDRCubeTexture.prototype.delayLoad = function () {
  73205. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73206. return;
  73207. }
  73208. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73209. this._texture = this._getFromCache(this.url, this._noMipmap);
  73210. if (!this._texture) {
  73211. this.loadTexture();
  73212. }
  73213. };
  73214. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73215. return this._textureMatrix;
  73216. };
  73217. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73218. this._textureMatrix = value;
  73219. };
  73220. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73221. var texture = null;
  73222. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73223. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73224. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73225. texture.name = parsedTexture.name;
  73226. texture.hasAlpha = parsedTexture.hasAlpha;
  73227. texture.level = parsedTexture.level;
  73228. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73229. texture.isBlocking = parsedTexture.isBlocking;
  73230. }
  73231. if (texture) {
  73232. if (parsedTexture.boundingBoxPosition) {
  73233. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73234. }
  73235. if (parsedTexture.boundingBoxSize) {
  73236. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73237. }
  73238. }
  73239. return texture;
  73240. };
  73241. HDRCubeTexture.prototype.serialize = function () {
  73242. if (!this.name) {
  73243. return null;
  73244. }
  73245. var serializationObject = {};
  73246. serializationObject.name = this.name;
  73247. serializationObject.hasAlpha = this.hasAlpha;
  73248. serializationObject.isCube = true;
  73249. serializationObject.level = this.level;
  73250. serializationObject.size = this._size;
  73251. serializationObject.coordinatesMode = this.coordinatesMode;
  73252. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73253. serializationObject.generateHarmonics = this._generateHarmonics;
  73254. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73255. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73256. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73257. serializationObject.noMipmap = this._noMipmap;
  73258. serializationObject.isBlocking = this._isBlocking;
  73259. return serializationObject;
  73260. };
  73261. /**
  73262. * Saves as a file the data contained in the texture in a binary format.
  73263. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73264. * as the spherical used in the lighting.
  73265. * @param url The HDR file url.
  73266. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73267. * @param onError Method called if any error happens during download.
  73268. * @return The packed binary data.
  73269. */
  73270. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73271. if (onError === void 0) { onError = null; }
  73272. var callback = function (buffer) {
  73273. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73274. // Returns a URL you can use as a href.
  73275. var objUrl = window.URL.createObjectURL(data);
  73276. // Simulates a link to it and click to dowload.
  73277. var a = document.createElement("a");
  73278. document.body.appendChild(a);
  73279. a.style.display = "none";
  73280. a.href = objUrl;
  73281. a.download = "envmap.babylon.hdr";
  73282. a.click();
  73283. };
  73284. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73285. };
  73286. /**
  73287. * Serializes the data contained in the texture in a binary format.
  73288. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73289. * as the spherical used in the lighting.
  73290. * @param url The HDR file url.
  73291. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73292. * @param onError Method called if any error happens during download.
  73293. * @return The packed binary data.
  73294. */
  73295. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73296. if (onError === void 0) { onError = null; }
  73297. // Needs the url tho create the texture.
  73298. if (!url) {
  73299. return;
  73300. }
  73301. // Check Power of two size.
  73302. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73303. return;
  73304. }
  73305. // Coming Back in 3.x.
  73306. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73307. };
  73308. HDRCubeTexture._facesMapping = [
  73309. "right",
  73310. "left",
  73311. "up",
  73312. "down",
  73313. "front",
  73314. "back"
  73315. ];
  73316. return HDRCubeTexture;
  73317. }(BABYLON.BaseTexture));
  73318. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73319. })(BABYLON || (BABYLON = {}));
  73320. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73321. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73322. // Huge respect for a such great lib.
  73323. // Earcut license:
  73324. // Copyright (c) 2016, Mapbox
  73325. //
  73326. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73327. // with or without fee is hereby granted, provided that the above copyright notice
  73328. // and this permission notice appear in all copies.
  73329. //
  73330. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73331. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73332. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73333. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73334. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73335. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73336. // THIS SOFTWARE.
  73337. var Earcut;
  73338. (function (Earcut) {
  73339. /**
  73340. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73341. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73342. * @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).
  73343. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73344. */
  73345. function earcut(data, holeIndices, dim) {
  73346. dim = dim || 2;
  73347. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73348. if (!outerNode)
  73349. return triangles;
  73350. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73351. if (hasHoles)
  73352. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73353. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73354. if (data.length > 80 * dim) {
  73355. minX = maxX = data[0];
  73356. minY = maxY = data[1];
  73357. for (var i = dim; i < outerLen; i += dim) {
  73358. x = data[i];
  73359. y = data[i + 1];
  73360. if (x < minX)
  73361. minX = x;
  73362. if (y < minY)
  73363. minY = y;
  73364. if (x > maxX)
  73365. maxX = x;
  73366. if (y > maxY)
  73367. maxY = y;
  73368. }
  73369. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73370. size = Math.max(maxX - minX, maxY - minY);
  73371. }
  73372. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73373. return triangles;
  73374. }
  73375. Earcut.earcut = earcut;
  73376. var Node = /** @class */ (function () {
  73377. function Node(i, x, y) {
  73378. this.i = i;
  73379. this.x = x;
  73380. this.y = y;
  73381. this.prev = null;
  73382. this.next = null;
  73383. this.z = null;
  73384. this.prevZ = null;
  73385. this.nextZ = null;
  73386. this.steiner = false;
  73387. }
  73388. return Node;
  73389. }());
  73390. // create a circular doubly linked list from polygon points in the specified winding order
  73391. function linkedList(data, start, end, dim, clockwise) {
  73392. var i, last = null;
  73393. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73394. for (i = start; i < end; i += dim)
  73395. last = insertNode(i, data[i], data[i + 1], last);
  73396. }
  73397. else {
  73398. for (i = end - dim; i >= start; i -= dim)
  73399. last = insertNode(i, data[i], data[i + 1], last);
  73400. }
  73401. if (last && equals(last, last.next)) {
  73402. removeNode(last);
  73403. last = last.next;
  73404. }
  73405. return last;
  73406. }
  73407. // eliminate colinear or duplicate points
  73408. function filterPoints(start, end) {
  73409. if (!start)
  73410. return start;
  73411. if (!end)
  73412. end = start;
  73413. var p = start, again;
  73414. do {
  73415. again = false;
  73416. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73417. removeNode(p);
  73418. p = end = p.prev;
  73419. if (p === p.next)
  73420. return undefined;
  73421. again = true;
  73422. }
  73423. else {
  73424. p = p.next;
  73425. }
  73426. } while (again || p !== end);
  73427. return end;
  73428. }
  73429. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73430. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73431. if (!ear)
  73432. return;
  73433. // interlink polygon nodes in z-order
  73434. if (!pass && size)
  73435. indexCurve(ear, minX, minY, size);
  73436. var stop = ear, prev, next;
  73437. // iterate through ears, slicing them one by one
  73438. while (ear.prev !== ear.next) {
  73439. prev = ear.prev;
  73440. next = ear.next;
  73441. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73442. // cut off the triangle
  73443. triangles.push(prev.i / dim);
  73444. triangles.push(ear.i / dim);
  73445. triangles.push(next.i / dim);
  73446. removeNode(ear);
  73447. // skipping the next vertice leads to less sliver triangles
  73448. ear = next.next;
  73449. stop = next.next;
  73450. continue;
  73451. }
  73452. ear = next;
  73453. // if we looped through the whole remaining polygon and can't find any more ears
  73454. if (ear === stop) {
  73455. // try filtering points and slicing again
  73456. if (!pass) {
  73457. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73458. // if this didn't work, try curing all small self-intersections locally
  73459. }
  73460. else if (pass === 1) {
  73461. ear = cureLocalIntersections(ear, triangles, dim);
  73462. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73463. // as a last resort, try splitting the remaining polygon into two
  73464. }
  73465. else if (pass === 2) {
  73466. splitEarcut(ear, triangles, dim, minX, minY, size);
  73467. }
  73468. break;
  73469. }
  73470. }
  73471. }
  73472. // check whether a polygon node forms a valid ear with adjacent nodes
  73473. function isEar(ear) {
  73474. var a = ear.prev, b = ear, c = ear.next;
  73475. if (area(a, b, c) >= 0)
  73476. return false; // reflex, can't be an ear
  73477. // now make sure we don't have other points inside the potential ear
  73478. var p = ear.next.next;
  73479. while (p !== ear.prev) {
  73480. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73481. area(p.prev, p, p.next) >= 0)
  73482. return false;
  73483. p = p.next;
  73484. }
  73485. return true;
  73486. }
  73487. function isEarHashed(ear, minX, minY, size) {
  73488. var a = ear.prev, b = ear, c = ear.next;
  73489. if (area(a, b, c) >= 0)
  73490. return false; // reflex, can't be an ear
  73491. // triangle bbox; min & max are calculated like this for speed
  73492. 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);
  73493. // z-order range for the current triangle bbox;
  73494. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73495. // first look for points inside the triangle in increasing z-order
  73496. var p = ear.nextZ;
  73497. while (p && p.z <= maxZ) {
  73498. if (p !== ear.prev &&
  73499. p !== ear.next &&
  73500. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73501. area(p.prev, p, p.next) >= 0)
  73502. return false;
  73503. p = p.nextZ;
  73504. }
  73505. // then look for points in decreasing z-order
  73506. p = ear.prevZ;
  73507. while (p && p.z >= minZ) {
  73508. if (p !== ear.prev &&
  73509. p !== ear.next &&
  73510. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73511. area(p.prev, p, p.next) >= 0)
  73512. return false;
  73513. p = p.prevZ;
  73514. }
  73515. return true;
  73516. }
  73517. // go through all polygon nodes and cure small local self-intersections
  73518. function cureLocalIntersections(start, triangles, dim) {
  73519. var p = start;
  73520. do {
  73521. var a = p.prev, b = p.next.next;
  73522. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73523. triangles.push(a.i / dim);
  73524. triangles.push(p.i / dim);
  73525. triangles.push(b.i / dim);
  73526. // remove two nodes involved
  73527. removeNode(p);
  73528. removeNode(p.next);
  73529. p = start = b;
  73530. }
  73531. p = p.next;
  73532. } while (p !== start);
  73533. return p;
  73534. }
  73535. // try splitting polygon into two and triangulate them independently
  73536. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73537. // look for a valid diagonal that divides the polygon into two
  73538. var a = start;
  73539. do {
  73540. var b = a.next.next;
  73541. while (b !== a.prev) {
  73542. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73543. // split the polygon in two by the diagonal
  73544. var c = splitPolygon(a, b);
  73545. // filter colinear points around the cuts
  73546. a = filterPoints(a, a.next);
  73547. c = filterPoints(c, c.next);
  73548. // run earcut on each half
  73549. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73550. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73551. return;
  73552. }
  73553. b = b.next;
  73554. }
  73555. a = a.next;
  73556. } while (a !== start);
  73557. }
  73558. // link every hole into the outer loop, producing a single-ring polygon without holes
  73559. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73560. var queue = [], i, len, start, end, list;
  73561. for (i = 0, len = holeIndices.length; i < len; i++) {
  73562. start = holeIndices[i] * dim;
  73563. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73564. list = linkedList(data, start, end, dim, false);
  73565. if (list === list.next)
  73566. list.steiner = true;
  73567. queue.push(getLeftmost(list));
  73568. }
  73569. queue.sort(compareX);
  73570. // process holes from left to right
  73571. for (i = 0; i < queue.length; i++) {
  73572. eliminateHole(queue[i], outerNode);
  73573. outerNode = filterPoints(outerNode, outerNode.next);
  73574. }
  73575. return outerNode;
  73576. }
  73577. function compareX(a, b) {
  73578. return a.x - b.x;
  73579. }
  73580. // find a bridge between vertices that connects hole with an outer ring and and link it
  73581. function eliminateHole(hole, outerNode) {
  73582. outerNode = findHoleBridge(hole, outerNode);
  73583. if (outerNode) {
  73584. var b = splitPolygon(outerNode, hole);
  73585. filterPoints(b, b.next);
  73586. }
  73587. }
  73588. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73589. function findHoleBridge(hole, outerNode) {
  73590. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73591. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73592. // segment's endpoint with lesser x will be potential connection point
  73593. do {
  73594. if (hy <= p.y && hy >= p.next.y) {
  73595. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73596. if (x <= hx && x > qx) {
  73597. qx = x;
  73598. if (x === hx) {
  73599. if (hy === p.y)
  73600. return p;
  73601. if (hy === p.next.y)
  73602. return p.next;
  73603. }
  73604. m = p.x < p.next.x ? p : p.next;
  73605. }
  73606. }
  73607. p = p.next;
  73608. } while (p !== outerNode);
  73609. if (!m)
  73610. return null;
  73611. if (hx === qx)
  73612. return m.prev; // hole touches outer segment; pick lower endpoint
  73613. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73614. // if there are no points found, we have a valid connection;
  73615. // otherwise choose the point of the minimum angle with the ray as connection point
  73616. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73617. p = m.next;
  73618. while (p !== stop) {
  73619. if (hx >= p.x &&
  73620. p.x >= mx &&
  73621. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73622. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73623. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73624. m = p;
  73625. tanMin = tan;
  73626. }
  73627. }
  73628. p = p.next;
  73629. }
  73630. return m;
  73631. }
  73632. // interlink polygon nodes in z-order
  73633. function indexCurve(start, minX, minY, size) {
  73634. var p = start;
  73635. do {
  73636. if (p.z === null)
  73637. p.z = zOrder(p.x, p.y, minX, minY, size);
  73638. p.prevZ = p.prev;
  73639. p.nextZ = p.next;
  73640. p = p.next;
  73641. } while (p !== start);
  73642. p.prevZ.nextZ = null;
  73643. p.prevZ = null;
  73644. sortLinked(p);
  73645. }
  73646. // Simon Tatham's linked list merge sort algorithm
  73647. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73648. function sortLinked(list) {
  73649. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73650. do {
  73651. p = list;
  73652. list = null;
  73653. tail = null;
  73654. numMerges = 0;
  73655. while (p) {
  73656. numMerges++;
  73657. q = p;
  73658. pSize = 0;
  73659. for (i = 0; i < inSize; i++) {
  73660. pSize++;
  73661. q = q.nextZ;
  73662. if (!q)
  73663. break;
  73664. }
  73665. qSize = inSize;
  73666. while (pSize > 0 || (qSize > 0 && q)) {
  73667. if (pSize === 0) {
  73668. e = q;
  73669. q = q.nextZ;
  73670. qSize--;
  73671. }
  73672. else if (qSize === 0 || !q) {
  73673. e = p;
  73674. p = p.nextZ;
  73675. pSize--;
  73676. }
  73677. else if (p.z <= q.z) {
  73678. e = p;
  73679. p = p.nextZ;
  73680. pSize--;
  73681. }
  73682. else {
  73683. e = q;
  73684. q = q.nextZ;
  73685. qSize--;
  73686. }
  73687. if (tail)
  73688. tail.nextZ = e;
  73689. else
  73690. list = e;
  73691. e.prevZ = tail;
  73692. tail = e;
  73693. }
  73694. p = q;
  73695. }
  73696. tail.nextZ = null;
  73697. inSize *= 2;
  73698. } while (numMerges > 1);
  73699. return list;
  73700. }
  73701. // z-order of a point given coords and size of the data bounding box
  73702. function zOrder(x, y, minX, minY, size) {
  73703. // coords are transformed into non-negative 15-bit integer range
  73704. x = 32767 * (x - minX) / size;
  73705. y = 32767 * (y - minY) / size;
  73706. x = (x | (x << 8)) & 0x00FF00FF;
  73707. x = (x | (x << 4)) & 0x0F0F0F0F;
  73708. x = (x | (x << 2)) & 0x33333333;
  73709. x = (x | (x << 1)) & 0x55555555;
  73710. y = (y | (y << 8)) & 0x00FF00FF;
  73711. y = (y | (y << 4)) & 0x0F0F0F0F;
  73712. y = (y | (y << 2)) & 0x33333333;
  73713. y = (y | (y << 1)) & 0x55555555;
  73714. return x | (y << 1);
  73715. }
  73716. // find the leftmost node of a polygon ring
  73717. function getLeftmost(start) {
  73718. var p = start, leftmost = start;
  73719. do {
  73720. if (p.x < leftmost.x)
  73721. leftmost = p;
  73722. p = p.next;
  73723. } while (p !== start);
  73724. return leftmost;
  73725. }
  73726. // check if a point lies within a convex triangle
  73727. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73728. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73729. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73730. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73731. }
  73732. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73733. function isValidDiagonal(a, b) {
  73734. return a.next.i !== b.i &&
  73735. a.prev.i !== b.i &&
  73736. !intersectsPolygon(a, b) &&
  73737. locallyInside(a, b) &&
  73738. locallyInside(b, a) &&
  73739. middleInside(a, b);
  73740. }
  73741. // signed area of a triangle
  73742. function area(p, q, r) {
  73743. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73744. }
  73745. // check if two points are equal
  73746. function equals(p1, p2) {
  73747. return p1.x === p2.x && p1.y === p2.y;
  73748. }
  73749. // check if two segments intersect
  73750. function intersects(p1, q1, p2, q2) {
  73751. if ((equals(p1, q1) && equals(p2, q2)) ||
  73752. (equals(p1, q2) && equals(p2, q1)))
  73753. return true;
  73754. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73755. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73756. }
  73757. // check if a polygon diagonal intersects any polygon segments
  73758. function intersectsPolygon(a, b) {
  73759. var p = a;
  73760. do {
  73761. if (p.i !== a.i &&
  73762. p.next.i !== a.i &&
  73763. p.i !== b.i &&
  73764. p.next.i !== b.i &&
  73765. intersects(p, p.next, a, b))
  73766. return true;
  73767. p = p.next;
  73768. } while (p !== a);
  73769. return false;
  73770. }
  73771. // check if a polygon diagonal is locally inside the polygon
  73772. function locallyInside(a, b) {
  73773. return area(a.prev, a, a.next) < 0
  73774. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73775. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73776. }
  73777. // check if the middle point of a polygon diagonal is inside the polygon
  73778. function middleInside(a, b) {
  73779. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73780. do {
  73781. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73782. inside = !inside;
  73783. p = p.next;
  73784. } while (p !== a);
  73785. return inside;
  73786. }
  73787. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73788. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73789. function splitPolygon(a, b) {
  73790. 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;
  73791. a.next = b;
  73792. b.prev = a;
  73793. a2.next = an;
  73794. an.prev = a2;
  73795. b2.next = a2;
  73796. a2.prev = b2;
  73797. bp.next = b2;
  73798. b2.prev = bp;
  73799. return b2;
  73800. }
  73801. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73802. function insertNode(i, x, y, last) {
  73803. var p = new Node(i, x, y);
  73804. if (!last) {
  73805. p.prev = p;
  73806. p.next = p;
  73807. }
  73808. else {
  73809. p.next = last.next;
  73810. p.prev = last;
  73811. last.next.prev = p;
  73812. last.next = p;
  73813. }
  73814. return p;
  73815. }
  73816. function removeNode(p) {
  73817. p.next.prev = p.prev;
  73818. p.prev.next = p.next;
  73819. if (p.prevZ)
  73820. p.prevZ.nextZ = p.nextZ;
  73821. if (p.nextZ)
  73822. p.nextZ.prevZ = p.prevZ;
  73823. }
  73824. /**
  73825. * return a percentage difference between the polygon area and its triangulation area;
  73826. * used to verify correctness of triangulation
  73827. */
  73828. function deviation(data, holeIndices, dim, triangles) {
  73829. var hasHoles = holeIndices && holeIndices.length;
  73830. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73831. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73832. if (hasHoles) {
  73833. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73834. var start = holeIndices[i] * dim;
  73835. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73836. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73837. }
  73838. }
  73839. var trianglesArea = 0;
  73840. for (i = 0; i < triangles.length; i += 3) {
  73841. var a = triangles[i] * dim;
  73842. var b = triangles[i + 1] * dim;
  73843. var c = triangles[i + 2] * dim;
  73844. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73845. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73846. }
  73847. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73848. }
  73849. Earcut.deviation = deviation;
  73850. ;
  73851. function signedArea(data, start, end, dim) {
  73852. var sum = 0;
  73853. for (var i = start, j = end - dim; i < end; i += dim) {
  73854. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73855. j = i;
  73856. }
  73857. return sum;
  73858. }
  73859. /**
  73860. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73861. */
  73862. function flatten(data) {
  73863. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73864. for (var i = 0; i < data.length; i++) {
  73865. for (var j = 0; j < data[i].length; j++) {
  73866. for (var d = 0; d < dim; d++)
  73867. result.vertices.push(data[i][j][d]);
  73868. }
  73869. if (i > 0) {
  73870. holeIndex += data[i - 1].length;
  73871. result.holes.push(holeIndex);
  73872. }
  73873. }
  73874. return result;
  73875. }
  73876. Earcut.flatten = flatten;
  73877. ;
  73878. })(Earcut || (Earcut = {}));
  73879. //# sourceMappingURL=babylon.earcut.js.map
  73880. var BABYLON;
  73881. (function (BABYLON) {
  73882. var IndexedVector2 = /** @class */ (function (_super) {
  73883. __extends(IndexedVector2, _super);
  73884. function IndexedVector2(original, index) {
  73885. var _this = _super.call(this, original.x, original.y) || this;
  73886. _this.index = index;
  73887. return _this;
  73888. }
  73889. return IndexedVector2;
  73890. }(BABYLON.Vector2));
  73891. var PolygonPoints = /** @class */ (function () {
  73892. function PolygonPoints() {
  73893. this.elements = new Array();
  73894. }
  73895. PolygonPoints.prototype.add = function (originalPoints) {
  73896. var _this = this;
  73897. var result = new Array();
  73898. originalPoints.forEach(function (point) {
  73899. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73900. var newPoint = new IndexedVector2(point, _this.elements.length);
  73901. result.push(newPoint);
  73902. _this.elements.push(newPoint);
  73903. }
  73904. });
  73905. return result;
  73906. };
  73907. PolygonPoints.prototype.computeBounds = function () {
  73908. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73909. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73910. this.elements.forEach(function (point) {
  73911. // x
  73912. if (point.x < lmin.x) {
  73913. lmin.x = point.x;
  73914. }
  73915. else if (point.x > lmax.x) {
  73916. lmax.x = point.x;
  73917. }
  73918. // y
  73919. if (point.y < lmin.y) {
  73920. lmin.y = point.y;
  73921. }
  73922. else if (point.y > lmax.y) {
  73923. lmax.y = point.y;
  73924. }
  73925. });
  73926. return {
  73927. min: lmin,
  73928. max: lmax,
  73929. width: lmax.x - lmin.x,
  73930. height: lmax.y - lmin.y
  73931. };
  73932. };
  73933. return PolygonPoints;
  73934. }());
  73935. var Polygon = /** @class */ (function () {
  73936. function Polygon() {
  73937. }
  73938. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73939. return [
  73940. new BABYLON.Vector2(xmin, ymin),
  73941. new BABYLON.Vector2(xmax, ymin),
  73942. new BABYLON.Vector2(xmax, ymax),
  73943. new BABYLON.Vector2(xmin, ymax)
  73944. ];
  73945. };
  73946. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73947. if (cx === void 0) { cx = 0; }
  73948. if (cy === void 0) { cy = 0; }
  73949. if (numberOfSides === void 0) { numberOfSides = 32; }
  73950. var result = new Array();
  73951. var angle = 0;
  73952. var increment = (Math.PI * 2) / numberOfSides;
  73953. for (var i = 0; i < numberOfSides; i++) {
  73954. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73955. angle -= increment;
  73956. }
  73957. return result;
  73958. };
  73959. Polygon.Parse = function (input) {
  73960. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73961. var i, result = [];
  73962. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73963. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73964. }
  73965. return result;
  73966. };
  73967. Polygon.StartingAt = function (x, y) {
  73968. return BABYLON.Path2.StartingAt(x, y);
  73969. };
  73970. return Polygon;
  73971. }());
  73972. BABYLON.Polygon = Polygon;
  73973. var PolygonMeshBuilder = /** @class */ (function () {
  73974. function PolygonMeshBuilder(name, contours, scene) {
  73975. this._points = new PolygonPoints();
  73976. this._outlinepoints = new PolygonPoints();
  73977. this._holes = new Array();
  73978. this._epoints = new Array();
  73979. this._eholes = new Array();
  73980. this._name = name;
  73981. this._scene = scene;
  73982. var points;
  73983. if (contours instanceof BABYLON.Path2) {
  73984. points = contours.getPoints();
  73985. }
  73986. else {
  73987. points = contours;
  73988. }
  73989. this._addToepoint(points);
  73990. this._points.add(points);
  73991. this._outlinepoints.add(points);
  73992. }
  73993. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73994. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73995. var p = points_1[_i];
  73996. this._epoints.push(p.x, p.y);
  73997. }
  73998. };
  73999. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74000. this._points.add(hole);
  74001. var holepoints = new PolygonPoints();
  74002. holepoints.add(hole);
  74003. this._holes.push(holepoints);
  74004. this._eholes.push(this._epoints.length / 2);
  74005. this._addToepoint(hole);
  74006. return this;
  74007. };
  74008. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74009. var _this = this;
  74010. if (updatable === void 0) { updatable = false; }
  74011. if (depth === void 0) { depth = 0; }
  74012. var result = new BABYLON.Mesh(this._name, this._scene);
  74013. var normals = new Array();
  74014. var positions = new Array();
  74015. var uvs = new Array();
  74016. var bounds = this._points.computeBounds();
  74017. this._points.elements.forEach(function (p) {
  74018. normals.push(0, 1.0, 0);
  74019. positions.push(p.x, 0, p.y);
  74020. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74021. });
  74022. var indices = new Array();
  74023. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74024. for (var i = 0; i < res.length; i++) {
  74025. indices.push(res[i]);
  74026. }
  74027. if (depth > 0) {
  74028. var positionscount = (positions.length / 3); //get the current pointcount
  74029. this._points.elements.forEach(function (p) {
  74030. normals.push(0, -1.0, 0);
  74031. positions.push(p.x, -depth, p.y);
  74032. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74033. });
  74034. var totalCount = indices.length;
  74035. for (var i = 0; i < totalCount; i += 3) {
  74036. var i0 = indices[i + 0];
  74037. var i1 = indices[i + 1];
  74038. var i2 = indices[i + 2];
  74039. indices.push(i2 + positionscount);
  74040. indices.push(i1 + positionscount);
  74041. indices.push(i0 + positionscount);
  74042. }
  74043. //Add the sides
  74044. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74045. this._holes.forEach(function (hole) {
  74046. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74047. });
  74048. }
  74049. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74050. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74051. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74052. result.setIndices(indices);
  74053. return result;
  74054. };
  74055. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74056. var StartIndex = positions.length / 3;
  74057. var ulength = 0;
  74058. for (var i = 0; i < points.elements.length; i++) {
  74059. var p = points.elements[i];
  74060. var p1;
  74061. if ((i + 1) > points.elements.length - 1) {
  74062. p1 = points.elements[0];
  74063. }
  74064. else {
  74065. p1 = points.elements[i + 1];
  74066. }
  74067. positions.push(p.x, 0, p.y);
  74068. positions.push(p.x, -depth, p.y);
  74069. positions.push(p1.x, 0, p1.y);
  74070. positions.push(p1.x, -depth, p1.y);
  74071. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74072. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74073. var v3 = v2.subtract(v1);
  74074. var v4 = new BABYLON.Vector3(0, 1, 0);
  74075. var vn = BABYLON.Vector3.Cross(v3, v4);
  74076. vn = vn.normalize();
  74077. uvs.push(ulength / bounds.width, 0);
  74078. uvs.push(ulength / bounds.width, 1);
  74079. ulength += v3.length();
  74080. uvs.push((ulength / bounds.width), 0);
  74081. uvs.push((ulength / bounds.width), 1);
  74082. if (!flip) {
  74083. normals.push(-vn.x, -vn.y, -vn.z);
  74084. normals.push(-vn.x, -vn.y, -vn.z);
  74085. normals.push(-vn.x, -vn.y, -vn.z);
  74086. normals.push(-vn.x, -vn.y, -vn.z);
  74087. indices.push(StartIndex);
  74088. indices.push(StartIndex + 1);
  74089. indices.push(StartIndex + 2);
  74090. indices.push(StartIndex + 1);
  74091. indices.push(StartIndex + 3);
  74092. indices.push(StartIndex + 2);
  74093. }
  74094. else {
  74095. normals.push(vn.x, vn.y, vn.z);
  74096. normals.push(vn.x, vn.y, vn.z);
  74097. normals.push(vn.x, vn.y, vn.z);
  74098. normals.push(vn.x, vn.y, vn.z);
  74099. indices.push(StartIndex);
  74100. indices.push(StartIndex + 2);
  74101. indices.push(StartIndex + 1);
  74102. indices.push(StartIndex + 1);
  74103. indices.push(StartIndex + 2);
  74104. indices.push(StartIndex + 3);
  74105. }
  74106. StartIndex += 4;
  74107. }
  74108. ;
  74109. };
  74110. return PolygonMeshBuilder;
  74111. }());
  74112. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74113. })(BABYLON || (BABYLON = {}));
  74114. //# sourceMappingURL=babylon.polygonMesh.js.map
  74115. var BABYLON;
  74116. (function (BABYLON) {
  74117. // Unique ID when we import meshes from Babylon to CSG
  74118. var currentCSGMeshId = 0;
  74119. // # class Vertex
  74120. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74121. // one to provide additional features like texture coordinates and vertex
  74122. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74123. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74124. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74125. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74126. // is not used anywhere else.
  74127. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74128. var Vertex = /** @class */ (function () {
  74129. function Vertex(pos, normal, uv) {
  74130. this.pos = pos;
  74131. this.normal = normal;
  74132. this.uv = uv;
  74133. }
  74134. Vertex.prototype.clone = function () {
  74135. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74136. };
  74137. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74138. // orientation of a polygon is flipped.
  74139. Vertex.prototype.flip = function () {
  74140. this.normal = this.normal.scale(-1);
  74141. };
  74142. // Create a new vertex between this vertex and `other` by linearly
  74143. // interpolating all properties using a parameter of `t`. Subclasses should
  74144. // override this to interpolate additional properties.
  74145. Vertex.prototype.interpolate = function (other, t) {
  74146. 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));
  74147. };
  74148. return Vertex;
  74149. }());
  74150. // # class Plane
  74151. // Represents a plane in 3D space.
  74152. var Plane = /** @class */ (function () {
  74153. function Plane(normal, w) {
  74154. this.normal = normal;
  74155. this.w = w;
  74156. }
  74157. Plane.FromPoints = function (a, b, c) {
  74158. var v0 = c.subtract(a);
  74159. var v1 = b.subtract(a);
  74160. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74161. return null;
  74162. }
  74163. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74164. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74165. };
  74166. Plane.prototype.clone = function () {
  74167. return new Plane(this.normal.clone(), this.w);
  74168. };
  74169. Plane.prototype.flip = function () {
  74170. this.normal.scaleInPlace(-1);
  74171. this.w = -this.w;
  74172. };
  74173. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74174. // fragments in the appropriate lists. Coplanar polygons go into either
  74175. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74176. // respect to this plane. Polygons in front or in back of this plane go into
  74177. // either `front` or `back`.
  74178. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74179. var COPLANAR = 0;
  74180. var FRONT = 1;
  74181. var BACK = 2;
  74182. var SPANNING = 3;
  74183. // Classify each point as well as the entire polygon into one of the above
  74184. // four classes.
  74185. var polygonType = 0;
  74186. var types = [];
  74187. var i;
  74188. var t;
  74189. for (i = 0; i < polygon.vertices.length; i++) {
  74190. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74191. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74192. polygonType |= type;
  74193. types.push(type);
  74194. }
  74195. // Put the polygon in the correct list, splitting it when necessary.
  74196. switch (polygonType) {
  74197. case COPLANAR:
  74198. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74199. break;
  74200. case FRONT:
  74201. front.push(polygon);
  74202. break;
  74203. case BACK:
  74204. back.push(polygon);
  74205. break;
  74206. case SPANNING:
  74207. var f = [], b = [];
  74208. for (i = 0; i < polygon.vertices.length; i++) {
  74209. var j = (i + 1) % polygon.vertices.length;
  74210. var ti = types[i], tj = types[j];
  74211. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74212. if (ti !== BACK)
  74213. f.push(vi);
  74214. if (ti !== FRONT)
  74215. b.push(ti !== BACK ? vi.clone() : vi);
  74216. if ((ti | tj) === SPANNING) {
  74217. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74218. var v = vi.interpolate(vj, t);
  74219. f.push(v);
  74220. b.push(v.clone());
  74221. }
  74222. }
  74223. var poly;
  74224. if (f.length >= 3) {
  74225. poly = new Polygon(f, polygon.shared);
  74226. if (poly.plane)
  74227. front.push(poly);
  74228. }
  74229. if (b.length >= 3) {
  74230. poly = new Polygon(b, polygon.shared);
  74231. if (poly.plane)
  74232. back.push(poly);
  74233. }
  74234. break;
  74235. }
  74236. };
  74237. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74238. // point is on the plane.
  74239. Plane.EPSILON = 1e-5;
  74240. return Plane;
  74241. }());
  74242. // # class Polygon
  74243. // Represents a convex polygon. The vertices used to initialize a polygon must
  74244. // be coplanar and form a convex loop.
  74245. //
  74246. // Each convex polygon has a `shared` property, which is shared between all
  74247. // polygons that are clones of each other or were split from the same polygon.
  74248. // This can be used to define per-polygon properties (such as surface color).
  74249. var Polygon = /** @class */ (function () {
  74250. function Polygon(vertices, shared) {
  74251. this.vertices = vertices;
  74252. this.shared = shared;
  74253. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74254. }
  74255. Polygon.prototype.clone = function () {
  74256. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74257. return new Polygon(vertices, this.shared);
  74258. };
  74259. Polygon.prototype.flip = function () {
  74260. this.vertices.reverse().map(function (v) { v.flip(); });
  74261. this.plane.flip();
  74262. };
  74263. return Polygon;
  74264. }());
  74265. // # class Node
  74266. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74267. // by picking a polygon to split along. That polygon (and all other coplanar
  74268. // polygons) are added directly to that node and the other polygons are added to
  74269. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74270. // no distinction between internal and leaf nodes.
  74271. var Node = /** @class */ (function () {
  74272. function Node(polygons) {
  74273. this.plane = null;
  74274. this.front = null;
  74275. this.back = null;
  74276. this.polygons = new Array();
  74277. if (polygons) {
  74278. this.build(polygons);
  74279. }
  74280. }
  74281. Node.prototype.clone = function () {
  74282. var node = new Node();
  74283. node.plane = this.plane && this.plane.clone();
  74284. node.front = this.front && this.front.clone();
  74285. node.back = this.back && this.back.clone();
  74286. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74287. return node;
  74288. };
  74289. // Convert solid space to empty space and empty space to solid space.
  74290. Node.prototype.invert = function () {
  74291. for (var i = 0; i < this.polygons.length; i++) {
  74292. this.polygons[i].flip();
  74293. }
  74294. if (this.plane) {
  74295. this.plane.flip();
  74296. }
  74297. if (this.front) {
  74298. this.front.invert();
  74299. }
  74300. if (this.back) {
  74301. this.back.invert();
  74302. }
  74303. var temp = this.front;
  74304. this.front = this.back;
  74305. this.back = temp;
  74306. };
  74307. // Recursively remove all polygons in `polygons` that are inside this BSP
  74308. // tree.
  74309. Node.prototype.clipPolygons = function (polygons) {
  74310. if (!this.plane)
  74311. return polygons.slice();
  74312. var front = new Array(), back = new Array();
  74313. for (var i = 0; i < polygons.length; i++) {
  74314. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74315. }
  74316. if (this.front) {
  74317. front = this.front.clipPolygons(front);
  74318. }
  74319. if (this.back) {
  74320. back = this.back.clipPolygons(back);
  74321. }
  74322. else {
  74323. back = [];
  74324. }
  74325. return front.concat(back);
  74326. };
  74327. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74328. // `bsp`.
  74329. Node.prototype.clipTo = function (bsp) {
  74330. this.polygons = bsp.clipPolygons(this.polygons);
  74331. if (this.front)
  74332. this.front.clipTo(bsp);
  74333. if (this.back)
  74334. this.back.clipTo(bsp);
  74335. };
  74336. // Return a list of all polygons in this BSP tree.
  74337. Node.prototype.allPolygons = function () {
  74338. var polygons = this.polygons.slice();
  74339. if (this.front)
  74340. polygons = polygons.concat(this.front.allPolygons());
  74341. if (this.back)
  74342. polygons = polygons.concat(this.back.allPolygons());
  74343. return polygons;
  74344. };
  74345. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74346. // new polygons are filtered down to the bottom of the tree and become new
  74347. // nodes there. Each set of polygons is partitioned using the first polygon
  74348. // (no heuristic is used to pick a good split).
  74349. Node.prototype.build = function (polygons) {
  74350. if (!polygons.length)
  74351. return;
  74352. if (!this.plane)
  74353. this.plane = polygons[0].plane.clone();
  74354. var front = new Array(), back = new Array();
  74355. for (var i = 0; i < polygons.length; i++) {
  74356. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74357. }
  74358. if (front.length) {
  74359. if (!this.front)
  74360. this.front = new Node();
  74361. this.front.build(front);
  74362. }
  74363. if (back.length) {
  74364. if (!this.back)
  74365. this.back = new Node();
  74366. this.back.build(back);
  74367. }
  74368. };
  74369. return Node;
  74370. }());
  74371. var CSG = /** @class */ (function () {
  74372. function CSG() {
  74373. this.polygons = new Array();
  74374. }
  74375. // Convert BABYLON.Mesh to BABYLON.CSG
  74376. CSG.FromMesh = function (mesh) {
  74377. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74378. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74379. if (mesh instanceof BABYLON.Mesh) {
  74380. mesh.computeWorldMatrix(true);
  74381. matrix = mesh.getWorldMatrix();
  74382. meshPosition = mesh.position.clone();
  74383. meshRotation = mesh.rotation.clone();
  74384. if (mesh.rotationQuaternion) {
  74385. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74386. }
  74387. meshScaling = mesh.scaling.clone();
  74388. }
  74389. else {
  74390. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74391. }
  74392. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74393. var subMeshes = mesh.subMeshes;
  74394. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74395. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74396. vertices = [];
  74397. for (var j = 0; j < 3; j++) {
  74398. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74399. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74400. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74401. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74402. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74403. vertex = new Vertex(position, normal, uv);
  74404. vertices.push(vertex);
  74405. }
  74406. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74407. // To handle the case of degenerated triangle
  74408. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74409. if (polygon.plane)
  74410. polygons.push(polygon);
  74411. }
  74412. }
  74413. var csg = CSG.FromPolygons(polygons);
  74414. csg.matrix = matrix;
  74415. csg.position = meshPosition;
  74416. csg.rotation = meshRotation;
  74417. csg.scaling = meshScaling;
  74418. csg.rotationQuaternion = meshRotationQuaternion;
  74419. currentCSGMeshId++;
  74420. return csg;
  74421. };
  74422. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74423. CSG.FromPolygons = function (polygons) {
  74424. var csg = new CSG();
  74425. csg.polygons = polygons;
  74426. return csg;
  74427. };
  74428. CSG.prototype.clone = function () {
  74429. var csg = new CSG();
  74430. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74431. csg.copyTransformAttributes(this);
  74432. return csg;
  74433. };
  74434. CSG.prototype.union = function (csg) {
  74435. var a = new Node(this.clone().polygons);
  74436. var b = new Node(csg.clone().polygons);
  74437. a.clipTo(b);
  74438. b.clipTo(a);
  74439. b.invert();
  74440. b.clipTo(a);
  74441. b.invert();
  74442. a.build(b.allPolygons());
  74443. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74444. };
  74445. CSG.prototype.unionInPlace = function (csg) {
  74446. var a = new Node(this.polygons);
  74447. var b = new Node(csg.polygons);
  74448. a.clipTo(b);
  74449. b.clipTo(a);
  74450. b.invert();
  74451. b.clipTo(a);
  74452. b.invert();
  74453. a.build(b.allPolygons());
  74454. this.polygons = a.allPolygons();
  74455. };
  74456. CSG.prototype.subtract = function (csg) {
  74457. var a = new Node(this.clone().polygons);
  74458. var b = new Node(csg.clone().polygons);
  74459. a.invert();
  74460. a.clipTo(b);
  74461. b.clipTo(a);
  74462. b.invert();
  74463. b.clipTo(a);
  74464. b.invert();
  74465. a.build(b.allPolygons());
  74466. a.invert();
  74467. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74468. };
  74469. CSG.prototype.subtractInPlace = function (csg) {
  74470. var a = new Node(this.polygons);
  74471. var b = new Node(csg.polygons);
  74472. a.invert();
  74473. a.clipTo(b);
  74474. b.clipTo(a);
  74475. b.invert();
  74476. b.clipTo(a);
  74477. b.invert();
  74478. a.build(b.allPolygons());
  74479. a.invert();
  74480. this.polygons = a.allPolygons();
  74481. };
  74482. CSG.prototype.intersect = function (csg) {
  74483. var a = new Node(this.clone().polygons);
  74484. var b = new Node(csg.clone().polygons);
  74485. a.invert();
  74486. b.clipTo(a);
  74487. b.invert();
  74488. a.clipTo(b);
  74489. b.clipTo(a);
  74490. a.build(b.allPolygons());
  74491. a.invert();
  74492. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74493. };
  74494. CSG.prototype.intersectInPlace = function (csg) {
  74495. var a = new Node(this.polygons);
  74496. var b = new Node(csg.polygons);
  74497. a.invert();
  74498. b.clipTo(a);
  74499. b.invert();
  74500. a.clipTo(b);
  74501. b.clipTo(a);
  74502. a.build(b.allPolygons());
  74503. a.invert();
  74504. this.polygons = a.allPolygons();
  74505. };
  74506. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74507. // not modified.
  74508. CSG.prototype.inverse = function () {
  74509. var csg = this.clone();
  74510. csg.inverseInPlace();
  74511. return csg;
  74512. };
  74513. CSG.prototype.inverseInPlace = function () {
  74514. this.polygons.map(function (p) { p.flip(); });
  74515. };
  74516. // This is used to keep meshes transformations so they can be restored
  74517. // when we build back a Babylon Mesh
  74518. // NB : All CSG operations are performed in world coordinates
  74519. CSG.prototype.copyTransformAttributes = function (csg) {
  74520. this.matrix = csg.matrix;
  74521. this.position = csg.position;
  74522. this.rotation = csg.rotation;
  74523. this.scaling = csg.scaling;
  74524. this.rotationQuaternion = csg.rotationQuaternion;
  74525. return this;
  74526. };
  74527. // Build Raw mesh from CSG
  74528. // Coordinates here are in world space
  74529. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74530. var matrix = this.matrix.clone();
  74531. matrix.invert();
  74532. 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;
  74533. if (keepSubMeshes) {
  74534. // Sort Polygons, since subMeshes are indices range
  74535. polygons.sort(function (a, b) {
  74536. if (a.shared.meshId === b.shared.meshId) {
  74537. return a.shared.subMeshId - b.shared.subMeshId;
  74538. }
  74539. else {
  74540. return a.shared.meshId - b.shared.meshId;
  74541. }
  74542. });
  74543. }
  74544. for (var i = 0, il = polygons.length; i < il; i++) {
  74545. polygon = polygons[i];
  74546. // Building SubMeshes
  74547. if (!subMesh_dict[polygon.shared.meshId]) {
  74548. subMesh_dict[polygon.shared.meshId] = {};
  74549. }
  74550. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74551. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74552. indexStart: +Infinity,
  74553. indexEnd: -Infinity,
  74554. materialIndex: polygon.shared.materialIndex
  74555. };
  74556. }
  74557. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74558. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74559. polygonIndices[0] = 0;
  74560. polygonIndices[1] = j - 1;
  74561. polygonIndices[2] = j;
  74562. for (var k = 0; k < 3; k++) {
  74563. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74564. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74565. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74566. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74567. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74568. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74569. // Check if 2 points can be merged
  74570. if (!(typeof vertex_idx !== 'undefined' &&
  74571. normals[vertex_idx * 3] === localNormal.x &&
  74572. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74573. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74574. uvs[vertex_idx * 2] === uv.x &&
  74575. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74576. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74577. uvs.push(uv.x, uv.y);
  74578. normals.push(normal.x, normal.y, normal.z);
  74579. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74580. }
  74581. indices.push(vertex_idx);
  74582. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74583. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74584. currentIndex++;
  74585. }
  74586. }
  74587. }
  74588. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74589. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74590. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74591. mesh.setIndices(indices, null);
  74592. if (keepSubMeshes) {
  74593. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74594. var materialIndexOffset = 0, materialMaxIndex;
  74595. mesh.subMeshes = new Array();
  74596. for (var m in subMesh_dict) {
  74597. materialMaxIndex = -1;
  74598. for (var sm in subMesh_dict[m]) {
  74599. subMesh_obj = subMesh_dict[m][sm];
  74600. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74601. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74602. }
  74603. materialIndexOffset += ++materialMaxIndex;
  74604. }
  74605. }
  74606. return mesh;
  74607. };
  74608. // Build Mesh from CSG taking material and transforms into account
  74609. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74610. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74611. mesh.material = material;
  74612. mesh.position.copyFrom(this.position);
  74613. mesh.rotation.copyFrom(this.rotation);
  74614. if (this.rotationQuaternion) {
  74615. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74616. }
  74617. mesh.scaling.copyFrom(this.scaling);
  74618. mesh.computeWorldMatrix(true);
  74619. return mesh;
  74620. };
  74621. return CSG;
  74622. }());
  74623. BABYLON.CSG = CSG;
  74624. })(BABYLON || (BABYLON = {}));
  74625. //# sourceMappingURL=babylon.csg.js.map
  74626. var BABYLON;
  74627. (function (BABYLON) {
  74628. var LensFlare = /** @class */ (function () {
  74629. function LensFlare(size, position, color, imgUrl, system) {
  74630. this.size = size;
  74631. this.position = position;
  74632. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74633. this.color = color || new BABYLON.Color3(1, 1, 1);
  74634. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74635. this._system = system;
  74636. system.lensFlares.push(this);
  74637. }
  74638. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74639. return new LensFlare(size, position, color, imgUrl, system);
  74640. };
  74641. LensFlare.prototype.dispose = function () {
  74642. if (this.texture) {
  74643. this.texture.dispose();
  74644. }
  74645. // Remove from scene
  74646. var index = this._system.lensFlares.indexOf(this);
  74647. this._system.lensFlares.splice(index, 1);
  74648. };
  74649. ;
  74650. return LensFlare;
  74651. }());
  74652. BABYLON.LensFlare = LensFlare;
  74653. })(BABYLON || (BABYLON = {}));
  74654. //# sourceMappingURL=babylon.lensFlare.js.map
  74655. var BABYLON;
  74656. (function (BABYLON) {
  74657. var LensFlareSystem = /** @class */ (function () {
  74658. function LensFlareSystem(name, emitter, scene) {
  74659. this.name = name;
  74660. this.lensFlares = new Array();
  74661. this.borderLimit = 300;
  74662. this.viewportBorder = 0;
  74663. this.layerMask = 0x0FFFFFFF;
  74664. this._vertexBuffers = {};
  74665. this._isEnabled = true;
  74666. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74667. this._emitter = emitter;
  74668. this.id = name;
  74669. scene.lensFlareSystems.push(this);
  74670. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74671. var engine = scene.getEngine();
  74672. // VBO
  74673. var vertices = [];
  74674. vertices.push(1, 1);
  74675. vertices.push(-1, 1);
  74676. vertices.push(-1, -1);
  74677. vertices.push(1, -1);
  74678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74679. // Indices
  74680. var indices = [];
  74681. indices.push(0);
  74682. indices.push(1);
  74683. indices.push(2);
  74684. indices.push(0);
  74685. indices.push(2);
  74686. indices.push(3);
  74687. this._indexBuffer = engine.createIndexBuffer(indices);
  74688. // Effects
  74689. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74690. }
  74691. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74692. get: function () {
  74693. return this._isEnabled;
  74694. },
  74695. set: function (value) {
  74696. this._isEnabled = value;
  74697. },
  74698. enumerable: true,
  74699. configurable: true
  74700. });
  74701. LensFlareSystem.prototype.getScene = function () {
  74702. return this._scene;
  74703. };
  74704. LensFlareSystem.prototype.getEmitter = function () {
  74705. return this._emitter;
  74706. };
  74707. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74708. this._emitter = newEmitter;
  74709. };
  74710. LensFlareSystem.prototype.getEmitterPosition = function () {
  74711. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74712. };
  74713. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74714. var position = this.getEmitterPosition();
  74715. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74716. this._positionX = position.x;
  74717. this._positionY = position.y;
  74718. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74719. if (this.viewportBorder > 0) {
  74720. globalViewport.x -= this.viewportBorder;
  74721. globalViewport.y -= this.viewportBorder;
  74722. globalViewport.width += this.viewportBorder * 2;
  74723. globalViewport.height += this.viewportBorder * 2;
  74724. position.x += this.viewportBorder;
  74725. position.y += this.viewportBorder;
  74726. this._positionX += this.viewportBorder;
  74727. this._positionY += this.viewportBorder;
  74728. }
  74729. if (position.z > 0) {
  74730. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74731. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74732. return true;
  74733. }
  74734. return true;
  74735. }
  74736. return false;
  74737. };
  74738. LensFlareSystem.prototype._isVisible = function () {
  74739. if (!this._isEnabled || !this._scene.activeCamera) {
  74740. return false;
  74741. }
  74742. var emitterPosition = this.getEmitterPosition();
  74743. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74744. var distance = direction.length();
  74745. direction.normalize();
  74746. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74747. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74748. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74749. };
  74750. LensFlareSystem.prototype.render = function () {
  74751. if (!this._effect.isReady() || !this._scene.activeCamera)
  74752. return false;
  74753. var engine = this._scene.getEngine();
  74754. var viewport = this._scene.activeCamera.viewport;
  74755. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74756. // Position
  74757. if (!this.computeEffectivePosition(globalViewport)) {
  74758. return false;
  74759. }
  74760. // Visibility
  74761. if (!this._isVisible()) {
  74762. return false;
  74763. }
  74764. // Intensity
  74765. var awayX;
  74766. var awayY;
  74767. if (this._positionX < this.borderLimit + globalViewport.x) {
  74768. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74769. }
  74770. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74771. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74772. }
  74773. else {
  74774. awayX = 0;
  74775. }
  74776. if (this._positionY < this.borderLimit + globalViewport.y) {
  74777. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74778. }
  74779. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74780. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74781. }
  74782. else {
  74783. awayY = 0;
  74784. }
  74785. var away = (awayX > awayY) ? awayX : awayY;
  74786. away -= this.viewportBorder;
  74787. if (away > this.borderLimit) {
  74788. away = this.borderLimit;
  74789. }
  74790. var intensity = 1.0 - (away / this.borderLimit);
  74791. if (intensity < 0) {
  74792. return false;
  74793. }
  74794. if (intensity > 1.0) {
  74795. intensity = 1.0;
  74796. }
  74797. if (this.viewportBorder > 0) {
  74798. globalViewport.x += this.viewportBorder;
  74799. globalViewport.y += this.viewportBorder;
  74800. globalViewport.width -= this.viewportBorder * 2;
  74801. globalViewport.height -= this.viewportBorder * 2;
  74802. this._positionX -= this.viewportBorder;
  74803. this._positionY -= this.viewportBorder;
  74804. }
  74805. // Position
  74806. var centerX = globalViewport.x + globalViewport.width / 2;
  74807. var centerY = globalViewport.y + globalViewport.height / 2;
  74808. var distX = centerX - this._positionX;
  74809. var distY = centerY - this._positionY;
  74810. // Effects
  74811. engine.enableEffect(this._effect);
  74812. engine.setState(false);
  74813. engine.setDepthBuffer(false);
  74814. // VBOs
  74815. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74816. // Flares
  74817. for (var index = 0; index < this.lensFlares.length; index++) {
  74818. var flare = this.lensFlares[index];
  74819. engine.setAlphaMode(flare.alphaMode);
  74820. var x = centerX - (distX * flare.position);
  74821. var y = centerY - (distY * flare.position);
  74822. var cw = flare.size;
  74823. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74824. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74825. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74826. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74827. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74828. // Texture
  74829. this._effect.setTexture("textureSampler", flare.texture);
  74830. // Color
  74831. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74832. // Draw order
  74833. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74834. }
  74835. engine.setDepthBuffer(true);
  74836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74837. return true;
  74838. };
  74839. LensFlareSystem.prototype.dispose = function () {
  74840. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74841. if (vertexBuffer) {
  74842. vertexBuffer.dispose();
  74843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74844. }
  74845. if (this._indexBuffer) {
  74846. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74847. this._indexBuffer = null;
  74848. }
  74849. while (this.lensFlares.length) {
  74850. this.lensFlares[0].dispose();
  74851. }
  74852. // Remove from scene
  74853. var index = this._scene.lensFlareSystems.indexOf(this);
  74854. this._scene.lensFlareSystems.splice(index, 1);
  74855. };
  74856. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74857. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74858. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74859. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74860. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74861. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74862. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74863. var parsedFlare = parsedLensFlareSystem.flares[index];
  74864. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74865. }
  74866. return lensFlareSystem;
  74867. };
  74868. LensFlareSystem.prototype.serialize = function () {
  74869. var serializationObject = {};
  74870. serializationObject.id = this.id;
  74871. serializationObject.name = this.name;
  74872. serializationObject.emitterId = this.getEmitter().id;
  74873. serializationObject.borderLimit = this.borderLimit;
  74874. serializationObject.flares = [];
  74875. for (var index = 0; index < this.lensFlares.length; index++) {
  74876. var flare = this.lensFlares[index];
  74877. serializationObject.flares.push({
  74878. size: flare.size,
  74879. position: flare.position,
  74880. color: flare.color.asArray(),
  74881. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74882. });
  74883. }
  74884. return serializationObject;
  74885. };
  74886. return LensFlareSystem;
  74887. }());
  74888. BABYLON.LensFlareSystem = LensFlareSystem;
  74889. })(BABYLON || (BABYLON = {}));
  74890. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74891. var BABYLON;
  74892. (function (BABYLON) {
  74893. /**
  74894. * This is a holder class for the physics joint created by the physics plugin.
  74895. * It holds a set of functions to control the underlying joint.
  74896. */
  74897. var PhysicsJoint = /** @class */ (function () {
  74898. function PhysicsJoint(type, jointData) {
  74899. this.type = type;
  74900. this.jointData = jointData;
  74901. jointData.nativeParams = jointData.nativeParams || {};
  74902. }
  74903. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74904. get: function () {
  74905. return this._physicsJoint;
  74906. },
  74907. set: function (newJoint) {
  74908. if (this._physicsJoint) {
  74909. //remove from the wolrd
  74910. }
  74911. this._physicsJoint = newJoint;
  74912. },
  74913. enumerable: true,
  74914. configurable: true
  74915. });
  74916. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74917. set: function (physicsPlugin) {
  74918. this._physicsPlugin = physicsPlugin;
  74919. },
  74920. enumerable: true,
  74921. configurable: true
  74922. });
  74923. /**
  74924. * Execute a function that is physics-plugin specific.
  74925. * @param {Function} func the function that will be executed.
  74926. * It accepts two parameters: the physics world and the physics joint.
  74927. */
  74928. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74929. func(this._physicsPlugin.world, this._physicsJoint);
  74930. };
  74931. //TODO check if the native joints are the same
  74932. //Joint Types
  74933. PhysicsJoint.DistanceJoint = 0;
  74934. PhysicsJoint.HingeJoint = 1;
  74935. PhysicsJoint.BallAndSocketJoint = 2;
  74936. PhysicsJoint.WheelJoint = 3;
  74937. PhysicsJoint.SliderJoint = 4;
  74938. //OIMO
  74939. PhysicsJoint.PrismaticJoint = 5;
  74940. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74941. PhysicsJoint.UniversalJoint = 6;
  74942. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74943. //Cannon
  74944. //Similar to a Ball-Joint. Different in params
  74945. PhysicsJoint.PointToPointJoint = 8;
  74946. //Cannon only at the moment
  74947. PhysicsJoint.SpringJoint = 9;
  74948. PhysicsJoint.LockJoint = 10;
  74949. return PhysicsJoint;
  74950. }());
  74951. BABYLON.PhysicsJoint = PhysicsJoint;
  74952. /**
  74953. * A class representing a physics distance joint.
  74954. */
  74955. var DistanceJoint = /** @class */ (function (_super) {
  74956. __extends(DistanceJoint, _super);
  74957. function DistanceJoint(jointData) {
  74958. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74959. }
  74960. /**
  74961. * Update the predefined distance.
  74962. */
  74963. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74964. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74965. };
  74966. return DistanceJoint;
  74967. }(PhysicsJoint));
  74968. BABYLON.DistanceJoint = DistanceJoint;
  74969. var MotorEnabledJoint = /** @class */ (function (_super) {
  74970. __extends(MotorEnabledJoint, _super);
  74971. function MotorEnabledJoint(type, jointData) {
  74972. return _super.call(this, type, jointData) || this;
  74973. }
  74974. /**
  74975. * Set the motor values.
  74976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74977. * @param {number} force the force to apply
  74978. * @param {number} maxForce max force for this motor.
  74979. */
  74980. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74981. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74982. };
  74983. /**
  74984. * Set the motor's limits.
  74985. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74986. */
  74987. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74988. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74989. };
  74990. return MotorEnabledJoint;
  74991. }(PhysicsJoint));
  74992. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74993. /**
  74994. * This class represents a single hinge physics joint
  74995. */
  74996. var HingeJoint = /** @class */ (function (_super) {
  74997. __extends(HingeJoint, _super);
  74998. function HingeJoint(jointData) {
  74999. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75000. }
  75001. /**
  75002. * Set the motor values.
  75003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75004. * @param {number} force the force to apply
  75005. * @param {number} maxForce max force for this motor.
  75006. */
  75007. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75008. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75009. };
  75010. /**
  75011. * Set the motor's limits.
  75012. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75013. */
  75014. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75015. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75016. };
  75017. return HingeJoint;
  75018. }(MotorEnabledJoint));
  75019. BABYLON.HingeJoint = HingeJoint;
  75020. /**
  75021. * This class represents a dual hinge physics joint (same as wheel joint)
  75022. */
  75023. var Hinge2Joint = /** @class */ (function (_super) {
  75024. __extends(Hinge2Joint, _super);
  75025. function Hinge2Joint(jointData) {
  75026. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75027. }
  75028. /**
  75029. * Set the motor values.
  75030. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75031. * @param {number} force the force to apply
  75032. * @param {number} maxForce max force for this motor.
  75033. * @param {motorIndex} the motor's index, 0 or 1.
  75034. */
  75035. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75036. if (motorIndex === void 0) { motorIndex = 0; }
  75037. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75038. };
  75039. /**
  75040. * Set the motor limits.
  75041. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75042. * @param {number} upperLimit the upper limit
  75043. * @param {number} lowerLimit lower limit
  75044. * @param {motorIndex} the motor's index, 0 or 1.
  75045. */
  75046. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75047. if (motorIndex === void 0) { motorIndex = 0; }
  75048. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75049. };
  75050. return Hinge2Joint;
  75051. }(MotorEnabledJoint));
  75052. BABYLON.Hinge2Joint = Hinge2Joint;
  75053. })(BABYLON || (BABYLON = {}));
  75054. //# sourceMappingURL=babylon.physicsJoint.js.map
  75055. var BABYLON;
  75056. (function (BABYLON) {
  75057. var PhysicsImpostor = /** @class */ (function () {
  75058. function PhysicsImpostor(object, type, _options, _scene) {
  75059. if (_options === void 0) { _options = { mass: 0 }; }
  75060. var _this = this;
  75061. this.object = object;
  75062. this.type = type;
  75063. this._options = _options;
  75064. this._scene = _scene;
  75065. this._bodyUpdateRequired = false;
  75066. this._onBeforePhysicsStepCallbacks = new Array();
  75067. this._onAfterPhysicsStepCallbacks = new Array();
  75068. this._onPhysicsCollideCallbacks = [];
  75069. this._deltaPosition = BABYLON.Vector3.Zero();
  75070. this._isDisposed = false;
  75071. //temp variables for parent rotation calculations
  75072. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75073. this._tmpQuat = new BABYLON.Quaternion();
  75074. this._tmpQuat2 = new BABYLON.Quaternion();
  75075. /**
  75076. * this function is executed by the physics engine.
  75077. */
  75078. this.beforeStep = function () {
  75079. if (!_this._physicsEngine) {
  75080. return;
  75081. }
  75082. _this.object.translate(_this._deltaPosition, -1);
  75083. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75084. _this.object.computeWorldMatrix(false);
  75085. if (_this.object.parent && _this.object.rotationQuaternion) {
  75086. _this.getParentsRotation();
  75087. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75088. }
  75089. else {
  75090. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75091. }
  75092. if (!_this._options.disableBidirectionalTransformation) {
  75093. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75094. }
  75095. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75096. func(_this);
  75097. });
  75098. };
  75099. /**
  75100. * this function is executed by the physics engine.
  75101. */
  75102. this.afterStep = function () {
  75103. if (!_this._physicsEngine) {
  75104. return;
  75105. }
  75106. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75107. func(_this);
  75108. });
  75109. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75110. // object has now its world rotation. needs to be converted to local.
  75111. if (_this.object.parent && _this.object.rotationQuaternion) {
  75112. _this.getParentsRotation();
  75113. _this._tmpQuat.conjugateInPlace();
  75114. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75115. }
  75116. // take the position set and make it the absolute position of this object.
  75117. _this.object.setAbsolutePosition(_this.object.position);
  75118. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75119. _this.object.translate(_this._deltaPosition, 1);
  75120. };
  75121. /**
  75122. * Legacy collision detection event support
  75123. */
  75124. this.onCollideEvent = null;
  75125. //event and body object due to cannon's event-based architecture.
  75126. this.onCollide = function (e) {
  75127. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75128. return;
  75129. }
  75130. if (!_this._physicsEngine) {
  75131. return;
  75132. }
  75133. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75134. if (otherImpostor) {
  75135. // Legacy collision detection event support
  75136. if (_this.onCollideEvent) {
  75137. _this.onCollideEvent(_this, otherImpostor);
  75138. }
  75139. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75140. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75141. }).forEach(function (obj) {
  75142. obj.callback(_this, otherImpostor);
  75143. });
  75144. }
  75145. };
  75146. //sanity check!
  75147. if (!this.object) {
  75148. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75149. return;
  75150. }
  75151. //legacy support for old syntax.
  75152. if (!this._scene && object.getScene) {
  75153. this._scene = object.getScene();
  75154. }
  75155. if (!this._scene) {
  75156. return;
  75157. }
  75158. this._physicsEngine = this._scene.getPhysicsEngine();
  75159. if (!this._physicsEngine) {
  75160. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75161. }
  75162. else {
  75163. //set the object's quaternion, if not set
  75164. if (!this.object.rotationQuaternion) {
  75165. if (this.object.rotation) {
  75166. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75167. }
  75168. else {
  75169. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75170. }
  75171. }
  75172. //default options params
  75173. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75174. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75175. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75176. this._joints = [];
  75177. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75178. if (!this.object.parent || this._options.ignoreParent) {
  75179. this._init();
  75180. }
  75181. else if (this.object.parent.physicsImpostor) {
  75182. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75183. }
  75184. }
  75185. }
  75186. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75187. get: function () {
  75188. return this._isDisposed;
  75189. },
  75190. enumerable: true,
  75191. configurable: true
  75192. });
  75193. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75194. get: function () {
  75195. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75196. },
  75197. set: function (value) {
  75198. this.setMass(value);
  75199. },
  75200. enumerable: true,
  75201. configurable: true
  75202. });
  75203. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75204. get: function () {
  75205. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75206. },
  75207. set: function (value) {
  75208. if (!this._physicsEngine) {
  75209. return;
  75210. }
  75211. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75212. },
  75213. enumerable: true,
  75214. configurable: true
  75215. });
  75216. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75217. get: function () {
  75218. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75219. },
  75220. set: function (value) {
  75221. if (!this._physicsEngine) {
  75222. return;
  75223. }
  75224. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. /**
  75230. * This function will completly initialize this impostor.
  75231. * It will create a new body - but only if this mesh has no parent.
  75232. * If it has, this impostor will not be used other than to define the impostor
  75233. * of the child mesh.
  75234. */
  75235. PhysicsImpostor.prototype._init = function () {
  75236. if (!this._physicsEngine) {
  75237. return;
  75238. }
  75239. this._physicsEngine.removeImpostor(this);
  75240. this.physicsBody = null;
  75241. this._parent = this._parent || this._getPhysicsParent();
  75242. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75243. this._physicsEngine.addImpostor(this);
  75244. }
  75245. };
  75246. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75247. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75248. var parentMesh = this.object.parent;
  75249. return parentMesh.physicsImpostor;
  75250. }
  75251. return null;
  75252. };
  75253. /**
  75254. * Should a new body be generated.
  75255. */
  75256. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75257. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75258. };
  75259. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75260. this.forceUpdate();
  75261. };
  75262. /**
  75263. * Force a regeneration of this or the parent's impostor's body.
  75264. * Use under cautious - This will remove all joints already implemented.
  75265. */
  75266. PhysicsImpostor.prototype.forceUpdate = function () {
  75267. this._init();
  75268. if (this.parent && !this._options.ignoreParent) {
  75269. this.parent.forceUpdate();
  75270. }
  75271. };
  75272. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75273. /*public get mesh(): AbstractMesh {
  75274. return this._mesh;
  75275. }*/
  75276. /**
  75277. * Gets the body that holds this impostor. Either its own, or its parent.
  75278. */
  75279. get: function () {
  75280. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75281. },
  75282. /**
  75283. * Set the physics body. Used mainly by the physics engine/plugin
  75284. */
  75285. set: function (physicsBody) {
  75286. if (this._physicsBody && this._physicsEngine) {
  75287. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75288. }
  75289. this._physicsBody = physicsBody;
  75290. this.resetUpdateFlags();
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75296. get: function () {
  75297. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75298. },
  75299. set: function (value) {
  75300. this._parent = value;
  75301. },
  75302. enumerable: true,
  75303. configurable: true
  75304. });
  75305. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75306. this._bodyUpdateRequired = false;
  75307. };
  75308. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75309. if (this.object.getBoundingInfo) {
  75310. var q = this.object.rotationQuaternion;
  75311. //reset rotation
  75312. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75313. //calculate the world matrix with no rotation
  75314. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75315. var boundingInfo = this.object.getBoundingInfo();
  75316. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75317. //bring back the rotation
  75318. this.object.rotationQuaternion = q;
  75319. //calculate the world matrix with the new rotation
  75320. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75321. return size;
  75322. }
  75323. else {
  75324. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75325. }
  75326. };
  75327. PhysicsImpostor.prototype.getObjectCenter = function () {
  75328. if (this.object.getBoundingInfo) {
  75329. var boundingInfo = this.object.getBoundingInfo();
  75330. return boundingInfo.boundingBox.centerWorld;
  75331. }
  75332. else {
  75333. return this.object.position;
  75334. }
  75335. };
  75336. /**
  75337. * Get a specific parametes from the options parameter.
  75338. */
  75339. PhysicsImpostor.prototype.getParam = function (paramName) {
  75340. return this._options[paramName];
  75341. };
  75342. /**
  75343. * Sets a specific parameter in the options given to the physics plugin
  75344. */
  75345. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75346. this._options[paramName] = value;
  75347. this._bodyUpdateRequired = true;
  75348. };
  75349. /**
  75350. * Specifically change the body's mass option. Won't recreate the physics body object
  75351. */
  75352. PhysicsImpostor.prototype.setMass = function (mass) {
  75353. if (this.getParam("mass") !== mass) {
  75354. this.setParam("mass", mass);
  75355. }
  75356. if (this._physicsEngine) {
  75357. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75358. }
  75359. };
  75360. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75361. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75362. };
  75363. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75364. if (this._physicsEngine) {
  75365. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75366. }
  75367. };
  75368. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75369. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75370. };
  75371. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75372. if (this._physicsEngine) {
  75373. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75374. }
  75375. };
  75376. /**
  75377. * Execute a function with the physics plugin native code.
  75378. * Provide a function the will have two variables - the world object and the physics body object.
  75379. */
  75380. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75381. if (this._physicsEngine) {
  75382. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75383. }
  75384. };
  75385. /**
  75386. * Register a function that will be executed before the physics world is stepping forward.
  75387. */
  75388. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75389. this._onBeforePhysicsStepCallbacks.push(func);
  75390. };
  75391. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75392. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75393. if (index > -1) {
  75394. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75395. }
  75396. else {
  75397. BABYLON.Tools.Warn("Function to remove was not found");
  75398. }
  75399. };
  75400. /**
  75401. * Register a function that will be executed after the physics step
  75402. */
  75403. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75404. this._onAfterPhysicsStepCallbacks.push(func);
  75405. };
  75406. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75407. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75408. if (index > -1) {
  75409. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75410. }
  75411. else {
  75412. BABYLON.Tools.Warn("Function to remove was not found");
  75413. }
  75414. };
  75415. /**
  75416. * register a function that will be executed when this impostor collides against a different body.
  75417. */
  75418. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75419. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75420. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75421. };
  75422. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75423. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75424. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75425. if (index > -1) {
  75426. this._onPhysicsCollideCallbacks.splice(index, 1);
  75427. }
  75428. else {
  75429. BABYLON.Tools.Warn("Function to remove was not found");
  75430. }
  75431. };
  75432. PhysicsImpostor.prototype.getParentsRotation = function () {
  75433. var parent = this.object.parent;
  75434. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75435. while (parent) {
  75436. if (parent.rotationQuaternion) {
  75437. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75438. }
  75439. else {
  75440. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75441. }
  75442. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75443. parent = parent.parent;
  75444. }
  75445. return this._tmpQuat;
  75446. };
  75447. /**
  75448. * Apply a force
  75449. */
  75450. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75451. if (this._physicsEngine) {
  75452. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75453. }
  75454. return this;
  75455. };
  75456. /**
  75457. * Apply an impulse
  75458. */
  75459. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75460. if (this._physicsEngine) {
  75461. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75462. }
  75463. return this;
  75464. };
  75465. /**
  75466. * A help function to create a joint.
  75467. */
  75468. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75469. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75470. this.addJoint(otherImpostor, joint);
  75471. return this;
  75472. };
  75473. /**
  75474. * Add a joint to this impostor with a different impostor.
  75475. */
  75476. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75477. this._joints.push({
  75478. otherImpostor: otherImpostor,
  75479. joint: joint
  75480. });
  75481. if (this._physicsEngine) {
  75482. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75483. }
  75484. return this;
  75485. };
  75486. /**
  75487. * Will keep this body still, in a sleep mode.
  75488. */
  75489. PhysicsImpostor.prototype.sleep = function () {
  75490. if (this._physicsEngine) {
  75491. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75492. }
  75493. return this;
  75494. };
  75495. /**
  75496. * Wake the body up.
  75497. */
  75498. PhysicsImpostor.prototype.wakeUp = function () {
  75499. if (this._physicsEngine) {
  75500. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75501. }
  75502. return this;
  75503. };
  75504. PhysicsImpostor.prototype.clone = function (newObject) {
  75505. if (!newObject)
  75506. return null;
  75507. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75508. };
  75509. PhysicsImpostor.prototype.dispose = function () {
  75510. var _this = this;
  75511. //no dispose if no physics engine is available.
  75512. if (!this._physicsEngine) {
  75513. return;
  75514. }
  75515. this._joints.forEach(function (j) {
  75516. if (_this._physicsEngine) {
  75517. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75518. }
  75519. });
  75520. //dispose the physics body
  75521. this._physicsEngine.removeImpostor(this);
  75522. if (this.parent) {
  75523. this.parent.forceUpdate();
  75524. }
  75525. else {
  75526. /*this._object.getChildMeshes().forEach(function(mesh) {
  75527. if (mesh.physicsImpostor) {
  75528. if (disposeChildren) {
  75529. mesh.physicsImpostor.dispose();
  75530. mesh.physicsImpostor = null;
  75531. }
  75532. }
  75533. })*/
  75534. }
  75535. this._isDisposed = true;
  75536. };
  75537. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75538. this._deltaPosition.copyFrom(position);
  75539. };
  75540. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75541. if (!this._deltaRotation) {
  75542. this._deltaRotation = new BABYLON.Quaternion();
  75543. }
  75544. this._deltaRotation.copyFrom(rotation);
  75545. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75546. };
  75547. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75548. if (this._physicsEngine) {
  75549. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75550. }
  75551. return this;
  75552. };
  75553. PhysicsImpostor.prototype.getRadius = function () {
  75554. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75555. };
  75556. /**
  75557. * Sync a bone with this impostor
  75558. * @param bone The bone to sync to the impostor.
  75559. * @param boneMesh The mesh that the bone is influencing.
  75560. * @param jointPivot The pivot of the joint / bone in local space.
  75561. * @param distToJoint Optional distance from the impostor to the joint.
  75562. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75563. */
  75564. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75565. var tempVec = PhysicsImpostor._tmpVecs[0];
  75566. var mesh = this.object;
  75567. if (mesh.rotationQuaternion) {
  75568. if (adjustRotation) {
  75569. var tempQuat = PhysicsImpostor._tmpQuat;
  75570. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75571. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75572. }
  75573. else {
  75574. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75575. }
  75576. }
  75577. tempVec.x = 0;
  75578. tempVec.y = 0;
  75579. tempVec.z = 0;
  75580. if (jointPivot) {
  75581. tempVec.x = jointPivot.x;
  75582. tempVec.y = jointPivot.y;
  75583. tempVec.z = jointPivot.z;
  75584. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75585. if (distToJoint === undefined || distToJoint === null) {
  75586. distToJoint = jointPivot.length();
  75587. }
  75588. tempVec.x *= distToJoint;
  75589. tempVec.y *= distToJoint;
  75590. tempVec.z *= distToJoint;
  75591. }
  75592. if (bone.getParent()) {
  75593. tempVec.addInPlace(mesh.getAbsolutePosition());
  75594. bone.setAbsolutePosition(tempVec, boneMesh);
  75595. }
  75596. else {
  75597. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75598. boneMesh.position.x -= tempVec.x;
  75599. boneMesh.position.y -= tempVec.y;
  75600. boneMesh.position.z -= tempVec.z;
  75601. }
  75602. };
  75603. /**
  75604. * Sync impostor to a bone
  75605. * @param bone The bone that the impostor will be synced to.
  75606. * @param boneMesh The mesh that the bone is influencing.
  75607. * @param jointPivot The pivot of the joint / bone in local space.
  75608. * @param distToJoint Optional distance from the impostor to the joint.
  75609. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75610. * @param boneAxis Optional vector3 axis the bone is aligned with
  75611. */
  75612. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75613. var mesh = this.object;
  75614. if (mesh.rotationQuaternion) {
  75615. if (adjustRotation) {
  75616. var tempQuat = PhysicsImpostor._tmpQuat;
  75617. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75618. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75619. }
  75620. else {
  75621. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75622. }
  75623. }
  75624. var pos = PhysicsImpostor._tmpVecs[0];
  75625. var boneDir = PhysicsImpostor._tmpVecs[1];
  75626. if (!boneAxis) {
  75627. boneAxis = PhysicsImpostor._tmpVecs[2];
  75628. boneAxis.x = 0;
  75629. boneAxis.y = 1;
  75630. boneAxis.z = 0;
  75631. }
  75632. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75633. bone.getAbsolutePositionToRef(boneMesh, pos);
  75634. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75635. distToJoint = jointPivot.length();
  75636. }
  75637. if (distToJoint !== undefined && distToJoint !== null) {
  75638. pos.x += boneDir.x * distToJoint;
  75639. pos.y += boneDir.y * distToJoint;
  75640. pos.z += boneDir.z * distToJoint;
  75641. }
  75642. mesh.setAbsolutePosition(pos);
  75643. };
  75644. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75645. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75646. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75647. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75648. //Impostor types
  75649. PhysicsImpostor.NoImpostor = 0;
  75650. PhysicsImpostor.SphereImpostor = 1;
  75651. PhysicsImpostor.BoxImpostor = 2;
  75652. PhysicsImpostor.PlaneImpostor = 3;
  75653. PhysicsImpostor.MeshImpostor = 4;
  75654. PhysicsImpostor.CylinderImpostor = 7;
  75655. PhysicsImpostor.ParticleImpostor = 8;
  75656. PhysicsImpostor.HeightmapImpostor = 9;
  75657. return PhysicsImpostor;
  75658. }());
  75659. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75660. })(BABYLON || (BABYLON = {}));
  75661. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75662. var BABYLON;
  75663. (function (BABYLON) {
  75664. var PhysicsEngine = /** @class */ (function () {
  75665. function PhysicsEngine(gravity, _physicsPlugin) {
  75666. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75667. this._physicsPlugin = _physicsPlugin;
  75668. //new methods and parameters
  75669. this._impostors = [];
  75670. this._joints = [];
  75671. if (!this._physicsPlugin.isSupported()) {
  75672. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75673. + "Please make sure it is included.");
  75674. }
  75675. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75676. this.setGravity(gravity);
  75677. this.setTimeStep();
  75678. }
  75679. PhysicsEngine.prototype.setGravity = function (gravity) {
  75680. this.gravity = gravity;
  75681. this._physicsPlugin.setGravity(this.gravity);
  75682. };
  75683. /**
  75684. * Set the time step of the physics engine.
  75685. * default is 1/60.
  75686. * To slow it down, enter 1/600 for example.
  75687. * To speed it up, 1/30
  75688. * @param {number} newTimeStep the new timestep to apply to this world.
  75689. */
  75690. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75691. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75692. this._physicsPlugin.setTimeStep(newTimeStep);
  75693. };
  75694. /**
  75695. * Get the time step of the physics engine.
  75696. */
  75697. PhysicsEngine.prototype.getTimeStep = function () {
  75698. return this._physicsPlugin.getTimeStep();
  75699. };
  75700. PhysicsEngine.prototype.dispose = function () {
  75701. this._impostors.forEach(function (impostor) {
  75702. impostor.dispose();
  75703. });
  75704. this._physicsPlugin.dispose();
  75705. };
  75706. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75707. return this._physicsPlugin.name;
  75708. };
  75709. /**
  75710. * Adding a new impostor for the impostor tracking.
  75711. * This will be done by the impostor itself.
  75712. * @param {PhysicsImpostor} impostor the impostor to add
  75713. */
  75714. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75715. impostor.uniqueId = this._impostors.push(impostor);
  75716. //if no parent, generate the body
  75717. if (!impostor.parent) {
  75718. this._physicsPlugin.generatePhysicsBody(impostor);
  75719. }
  75720. };
  75721. /**
  75722. * Remove an impostor from the engine.
  75723. * This impostor and its mesh will not longer be updated by the physics engine.
  75724. * @param {PhysicsImpostor} impostor the impostor to remove
  75725. */
  75726. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75727. var index = this._impostors.indexOf(impostor);
  75728. if (index > -1) {
  75729. var removed = this._impostors.splice(index, 1);
  75730. //Is it needed?
  75731. if (removed.length) {
  75732. //this will also remove it from the world.
  75733. removed[0].physicsBody = null;
  75734. }
  75735. }
  75736. };
  75737. /**
  75738. * Add a joint to the physics engine
  75739. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75740. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75741. * @param {PhysicsJoint} the joint that will connect both impostors.
  75742. */
  75743. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75744. var impostorJoint = {
  75745. mainImpostor: mainImpostor,
  75746. connectedImpostor: connectedImpostor,
  75747. joint: joint
  75748. };
  75749. joint.physicsPlugin = this._physicsPlugin;
  75750. this._joints.push(impostorJoint);
  75751. this._physicsPlugin.generateJoint(impostorJoint);
  75752. };
  75753. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75754. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75755. return (impostorJoint.connectedImpostor === connectedImpostor
  75756. && impostorJoint.joint === joint
  75757. && impostorJoint.mainImpostor === mainImpostor);
  75758. });
  75759. if (matchingJoints.length) {
  75760. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75761. //TODO remove it from the list as well
  75762. }
  75763. };
  75764. /**
  75765. * Called by the scene. no need to call it.
  75766. */
  75767. PhysicsEngine.prototype._step = function (delta) {
  75768. var _this = this;
  75769. //check if any mesh has no body / requires an update
  75770. this._impostors.forEach(function (impostor) {
  75771. if (impostor.isBodyInitRequired()) {
  75772. _this._physicsPlugin.generatePhysicsBody(impostor);
  75773. }
  75774. });
  75775. if (delta > 0.1) {
  75776. delta = 0.1;
  75777. }
  75778. else if (delta <= 0) {
  75779. delta = 1.0 / 60.0;
  75780. }
  75781. this._physicsPlugin.executeStep(delta, this._impostors);
  75782. };
  75783. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75784. return this._physicsPlugin;
  75785. };
  75786. PhysicsEngine.prototype.getImpostors = function () {
  75787. return this._impostors;
  75788. };
  75789. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75790. for (var i = 0; i < this._impostors.length; ++i) {
  75791. if (this._impostors[i].object === object) {
  75792. return this._impostors[i];
  75793. }
  75794. }
  75795. return null;
  75796. };
  75797. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75798. for (var i = 0; i < this._impostors.length; ++i) {
  75799. if (this._impostors[i].physicsBody === body) {
  75800. return this._impostors[i];
  75801. }
  75802. }
  75803. return null;
  75804. };
  75805. // Statics
  75806. PhysicsEngine.Epsilon = 0.001;
  75807. return PhysicsEngine;
  75808. }());
  75809. BABYLON.PhysicsEngine = PhysicsEngine;
  75810. })(BABYLON || (BABYLON = {}));
  75811. //# sourceMappingURL=babylon.physicsEngine.js.map
  75812. var BABYLON;
  75813. (function (BABYLON) {
  75814. var PhysicsHelper = /** @class */ (function () {
  75815. function PhysicsHelper(scene) {
  75816. this._scene = scene;
  75817. this._physicsEngine = this._scene.getPhysicsEngine();
  75818. if (!this._physicsEngine) {
  75819. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75820. }
  75821. }
  75822. /**
  75823. * @param {Vector3} origin the origin of the explosion
  75824. * @param {number} radius the explosion radius
  75825. * @param {number} strength the explosion strength
  75826. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75827. */
  75828. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75829. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75830. if (!this._physicsEngine) {
  75831. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75832. return null;
  75833. }
  75834. var impostors = this._physicsEngine.getImpostors();
  75835. if (impostors.length === 0) {
  75836. return null;
  75837. }
  75838. var event = new PhysicsRadialExplosionEvent(this._scene);
  75839. impostors.forEach(function (impostor) {
  75840. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75841. if (!impostorForceAndContactPoint) {
  75842. return;
  75843. }
  75844. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75845. });
  75846. event.dispose(false);
  75847. return event;
  75848. };
  75849. /**
  75850. * @param {Vector3} origin the origin of the explosion
  75851. * @param {number} radius the explosion radius
  75852. * @param {number} strength the explosion strength
  75853. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75854. */
  75855. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75856. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75857. if (!this._physicsEngine) {
  75858. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75859. return null;
  75860. }
  75861. var impostors = this._physicsEngine.getImpostors();
  75862. if (impostors.length === 0) {
  75863. return null;
  75864. }
  75865. var event = new PhysicsRadialExplosionEvent(this._scene);
  75866. impostors.forEach(function (impostor) {
  75867. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75868. if (!impostorForceAndContactPoint) {
  75869. return;
  75870. }
  75871. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75872. });
  75873. event.dispose(false);
  75874. return event;
  75875. };
  75876. /**
  75877. * @param {Vector3} origin the origin of the explosion
  75878. * @param {number} radius the explosion radius
  75879. * @param {number} strength the explosion strength
  75880. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75881. */
  75882. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75883. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75884. if (!this._physicsEngine) {
  75885. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75886. return null;
  75887. }
  75888. var impostors = this._physicsEngine.getImpostors();
  75889. if (impostors.length === 0) {
  75890. return null;
  75891. }
  75892. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75893. event.dispose(false);
  75894. return event;
  75895. };
  75896. /**
  75897. * @param {Vector3} origin the origin of the updraft
  75898. * @param {number} radius the radius of the updraft
  75899. * @param {number} strength the strength of the updraft
  75900. * @param {number} height the height of the updraft
  75901. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75902. */
  75903. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75904. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75905. if (!this._physicsEngine) {
  75906. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75907. return null;
  75908. }
  75909. if (this._physicsEngine.getImpostors().length === 0) {
  75910. return null;
  75911. }
  75912. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75913. event.dispose(false);
  75914. return event;
  75915. };
  75916. /**
  75917. * @param {Vector3} origin the of the vortex
  75918. * @param {number} radius the radius of the vortex
  75919. * @param {number} strength the strength of the vortex
  75920. * @param {number} height the height of the vortex
  75921. */
  75922. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75923. if (!this._physicsEngine) {
  75924. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75925. return null;
  75926. }
  75927. if (this._physicsEngine.getImpostors().length === 0) {
  75928. return null;
  75929. }
  75930. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75931. event.dispose(false);
  75932. return event;
  75933. };
  75934. return PhysicsHelper;
  75935. }());
  75936. BABYLON.PhysicsHelper = PhysicsHelper;
  75937. /***** Radial explosion *****/
  75938. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75939. function PhysicsRadialExplosionEvent(scene) {
  75940. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75941. this._rays = [];
  75942. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75943. this._scene = scene;
  75944. }
  75945. /**
  75946. * Returns the data related to the radial explosion event (sphere & rays).
  75947. * @returns {PhysicsRadialExplosionEventData}
  75948. */
  75949. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75950. this._dataFetched = true;
  75951. return {
  75952. sphere: this._sphere,
  75953. rays: this._rays,
  75954. };
  75955. };
  75956. /**
  75957. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75958. * @param impostor
  75959. * @param {Vector3} origin the origin of the explosion
  75960. * @param {number} radius the explosion radius
  75961. * @param {number} strength the explosion strength
  75962. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75963. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75964. */
  75965. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75966. if (impostor.mass === 0) {
  75967. return null;
  75968. }
  75969. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75970. return null;
  75971. }
  75972. if (impostor.object.getClassName() !== 'Mesh') {
  75973. return null;
  75974. }
  75975. var impostorObject = impostor.object;
  75976. var impostorObjectCenter = impostor.getObjectCenter();
  75977. var direction = impostorObjectCenter.subtract(origin);
  75978. var ray = new BABYLON.Ray(origin, direction, radius);
  75979. this._rays.push(ray);
  75980. var hit = ray.intersectsMesh(impostorObject);
  75981. var contactPoint = hit.pickedPoint;
  75982. if (!contactPoint) {
  75983. return null;
  75984. }
  75985. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75986. if (distanceFromOrigin > radius) {
  75987. return null;
  75988. }
  75989. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75990. ? strength
  75991. : strength * (1 - (distanceFromOrigin / radius));
  75992. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75993. return { force: force, contactPoint: contactPoint };
  75994. };
  75995. /**
  75996. * Disposes the sphere.
  75997. * @param {bolean} force
  75998. */
  75999. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76000. var _this = this;
  76001. if (force === void 0) { force = true; }
  76002. if (force) {
  76003. this._sphere.dispose();
  76004. }
  76005. else {
  76006. setTimeout(function () {
  76007. if (!_this._dataFetched) {
  76008. _this._sphere.dispose();
  76009. }
  76010. }, 0);
  76011. }
  76012. };
  76013. /*** Helpers ***/
  76014. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76015. if (!this._sphere) {
  76016. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76017. this._sphere.isVisible = false;
  76018. }
  76019. };
  76020. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76021. var impostorObject = impostor.object;
  76022. this._prepareSphere();
  76023. this._sphere.position = origin;
  76024. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76025. this._sphere._updateBoundingInfo();
  76026. this._sphere.computeWorldMatrix(true);
  76027. return this._sphere.intersectsMesh(impostorObject, true);
  76028. };
  76029. return PhysicsRadialExplosionEvent;
  76030. }());
  76031. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76032. /***** Gravitational Field *****/
  76033. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76034. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76035. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76036. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76037. this._physicsHelper = physicsHelper;
  76038. this._scene = scene;
  76039. this._origin = origin;
  76040. this._radius = radius;
  76041. this._strength = strength;
  76042. this._falloff = falloff;
  76043. this._tickCallback = this._tick.bind(this);
  76044. }
  76045. /**
  76046. * Returns the data related to the gravitational field event (sphere).
  76047. * @returns {PhysicsGravitationalFieldEventData}
  76048. */
  76049. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76050. this._dataFetched = true;
  76051. return {
  76052. sphere: this._sphere,
  76053. };
  76054. };
  76055. /**
  76056. * Enables the gravitational field.
  76057. */
  76058. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76059. this._tickCallback.call(this);
  76060. this._scene.registerBeforeRender(this._tickCallback);
  76061. };
  76062. /**
  76063. * Disables the gravitational field.
  76064. */
  76065. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76066. this._scene.unregisterBeforeRender(this._tickCallback);
  76067. };
  76068. /**
  76069. * Disposes the sphere.
  76070. * @param {bolean} force
  76071. */
  76072. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76073. var _this = this;
  76074. if (force === void 0) { force = true; }
  76075. if (force) {
  76076. this._sphere.dispose();
  76077. }
  76078. else {
  76079. setTimeout(function () {
  76080. if (!_this._dataFetched) {
  76081. _this._sphere.dispose();
  76082. }
  76083. }, 0);
  76084. }
  76085. };
  76086. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76087. // Since the params won't change, we fetch the event only once
  76088. if (this._sphere) {
  76089. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76090. }
  76091. else {
  76092. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76093. if (radialExplosionEvent) {
  76094. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76095. }
  76096. }
  76097. };
  76098. return PhysicsGravitationalFieldEvent;
  76099. }());
  76100. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76101. /***** Updraft *****/
  76102. var PhysicsUpdraftEvent = /** @class */ (function () {
  76103. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76104. this._scene = _scene;
  76105. this._origin = _origin;
  76106. this._radius = _radius;
  76107. this._strength = _strength;
  76108. this._height = _height;
  76109. this._updraftMode = _updraftMode;
  76110. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76111. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76112. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76113. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76114. this._physicsEngine = this._scene.getPhysicsEngine();
  76115. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76116. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76117. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76118. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76119. }
  76120. this._tickCallback = this._tick.bind(this);
  76121. }
  76122. /**
  76123. * Returns the data related to the updraft event (cylinder).
  76124. * @returns {PhysicsUpdraftEventData}
  76125. */
  76126. PhysicsUpdraftEvent.prototype.getData = function () {
  76127. this._dataFetched = true;
  76128. return {
  76129. cylinder: this._cylinder,
  76130. };
  76131. };
  76132. /**
  76133. * Enables the updraft.
  76134. */
  76135. PhysicsUpdraftEvent.prototype.enable = function () {
  76136. this._tickCallback.call(this);
  76137. this._scene.registerBeforeRender(this._tickCallback);
  76138. };
  76139. /**
  76140. * Disables the cortex.
  76141. */
  76142. PhysicsUpdraftEvent.prototype.disable = function () {
  76143. this._scene.unregisterBeforeRender(this._tickCallback);
  76144. };
  76145. /**
  76146. * Disposes the sphere.
  76147. * @param {bolean} force
  76148. */
  76149. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76150. var _this = this;
  76151. if (force === void 0) { force = true; }
  76152. if (force) {
  76153. this._cylinder.dispose();
  76154. }
  76155. else {
  76156. setTimeout(function () {
  76157. if (!_this._dataFetched) {
  76158. _this._cylinder.dispose();
  76159. }
  76160. }, 0);
  76161. }
  76162. };
  76163. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76164. if (impostor.mass === 0) {
  76165. return null;
  76166. }
  76167. if (!this._intersectsWithCylinder(impostor)) {
  76168. return null;
  76169. }
  76170. var impostorObjectCenter = impostor.getObjectCenter();
  76171. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76172. var direction = this._originDirection;
  76173. }
  76174. else {
  76175. var direction = impostorObjectCenter.subtract(this._originTop);
  76176. }
  76177. var multiplier = this._strength * -1;
  76178. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76179. return { force: force, contactPoint: impostorObjectCenter };
  76180. };
  76181. PhysicsUpdraftEvent.prototype._tick = function () {
  76182. var _this = this;
  76183. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76184. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76185. if (!impostorForceAndContactPoint) {
  76186. return;
  76187. }
  76188. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76189. });
  76190. };
  76191. /*** Helpers ***/
  76192. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76193. if (!this._cylinder) {
  76194. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76195. height: this._height,
  76196. diameter: this._radius * 2,
  76197. }, this._scene);
  76198. this._cylinder.isVisible = false;
  76199. }
  76200. };
  76201. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76202. var impostorObject = impostor.object;
  76203. this._prepareCylinder();
  76204. this._cylinder.position = this._cylinderPosition;
  76205. return this._cylinder.intersectsMesh(impostorObject, true);
  76206. };
  76207. return PhysicsUpdraftEvent;
  76208. }());
  76209. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76210. /***** Vortex *****/
  76211. var PhysicsVortexEvent = /** @class */ (function () {
  76212. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76213. this._scene = _scene;
  76214. this._origin = _origin;
  76215. this._radius = _radius;
  76216. this._strength = _strength;
  76217. this._height = _height;
  76218. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76219. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76220. this._updraftMultiplier = 0.02;
  76221. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76222. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76223. this._physicsEngine = this._scene.getPhysicsEngine();
  76224. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76225. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76226. this._tickCallback = this._tick.bind(this);
  76227. }
  76228. /**
  76229. * Returns the data related to the vortex event (cylinder).
  76230. * @returns {PhysicsVortexEventData}
  76231. */
  76232. PhysicsVortexEvent.prototype.getData = function () {
  76233. this._dataFetched = true;
  76234. return {
  76235. cylinder: this._cylinder,
  76236. };
  76237. };
  76238. /**
  76239. * Enables the vortex.
  76240. */
  76241. PhysicsVortexEvent.prototype.enable = function () {
  76242. this._tickCallback.call(this);
  76243. this._scene.registerBeforeRender(this._tickCallback);
  76244. };
  76245. /**
  76246. * Disables the cortex.
  76247. */
  76248. PhysicsVortexEvent.prototype.disable = function () {
  76249. this._scene.unregisterBeforeRender(this._tickCallback);
  76250. };
  76251. /**
  76252. * Disposes the sphere.
  76253. * @param {bolean} force
  76254. */
  76255. PhysicsVortexEvent.prototype.dispose = function (force) {
  76256. var _this = this;
  76257. if (force === void 0) { force = true; }
  76258. if (force) {
  76259. this._cylinder.dispose();
  76260. }
  76261. else {
  76262. setTimeout(function () {
  76263. if (!_this._dataFetched) {
  76264. _this._cylinder.dispose();
  76265. }
  76266. }, 0);
  76267. }
  76268. };
  76269. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76270. if (impostor.mass === 0) {
  76271. return null;
  76272. }
  76273. if (!this._intersectsWithCylinder(impostor)) {
  76274. return null;
  76275. }
  76276. if (impostor.object.getClassName() !== 'Mesh') {
  76277. return null;
  76278. }
  76279. var impostorObject = impostor.object;
  76280. var impostorObjectCenter = impostor.getObjectCenter();
  76281. 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)
  76282. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76283. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76284. var hit = ray.intersectsMesh(impostorObject);
  76285. var contactPoint = hit.pickedPoint;
  76286. if (!contactPoint) {
  76287. return null;
  76288. }
  76289. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76290. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76291. var directionToOrigin = contactPoint.normalize();
  76292. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76293. directionToOrigin = directionToOrigin.negate();
  76294. }
  76295. // TODO: find a more physically based solution
  76296. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76297. var forceX = directionToOrigin.x * this._strength / 8;
  76298. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76299. var forceZ = directionToOrigin.z * this._strength / 8;
  76300. }
  76301. else {
  76302. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76303. var forceY = this._originTop.y * this._updraftMultiplier;
  76304. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76305. }
  76306. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76307. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76308. return { force: force, contactPoint: impostorObjectCenter };
  76309. };
  76310. PhysicsVortexEvent.prototype._tick = function () {
  76311. var _this = this;
  76312. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76313. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76314. if (!impostorForceAndContactPoint) {
  76315. return;
  76316. }
  76317. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76318. });
  76319. };
  76320. /*** Helpers ***/
  76321. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76322. if (!this._cylinder) {
  76323. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76324. height: this._height,
  76325. diameter: this._radius * 2,
  76326. }, this._scene);
  76327. this._cylinder.isVisible = false;
  76328. }
  76329. };
  76330. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76331. var impostorObject = impostor.object;
  76332. this._prepareCylinder();
  76333. this._cylinder.position = this._cylinderPosition;
  76334. return this._cylinder.intersectsMesh(impostorObject, true);
  76335. };
  76336. return PhysicsVortexEvent;
  76337. }());
  76338. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76339. /***** Enums *****/
  76340. /**
  76341. * The strenght of the force in correspondence to the distance of the affected object
  76342. */
  76343. var PhysicsRadialImpulseFalloff;
  76344. (function (PhysicsRadialImpulseFalloff) {
  76345. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76346. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76347. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76348. /**
  76349. * The strenght of the force in correspondence to the distance of the affected object
  76350. */
  76351. var PhysicsUpdraftMode;
  76352. (function (PhysicsUpdraftMode) {
  76353. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76354. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76355. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76356. })(BABYLON || (BABYLON = {}));
  76357. //# sourceMappingURL=babylon.physicsHelper.js.map
  76358. var BABYLON;
  76359. (function (BABYLON) {
  76360. var CannonJSPlugin = /** @class */ (function () {
  76361. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76362. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76363. if (iterations === void 0) { iterations = 10; }
  76364. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76365. this.name = "CannonJSPlugin";
  76366. this._physicsMaterials = new Array();
  76367. this._fixedTimeStep = 1 / 60;
  76368. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76369. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76370. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76371. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76372. this._tmpPosition = BABYLON.Vector3.Zero();
  76373. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76374. this._tmpUnityRotation = new BABYLON.Quaternion();
  76375. if (!this.isSupported()) {
  76376. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76377. return;
  76378. }
  76379. this._extendNamespace();
  76380. this.world = new this.BJSCANNON.World();
  76381. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76382. this.world.solver.iterations = iterations;
  76383. }
  76384. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76385. this.world.gravity.copy(gravity);
  76386. };
  76387. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76388. this._fixedTimeStep = timeStep;
  76389. };
  76390. CannonJSPlugin.prototype.getTimeStep = function () {
  76391. return this._fixedTimeStep;
  76392. };
  76393. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76394. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76395. };
  76396. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76397. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76398. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76399. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76400. };
  76401. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76402. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76403. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76404. impostor.physicsBody.applyForce(impulse, worldPoint);
  76405. };
  76406. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76407. //parent-child relationship. Does this impostor has a parent impostor?
  76408. if (impostor.parent) {
  76409. if (impostor.physicsBody) {
  76410. this.removePhysicsBody(impostor);
  76411. //TODO is that needed?
  76412. impostor.forceUpdate();
  76413. }
  76414. return;
  76415. }
  76416. //should a new body be created for this impostor?
  76417. if (impostor.isBodyInitRequired()) {
  76418. var shape = this._createShape(impostor);
  76419. //unregister events, if body is being changed
  76420. var oldBody = impostor.physicsBody;
  76421. if (oldBody) {
  76422. this.removePhysicsBody(impostor);
  76423. }
  76424. //create the body and material
  76425. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76426. var bodyCreationObject = {
  76427. mass: impostor.getParam("mass"),
  76428. material: material
  76429. };
  76430. // A simple extend, in case native options were used.
  76431. var nativeOptions = impostor.getParam("nativeOptions");
  76432. for (var key in nativeOptions) {
  76433. if (nativeOptions.hasOwnProperty(key)) {
  76434. bodyCreationObject[key] = nativeOptions[key];
  76435. }
  76436. }
  76437. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76438. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76439. this.world.addEventListener("preStep", impostor.beforeStep);
  76440. this.world.addEventListener("postStep", impostor.afterStep);
  76441. impostor.physicsBody.addShape(shape);
  76442. this.world.add(impostor.physicsBody);
  76443. //try to keep the body moving in the right direction by taking old properties.
  76444. //Should be tested!
  76445. if (oldBody) {
  76446. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76447. impostor.physicsBody[param].copy(oldBody[param]);
  76448. });
  76449. }
  76450. this._processChildMeshes(impostor);
  76451. }
  76452. //now update the body's transformation
  76453. this._updatePhysicsBodyTransformation(impostor);
  76454. };
  76455. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76456. var _this = this;
  76457. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76458. var currentRotation = mainImpostor.object.rotationQuaternion;
  76459. if (meshChildren.length) {
  76460. var processMesh = function (localPosition, mesh) {
  76461. if (!currentRotation || !mesh.rotationQuaternion) {
  76462. return;
  76463. }
  76464. var childImpostor = mesh.getPhysicsImpostor();
  76465. if (childImpostor) {
  76466. var parent = childImpostor.parent;
  76467. if (parent !== mainImpostor) {
  76468. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76469. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76470. if (childImpostor.physicsBody) {
  76471. _this.removePhysicsBody(childImpostor);
  76472. childImpostor.physicsBody = null;
  76473. }
  76474. childImpostor.parent = mainImpostor;
  76475. childImpostor.resetUpdateFlags();
  76476. 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));
  76477. //Add the mass of the children.
  76478. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76479. }
  76480. }
  76481. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76482. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76483. };
  76484. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76485. }
  76486. };
  76487. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76488. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76489. this.world.removeEventListener("preStep", impostor.beforeStep);
  76490. this.world.removeEventListener("postStep", impostor.afterStep);
  76491. this.world.remove(impostor.physicsBody);
  76492. };
  76493. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76494. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76495. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76496. if (!mainBody || !connectedBody) {
  76497. return;
  76498. }
  76499. var constraint;
  76500. var jointData = impostorJoint.joint.jointData;
  76501. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76502. var constraintData = {
  76503. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76504. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76505. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76506. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76507. maxForce: jointData.nativeParams.maxForce,
  76508. collideConnected: !!jointData.collision
  76509. };
  76510. switch (impostorJoint.joint.type) {
  76511. case BABYLON.PhysicsJoint.HingeJoint:
  76512. case BABYLON.PhysicsJoint.Hinge2Joint:
  76513. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76514. break;
  76515. case BABYLON.PhysicsJoint.DistanceJoint:
  76516. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76517. break;
  76518. case BABYLON.PhysicsJoint.SpringJoint:
  76519. var springData = jointData;
  76520. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76521. restLength: springData.length,
  76522. stiffness: springData.stiffness,
  76523. damping: springData.damping,
  76524. localAnchorA: constraintData.pivotA,
  76525. localAnchorB: constraintData.pivotB
  76526. });
  76527. break;
  76528. case BABYLON.PhysicsJoint.LockJoint:
  76529. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76530. break;
  76531. case BABYLON.PhysicsJoint.PointToPointJoint:
  76532. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76533. default:
  76534. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76535. break;
  76536. }
  76537. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76538. constraint.collideConnected = !!jointData.collision;
  76539. impostorJoint.joint.physicsJoint = constraint;
  76540. //don't add spring as constraint, as it is not one.
  76541. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76542. this.world.addConstraint(constraint);
  76543. }
  76544. else {
  76545. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76546. constraint.applyForce();
  76547. });
  76548. }
  76549. };
  76550. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76551. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76552. };
  76553. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76554. var index;
  76555. var mat;
  76556. for (index = 0; index < this._physicsMaterials.length; index++) {
  76557. mat = this._physicsMaterials[index];
  76558. if (mat.friction === friction && mat.restitution === restitution) {
  76559. return mat;
  76560. }
  76561. }
  76562. var currentMat = new this.BJSCANNON.Material(name);
  76563. currentMat.friction = friction;
  76564. currentMat.restitution = restitution;
  76565. this._physicsMaterials.push(currentMat);
  76566. return currentMat;
  76567. };
  76568. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76569. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76570. };
  76571. CannonJSPlugin.prototype._createShape = function (impostor) {
  76572. var object = impostor.object;
  76573. var returnValue;
  76574. var extendSize = impostor.getObjectExtendSize();
  76575. switch (impostor.type) {
  76576. case BABYLON.PhysicsImpostor.SphereImpostor:
  76577. var radiusX = extendSize.x;
  76578. var radiusY = extendSize.y;
  76579. var radiusZ = extendSize.z;
  76580. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76581. break;
  76582. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76583. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76584. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76585. break;
  76586. case BABYLON.PhysicsImpostor.BoxImpostor:
  76587. var box = extendSize.scale(0.5);
  76588. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76589. break;
  76590. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76591. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76592. returnValue = new this.BJSCANNON.Plane();
  76593. break;
  76594. case BABYLON.PhysicsImpostor.MeshImpostor:
  76595. // should transform the vertex data to world coordinates!!
  76596. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76597. var rawFaces = object.getIndices ? object.getIndices() : [];
  76598. if (!rawVerts)
  76599. return;
  76600. // get only scale! so the object could transform correctly.
  76601. var oldPosition = object.position.clone();
  76602. var oldRotation = object.rotation && object.rotation.clone();
  76603. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76604. object.position.copyFromFloats(0, 0, 0);
  76605. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76606. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76607. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76608. var transform = object.computeWorldMatrix(true);
  76609. // convert rawVerts to object space
  76610. var temp = new Array();
  76611. var index;
  76612. for (index = 0; index < rawVerts.length; index += 3) {
  76613. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76614. }
  76615. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76616. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76617. //now set back the transformation!
  76618. object.position.copyFrom(oldPosition);
  76619. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76620. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76621. break;
  76622. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76623. var oldPosition2 = object.position.clone();
  76624. var oldRotation2 = object.rotation && object.rotation.clone();
  76625. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76626. object.position.copyFromFloats(0, 0, 0);
  76627. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76628. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76629. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76630. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76631. returnValue = this._createHeightmap(object);
  76632. object.position.copyFrom(oldPosition2);
  76633. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76634. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76635. object.computeWorldMatrix(true);
  76636. break;
  76637. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76638. returnValue = new this.BJSCANNON.Particle();
  76639. break;
  76640. }
  76641. return returnValue;
  76642. };
  76643. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76644. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76645. var transform = object.computeWorldMatrix(true);
  76646. // convert rawVerts to object space
  76647. var temp = new Array();
  76648. var index;
  76649. for (index = 0; index < pos.length; index += 3) {
  76650. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76651. }
  76652. pos = temp;
  76653. var matrix = new Array();
  76654. //For now pointDepth will not be used and will be automatically calculated.
  76655. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76656. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76657. var boundingInfo = object.getBoundingInfo();
  76658. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76659. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76660. var elementSize = dim * 2 / arraySize;
  76661. for (var i = 0; i < pos.length; i = i + 3) {
  76662. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76663. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76664. var y = -pos[i + 2] + minY;
  76665. if (!matrix[x]) {
  76666. matrix[x] = [];
  76667. }
  76668. if (!matrix[x][z]) {
  76669. matrix[x][z] = y;
  76670. }
  76671. matrix[x][z] = Math.max(y, matrix[x][z]);
  76672. }
  76673. for (var x = 0; x <= arraySize; ++x) {
  76674. if (!matrix[x]) {
  76675. var loc = 1;
  76676. while (!matrix[(x + loc) % arraySize]) {
  76677. loc++;
  76678. }
  76679. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76680. //console.log("missing x", x);
  76681. }
  76682. for (var z = 0; z <= arraySize; ++z) {
  76683. if (!matrix[x][z]) {
  76684. var loc = 1;
  76685. var newValue;
  76686. while (newValue === undefined) {
  76687. newValue = matrix[x][(z + loc++) % arraySize];
  76688. }
  76689. matrix[x][z] = newValue;
  76690. }
  76691. }
  76692. }
  76693. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76694. elementSize: elementSize
  76695. });
  76696. //For future reference, needed for body transformation
  76697. shape.minY = minY;
  76698. return shape;
  76699. };
  76700. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76701. var object = impostor.object;
  76702. //make sure it is updated...
  76703. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76704. // The delta between the mesh position and the mesh bounding box center
  76705. var bInfo = object.getBoundingInfo();
  76706. if (!bInfo)
  76707. return;
  76708. var center = impostor.getObjectCenter();
  76709. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76710. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76711. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76712. this._tmpPosition.copyFrom(center);
  76713. var quaternion = object.rotationQuaternion;
  76714. if (!quaternion) {
  76715. return;
  76716. }
  76717. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76718. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76719. //-90 DEG in X, precalculated
  76720. quaternion = quaternion.multiply(this._minus90X);
  76721. //Invert! (Precalculated, 90 deg in X)
  76722. //No need to clone. this will never change.
  76723. impostor.setDeltaRotation(this._plus90X);
  76724. }
  76725. //If it is a heightfield, if should be centered.
  76726. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76727. var mesh = object;
  76728. var boundingInfo = mesh.getBoundingInfo();
  76729. //calculate the correct body position:
  76730. var rotationQuaternion = mesh.rotationQuaternion;
  76731. mesh.rotationQuaternion = this._tmpUnityRotation;
  76732. mesh.computeWorldMatrix(true);
  76733. //get original center with no rotation
  76734. var c = center.clone();
  76735. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76736. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76737. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76738. mesh.setPreTransformMatrix(p);
  76739. mesh.computeWorldMatrix(true);
  76740. //calculate the translation
  76741. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76742. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76743. //add it inverted to the delta
  76744. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76745. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76746. //rotation is back
  76747. mesh.rotationQuaternion = rotationQuaternion;
  76748. mesh.setPreTransformMatrix(oldPivot);
  76749. mesh.computeWorldMatrix(true);
  76750. }
  76751. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76752. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76753. //this._tmpPosition.copyFrom(object.position);
  76754. }
  76755. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76756. //Now update the impostor object
  76757. impostor.physicsBody.position.copy(this._tmpPosition);
  76758. impostor.physicsBody.quaternion.copy(quaternion);
  76759. };
  76760. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76761. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76762. if (impostor.object.rotationQuaternion) {
  76763. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76764. }
  76765. };
  76766. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76767. impostor.physicsBody.position.copy(newPosition);
  76768. impostor.physicsBody.quaternion.copy(newRotation);
  76769. };
  76770. CannonJSPlugin.prototype.isSupported = function () {
  76771. return this.BJSCANNON !== undefined;
  76772. };
  76773. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76774. impostor.physicsBody.velocity.copy(velocity);
  76775. };
  76776. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76777. impostor.physicsBody.angularVelocity.copy(velocity);
  76778. };
  76779. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76780. var v = impostor.physicsBody.velocity;
  76781. if (!v) {
  76782. return null;
  76783. }
  76784. return new BABYLON.Vector3(v.x, v.y, v.z);
  76785. };
  76786. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76787. var v = impostor.physicsBody.angularVelocity;
  76788. if (!v) {
  76789. return null;
  76790. }
  76791. return new BABYLON.Vector3(v.x, v.y, v.z);
  76792. };
  76793. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76794. impostor.physicsBody.mass = mass;
  76795. impostor.physicsBody.updateMassProperties();
  76796. };
  76797. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76798. return impostor.physicsBody.mass;
  76799. };
  76800. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76801. return impostor.physicsBody.material.friction;
  76802. };
  76803. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76804. impostor.physicsBody.material.friction = friction;
  76805. };
  76806. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76807. return impostor.physicsBody.material.restitution;
  76808. };
  76809. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76810. impostor.physicsBody.material.restitution = restitution;
  76811. };
  76812. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76813. impostor.physicsBody.sleep();
  76814. };
  76815. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76816. impostor.physicsBody.wakeUp();
  76817. };
  76818. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76819. joint.physicsJoint.distance = maxDistance;
  76820. };
  76821. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76822. // if (!motorIndex) {
  76823. // joint.physicsJoint.enableMotor();
  76824. // }
  76825. // }
  76826. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76827. // if (!motorIndex) {
  76828. // joint.physicsJoint.disableMotor();
  76829. // }
  76830. // }
  76831. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76832. if (!motorIndex) {
  76833. joint.physicsJoint.enableMotor();
  76834. joint.physicsJoint.setMotorSpeed(speed);
  76835. if (maxForce) {
  76836. this.setLimit(joint, maxForce);
  76837. }
  76838. }
  76839. };
  76840. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76841. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76842. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76843. };
  76844. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76845. var body = impostor.physicsBody;
  76846. mesh.position.x = body.position.x;
  76847. mesh.position.y = body.position.y;
  76848. mesh.position.z = body.position.z;
  76849. if (mesh.rotationQuaternion) {
  76850. mesh.rotationQuaternion.x = body.quaternion.x;
  76851. mesh.rotationQuaternion.y = body.quaternion.y;
  76852. mesh.rotationQuaternion.z = body.quaternion.z;
  76853. mesh.rotationQuaternion.w = body.quaternion.w;
  76854. }
  76855. };
  76856. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76857. var shape = impostor.physicsBody.shapes[0];
  76858. return shape.boundingSphereRadius;
  76859. };
  76860. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76861. var shape = impostor.physicsBody.shapes[0];
  76862. result.x = shape.halfExtents.x * 2;
  76863. result.y = shape.halfExtents.y * 2;
  76864. result.z = shape.halfExtents.z * 2;
  76865. };
  76866. CannonJSPlugin.prototype.dispose = function () {
  76867. };
  76868. CannonJSPlugin.prototype._extendNamespace = function () {
  76869. //this will force cannon to execute at least one step when using interpolation
  76870. var step_tmp1 = new this.BJSCANNON.Vec3();
  76871. var Engine = this.BJSCANNON;
  76872. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76873. maxSubSteps = maxSubSteps || 10;
  76874. timeSinceLastCalled = timeSinceLastCalled || 0;
  76875. if (timeSinceLastCalled === 0) {
  76876. this.internalStep(dt);
  76877. this.time += dt;
  76878. }
  76879. else {
  76880. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76881. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76882. var t0 = performance.now();
  76883. for (var i = 0; i !== internalSteps; i++) {
  76884. this.internalStep(dt);
  76885. if (performance.now() - t0 > dt * 1000) {
  76886. break;
  76887. }
  76888. }
  76889. this.time += timeSinceLastCalled;
  76890. var h = this.time % dt;
  76891. var h_div_dt = h / dt;
  76892. var interpvelo = step_tmp1;
  76893. var bodies = this.bodies;
  76894. for (var j = 0; j !== bodies.length; j++) {
  76895. var b = bodies[j];
  76896. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76897. b.position.vsub(b.previousPosition, interpvelo);
  76898. interpvelo.scale(h_div_dt, interpvelo);
  76899. b.position.vadd(interpvelo, b.interpolatedPosition);
  76900. }
  76901. else {
  76902. b.interpolatedPosition.copy(b.position);
  76903. b.interpolatedQuaternion.copy(b.quaternion);
  76904. }
  76905. }
  76906. }
  76907. };
  76908. };
  76909. return CannonJSPlugin;
  76910. }());
  76911. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76912. })(BABYLON || (BABYLON = {}));
  76913. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76914. var BABYLON;
  76915. (function (BABYLON) {
  76916. var OimoJSPlugin = /** @class */ (function () {
  76917. function OimoJSPlugin(iterations) {
  76918. this.name = "OimoJSPlugin";
  76919. this._tmpImpostorsArray = [];
  76920. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76921. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76922. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76923. this.world.worldscale(1);
  76924. this.world.clear();
  76925. //making sure no stats are calculated
  76926. this.world.isNoStat = true;
  76927. }
  76928. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76929. this.world.gravity.copy(gravity);
  76930. };
  76931. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76932. this.world.timeStep = timeStep;
  76933. };
  76934. OimoJSPlugin.prototype.getTimeStep = function () {
  76935. return this.world.timeStep;
  76936. };
  76937. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76938. var _this = this;
  76939. impostors.forEach(function (impostor) {
  76940. impostor.beforeStep();
  76941. });
  76942. this.world.step();
  76943. impostors.forEach(function (impostor) {
  76944. impostor.afterStep();
  76945. //update the ordered impostors array
  76946. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76947. });
  76948. //check for collisions
  76949. var contact = this.world.contacts;
  76950. while (contact !== null) {
  76951. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76952. contact = contact.next;
  76953. continue;
  76954. }
  76955. //is this body colliding with any other? get the impostor
  76956. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76957. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76958. if (!mainImpostor || !collidingImpostor) {
  76959. contact = contact.next;
  76960. continue;
  76961. }
  76962. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76963. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76964. contact = contact.next;
  76965. }
  76966. };
  76967. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76968. var mass = impostor.physicsBody.massInfo.mass;
  76969. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76970. };
  76971. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76972. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76973. this.applyImpulse(impostor, force, contactPoint);
  76974. };
  76975. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76976. var _this = this;
  76977. //parent-child relationship. Does this impostor has a parent impostor?
  76978. if (impostor.parent) {
  76979. if (impostor.physicsBody) {
  76980. this.removePhysicsBody(impostor);
  76981. //TODO is that needed?
  76982. impostor.forceUpdate();
  76983. }
  76984. return;
  76985. }
  76986. if (impostor.isBodyInitRequired()) {
  76987. var bodyConfig = {
  76988. name: impostor.uniqueId,
  76989. //Oimo must have mass, also for static objects.
  76990. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76991. size: [],
  76992. type: [],
  76993. pos: [],
  76994. rot: [],
  76995. move: impostor.getParam("mass") !== 0,
  76996. //Supporting older versions of Oimo
  76997. world: this.world
  76998. };
  76999. var impostors = [impostor];
  77000. var addToArray = function (parent) {
  77001. if (!parent.getChildMeshes)
  77002. return;
  77003. parent.getChildMeshes().forEach(function (m) {
  77004. if (m.physicsImpostor) {
  77005. impostors.push(m.physicsImpostor);
  77006. //m.physicsImpostor._init();
  77007. }
  77008. });
  77009. };
  77010. addToArray(impostor.object);
  77011. var checkWithEpsilon_1 = function (value) {
  77012. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77013. };
  77014. impostors.forEach(function (i) {
  77015. if (!impostor.object.rotationQuaternion) {
  77016. return;
  77017. }
  77018. //get the correct bounding box
  77019. var oldQuaternion = i.object.rotationQuaternion;
  77020. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77021. x: impostor.object.rotationQuaternion.x,
  77022. y: impostor.object.rotationQuaternion.y,
  77023. z: impostor.object.rotationQuaternion.z,
  77024. s: impostor.object.rotationQuaternion.w
  77025. });
  77026. var extendSize = i.getObjectExtendSize();
  77027. if (i === impostor) {
  77028. var center = impostor.getObjectCenter();
  77029. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77030. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77031. //Can also use Array.prototype.push.apply
  77032. bodyConfig.pos.push(center.x);
  77033. bodyConfig.pos.push(center.y);
  77034. bodyConfig.pos.push(center.z);
  77035. //tmp solution
  77036. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77037. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77038. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77039. }
  77040. else {
  77041. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77042. bodyConfig.pos.push(localPosition.x);
  77043. bodyConfig.pos.push(localPosition.y);
  77044. bodyConfig.pos.push(localPosition.z);
  77045. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77046. bodyConfig.rot.push(0);
  77047. bodyConfig.rot.push(0);
  77048. bodyConfig.rot.push(0);
  77049. }
  77050. // register mesh
  77051. switch (i.type) {
  77052. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77053. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77054. case BABYLON.PhysicsImpostor.SphereImpostor:
  77055. var radiusX = extendSize.x;
  77056. var radiusY = extendSize.y;
  77057. var radiusZ = extendSize.z;
  77058. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77059. bodyConfig.type.push('sphere');
  77060. //due to the way oimo works with compounds, add 3 times
  77061. bodyConfig.size.push(size);
  77062. bodyConfig.size.push(size);
  77063. bodyConfig.size.push(size);
  77064. break;
  77065. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77066. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77067. var sizeY = checkWithEpsilon_1(extendSize.y);
  77068. bodyConfig.type.push('cylinder');
  77069. bodyConfig.size.push(sizeX);
  77070. bodyConfig.size.push(sizeY);
  77071. //due to the way oimo works with compounds, add one more value.
  77072. bodyConfig.size.push(sizeY);
  77073. break;
  77074. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77075. case BABYLON.PhysicsImpostor.BoxImpostor:
  77076. default:
  77077. var sizeX = checkWithEpsilon_1(extendSize.x);
  77078. var sizeY = checkWithEpsilon_1(extendSize.y);
  77079. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77080. bodyConfig.type.push('box');
  77081. bodyConfig.size.push(sizeX);
  77082. bodyConfig.size.push(sizeY);
  77083. bodyConfig.size.push(sizeZ);
  77084. break;
  77085. }
  77086. //actually not needed, but hey...
  77087. i.object.rotationQuaternion = oldQuaternion;
  77088. });
  77089. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77090. }
  77091. else {
  77092. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77093. }
  77094. impostor.setDeltaPosition(this._tmpPositionVector);
  77095. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77096. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77097. };
  77098. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77099. //impostor.physicsBody.dispose();
  77100. //Same as : (older oimo versions)
  77101. this.world.removeRigidBody(impostor.physicsBody);
  77102. };
  77103. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77104. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77105. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77106. if (!mainBody || !connectedBody) {
  77107. return;
  77108. }
  77109. var jointData = impostorJoint.joint.jointData;
  77110. var options = jointData.nativeParams || {};
  77111. var type;
  77112. var nativeJointData = {
  77113. body1: mainBody,
  77114. body2: connectedBody,
  77115. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77116. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77117. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77118. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77119. min: options.min,
  77120. max: options.max,
  77121. collision: options.collision || jointData.collision,
  77122. spring: options.spring,
  77123. //supporting older version of Oimo
  77124. world: this.world
  77125. };
  77126. switch (impostorJoint.joint.type) {
  77127. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77128. type = "jointBall";
  77129. break;
  77130. case BABYLON.PhysicsJoint.SpringJoint:
  77131. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77132. var springData = jointData;
  77133. nativeJointData.min = springData.length || nativeJointData.min;
  77134. //Max should also be set, just make sure it is at least min
  77135. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77136. case BABYLON.PhysicsJoint.DistanceJoint:
  77137. type = "jointDistance";
  77138. nativeJointData.max = jointData.maxDistance;
  77139. break;
  77140. case BABYLON.PhysicsJoint.PrismaticJoint:
  77141. type = "jointPrisme";
  77142. break;
  77143. case BABYLON.PhysicsJoint.SliderJoint:
  77144. type = "jointSlide";
  77145. break;
  77146. case BABYLON.PhysicsJoint.WheelJoint:
  77147. type = "jointWheel";
  77148. break;
  77149. case BABYLON.PhysicsJoint.HingeJoint:
  77150. default:
  77151. type = "jointHinge";
  77152. break;
  77153. }
  77154. nativeJointData.type = type;
  77155. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77156. };
  77157. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77158. //Bug in Oimo prevents us from disposing a joint in the playground
  77159. //joint.joint.physicsJoint.dispose();
  77160. //So we will bruteforce it!
  77161. try {
  77162. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77163. }
  77164. catch (e) {
  77165. BABYLON.Tools.Warn(e);
  77166. }
  77167. };
  77168. OimoJSPlugin.prototype.isSupported = function () {
  77169. return this.BJSOIMO !== undefined;
  77170. };
  77171. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77172. if (!impostor.physicsBody.sleeping) {
  77173. //TODO check that
  77174. if (impostor.physicsBody.shapes.next) {
  77175. var parentShape = this._getLastShape(impostor.physicsBody);
  77176. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77177. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77178. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77179. }
  77180. else {
  77181. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77182. }
  77183. if (impostor.object.rotationQuaternion) {
  77184. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77185. impostor.object.rotationQuaternion.normalize();
  77186. }
  77187. }
  77188. };
  77189. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77190. var body = impostor.physicsBody;
  77191. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77192. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77193. body.syncShapes();
  77194. body.awake();
  77195. };
  77196. OimoJSPlugin.prototype._getLastShape = function (body) {
  77197. var lastShape = body.shapes;
  77198. while (lastShape.next) {
  77199. lastShape = lastShape.next;
  77200. }
  77201. return lastShape;
  77202. };
  77203. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77204. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77205. };
  77206. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77207. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77208. };
  77209. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77210. var v = impostor.physicsBody.linearVelocity;
  77211. if (!v) {
  77212. return null;
  77213. }
  77214. return new BABYLON.Vector3(v.x, v.y, v.z);
  77215. };
  77216. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77217. var v = impostor.physicsBody.angularVelocity;
  77218. if (!v) {
  77219. return null;
  77220. }
  77221. return new BABYLON.Vector3(v.x, v.y, v.z);
  77222. };
  77223. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77224. var staticBody = mass === 0;
  77225. //this will actually set the body's density and not its mass.
  77226. //But this is how oimo treats the mass variable.
  77227. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77228. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77229. };
  77230. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77231. return impostor.physicsBody.shapes.density;
  77232. };
  77233. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77234. return impostor.physicsBody.shapes.friction;
  77235. };
  77236. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77237. impostor.physicsBody.shapes.friction = friction;
  77238. };
  77239. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77240. return impostor.physicsBody.shapes.restitution;
  77241. };
  77242. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77243. impostor.physicsBody.shapes.restitution = restitution;
  77244. };
  77245. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77246. impostor.physicsBody.sleep();
  77247. };
  77248. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77249. impostor.physicsBody.awake();
  77250. };
  77251. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77252. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77253. if (minDistance !== void 0) {
  77254. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77255. }
  77256. };
  77257. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77258. //TODO separate rotational and transational motors.
  77259. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77260. if (motor) {
  77261. motor.setMotor(speed, maxForce);
  77262. }
  77263. };
  77264. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77265. //TODO separate rotational and transational motors.
  77266. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77267. if (motor) {
  77268. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77269. }
  77270. };
  77271. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77272. var body = impostor.physicsBody;
  77273. mesh.position.x = body.position.x;
  77274. mesh.position.y = body.position.y;
  77275. mesh.position.z = body.position.z;
  77276. if (mesh.rotationQuaternion) {
  77277. mesh.rotationQuaternion.x = body.orientation.x;
  77278. mesh.rotationQuaternion.y = body.orientation.y;
  77279. mesh.rotationQuaternion.z = body.orientation.z;
  77280. mesh.rotationQuaternion.w = body.orientation.s;
  77281. }
  77282. };
  77283. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77284. return impostor.physicsBody.shapes.radius;
  77285. };
  77286. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77287. var shape = impostor.physicsBody.shapes;
  77288. result.x = shape.halfWidth * 2;
  77289. result.y = shape.halfHeight * 2;
  77290. result.z = shape.halfDepth * 2;
  77291. };
  77292. OimoJSPlugin.prototype.dispose = function () {
  77293. this.world.clear();
  77294. };
  77295. return OimoJSPlugin;
  77296. }());
  77297. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77298. })(BABYLON || (BABYLON = {}));
  77299. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77300. var BABYLON;
  77301. (function (BABYLON) {
  77302. /*
  77303. * Based on jsTGALoader - Javascript loader for TGA file
  77304. * By Vincent Thibault
  77305. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77306. */
  77307. var TGATools = /** @class */ (function () {
  77308. function TGATools() {
  77309. }
  77310. TGATools.GetTGAHeader = function (data) {
  77311. var offset = 0;
  77312. var header = {
  77313. id_length: data[offset++],
  77314. colormap_type: data[offset++],
  77315. image_type: data[offset++],
  77316. colormap_index: data[offset++] | data[offset++] << 8,
  77317. colormap_length: data[offset++] | data[offset++] << 8,
  77318. colormap_size: data[offset++],
  77319. origin: [
  77320. data[offset++] | data[offset++] << 8,
  77321. data[offset++] | data[offset++] << 8
  77322. ],
  77323. width: data[offset++] | data[offset++] << 8,
  77324. height: data[offset++] | data[offset++] << 8,
  77325. pixel_size: data[offset++],
  77326. flags: data[offset++]
  77327. };
  77328. return header;
  77329. };
  77330. TGATools.UploadContent = function (gl, data) {
  77331. // Not enough data to contain header ?
  77332. if (data.length < 19) {
  77333. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77334. return;
  77335. }
  77336. // Read Header
  77337. var offset = 18;
  77338. var header = TGATools.GetTGAHeader(data);
  77339. // Assume it's a valid Targa file.
  77340. if (header.id_length + offset > data.length) {
  77341. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77342. return;
  77343. }
  77344. // Skip not needed data
  77345. offset += header.id_length;
  77346. var use_rle = false;
  77347. var use_pal = false;
  77348. var use_grey = false;
  77349. // Get some informations.
  77350. switch (header.image_type) {
  77351. case TGATools._TYPE_RLE_INDEXED:
  77352. use_rle = true;
  77353. case TGATools._TYPE_INDEXED:
  77354. use_pal = true;
  77355. break;
  77356. case TGATools._TYPE_RLE_RGB:
  77357. use_rle = true;
  77358. case TGATools._TYPE_RGB:
  77359. // use_rgb = true;
  77360. break;
  77361. case TGATools._TYPE_RLE_GREY:
  77362. use_rle = true;
  77363. case TGATools._TYPE_GREY:
  77364. use_grey = true;
  77365. break;
  77366. }
  77367. var pixel_data;
  77368. // var numAlphaBits = header.flags & 0xf;
  77369. var pixel_size = header.pixel_size >> 3;
  77370. var pixel_total = header.width * header.height * pixel_size;
  77371. // Read palettes
  77372. var palettes;
  77373. if (use_pal) {
  77374. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77375. }
  77376. // Read LRE
  77377. if (use_rle) {
  77378. pixel_data = new Uint8Array(pixel_total);
  77379. var c, count, i;
  77380. var localOffset = 0;
  77381. var pixels = new Uint8Array(pixel_size);
  77382. while (offset < pixel_total && localOffset < pixel_total) {
  77383. c = data[offset++];
  77384. count = (c & 0x7f) + 1;
  77385. // RLE pixels
  77386. if (c & 0x80) {
  77387. // Bind pixel tmp array
  77388. for (i = 0; i < pixel_size; ++i) {
  77389. pixels[i] = data[offset++];
  77390. }
  77391. // Copy pixel array
  77392. for (i = 0; i < count; ++i) {
  77393. pixel_data.set(pixels, localOffset + i * pixel_size);
  77394. }
  77395. localOffset += pixel_size * count;
  77396. }
  77397. else {
  77398. count *= pixel_size;
  77399. for (i = 0; i < count; ++i) {
  77400. pixel_data[localOffset + i] = data[offset++];
  77401. }
  77402. localOffset += count;
  77403. }
  77404. }
  77405. }
  77406. else {
  77407. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77408. }
  77409. // Load to texture
  77410. var x_start, y_start, x_step, y_step, y_end, x_end;
  77411. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77412. default:
  77413. case TGATools._ORIGIN_UL:
  77414. x_start = 0;
  77415. x_step = 1;
  77416. x_end = header.width;
  77417. y_start = 0;
  77418. y_step = 1;
  77419. y_end = header.height;
  77420. break;
  77421. case TGATools._ORIGIN_BL:
  77422. x_start = 0;
  77423. x_step = 1;
  77424. x_end = header.width;
  77425. y_start = header.height - 1;
  77426. y_step = -1;
  77427. y_end = -1;
  77428. break;
  77429. case TGATools._ORIGIN_UR:
  77430. x_start = header.width - 1;
  77431. x_step = -1;
  77432. x_end = -1;
  77433. y_start = 0;
  77434. y_step = 1;
  77435. y_end = header.height;
  77436. break;
  77437. case TGATools._ORIGIN_BR:
  77438. x_start = header.width - 1;
  77439. x_step = -1;
  77440. x_end = -1;
  77441. y_start = header.height - 1;
  77442. y_step = -1;
  77443. y_end = -1;
  77444. break;
  77445. }
  77446. // Load the specify method
  77447. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77448. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77449. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77450. };
  77451. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77452. var image = pixel_data, colormap = palettes;
  77453. var width = header.width, height = header.height;
  77454. var color, i = 0, x, y;
  77455. var imageData = new Uint8Array(width * height * 4);
  77456. for (y = y_start; y !== y_end; y += y_step) {
  77457. for (x = x_start; x !== x_end; x += x_step, i++) {
  77458. color = image[i];
  77459. imageData[(x + width * y) * 4 + 3] = 255;
  77460. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77461. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77462. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77463. }
  77464. }
  77465. return imageData;
  77466. };
  77467. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77468. var image = pixel_data;
  77469. var width = header.width, height = header.height;
  77470. var color, i = 0, x, y;
  77471. var imageData = new Uint8Array(width * height * 4);
  77472. for (y = y_start; y !== y_end; y += y_step) {
  77473. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77474. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77475. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77476. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77477. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77478. imageData[(x + width * y) * 4 + 0] = r;
  77479. imageData[(x + width * y) * 4 + 1] = g;
  77480. imageData[(x + width * y) * 4 + 2] = b;
  77481. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77482. }
  77483. }
  77484. return imageData;
  77485. };
  77486. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77487. var image = pixel_data;
  77488. var width = header.width, height = header.height;
  77489. var i = 0, x, y;
  77490. var imageData = new Uint8Array(width * height * 4);
  77491. for (y = y_start; y !== y_end; y += y_step) {
  77492. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77493. imageData[(x + width * y) * 4 + 3] = 255;
  77494. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77495. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77496. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77497. }
  77498. }
  77499. return imageData;
  77500. };
  77501. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77502. var image = pixel_data;
  77503. var width = header.width, height = header.height;
  77504. var i = 0, x, y;
  77505. var imageData = new Uint8Array(width * height * 4);
  77506. for (y = y_start; y !== y_end; y += y_step) {
  77507. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77508. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77509. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77510. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77511. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77512. }
  77513. }
  77514. return imageData;
  77515. };
  77516. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77517. var image = pixel_data;
  77518. var width = header.width, height = header.height;
  77519. var color, i = 0, x, y;
  77520. var imageData = new Uint8Array(width * height * 4);
  77521. for (y = y_start; y !== y_end; y += y_step) {
  77522. for (x = x_start; x !== x_end; x += x_step, i++) {
  77523. color = image[i];
  77524. imageData[(x + width * y) * 4 + 0] = color;
  77525. imageData[(x + width * y) * 4 + 1] = color;
  77526. imageData[(x + width * y) * 4 + 2] = color;
  77527. imageData[(x + width * y) * 4 + 3] = 255;
  77528. }
  77529. }
  77530. return imageData;
  77531. };
  77532. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77533. var image = pixel_data;
  77534. var width = header.width, height = header.height;
  77535. var i = 0, x, y;
  77536. var imageData = new Uint8Array(width * height * 4);
  77537. for (y = y_start; y !== y_end; y += y_step) {
  77538. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77539. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77540. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77541. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77542. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77543. }
  77544. }
  77545. return imageData;
  77546. };
  77547. //private static _TYPE_NO_DATA = 0;
  77548. TGATools._TYPE_INDEXED = 1;
  77549. TGATools._TYPE_RGB = 2;
  77550. TGATools._TYPE_GREY = 3;
  77551. TGATools._TYPE_RLE_INDEXED = 9;
  77552. TGATools._TYPE_RLE_RGB = 10;
  77553. TGATools._TYPE_RLE_GREY = 11;
  77554. TGATools._ORIGIN_MASK = 0x30;
  77555. TGATools._ORIGIN_SHIFT = 0x04;
  77556. TGATools._ORIGIN_BL = 0x00;
  77557. TGATools._ORIGIN_BR = 0x01;
  77558. TGATools._ORIGIN_UL = 0x02;
  77559. TGATools._ORIGIN_UR = 0x03;
  77560. return TGATools;
  77561. }());
  77562. BABYLON.TGATools = TGATools;
  77563. })(BABYLON || (BABYLON = {}));
  77564. //# sourceMappingURL=babylon.tga.js.map
  77565. var BABYLON;
  77566. (function (BABYLON) {
  77567. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77568. // All values and structures referenced from:
  77569. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77570. var DDS_MAGIC = 0x20534444;
  77571. var
  77572. //DDSD_CAPS = 0x1,
  77573. //DDSD_HEIGHT = 0x2,
  77574. //DDSD_WIDTH = 0x4,
  77575. //DDSD_PITCH = 0x8,
  77576. //DDSD_PIXELFORMAT = 0x1000,
  77577. DDSD_MIPMAPCOUNT = 0x20000;
  77578. //DDSD_LINEARSIZE = 0x80000,
  77579. //DDSD_DEPTH = 0x800000;
  77580. // var DDSCAPS_COMPLEX = 0x8,
  77581. // DDSCAPS_MIPMAP = 0x400000,
  77582. // DDSCAPS_TEXTURE = 0x1000;
  77583. var DDSCAPS2_CUBEMAP = 0x200;
  77584. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77585. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77586. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77587. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77588. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77589. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77590. // DDSCAPS2_VOLUME = 0x200000;
  77591. var
  77592. //DDPF_ALPHAPIXELS = 0x1,
  77593. //DDPF_ALPHA = 0x2,
  77594. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77595. //DDPF_YUV = 0x200,
  77596. DDPF_LUMINANCE = 0x20000;
  77597. function FourCCToInt32(value) {
  77598. return value.charCodeAt(0) +
  77599. (value.charCodeAt(1) << 8) +
  77600. (value.charCodeAt(2) << 16) +
  77601. (value.charCodeAt(3) << 24);
  77602. }
  77603. function Int32ToFourCC(value) {
  77604. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77605. }
  77606. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77607. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77608. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77609. var FOURCC_DX10 = FourCCToInt32("DX10");
  77610. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77611. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77612. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77613. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77614. var headerLengthInt = 31; // The header length in 32 bit ints
  77615. // Offsets into the header array
  77616. var off_magic = 0;
  77617. var off_size = 1;
  77618. var off_flags = 2;
  77619. var off_height = 3;
  77620. var off_width = 4;
  77621. var off_mipmapCount = 7;
  77622. var off_pfFlags = 20;
  77623. var off_pfFourCC = 21;
  77624. var off_RGBbpp = 22;
  77625. var off_RMask = 23;
  77626. var off_GMask = 24;
  77627. var off_BMask = 25;
  77628. var off_AMask = 26;
  77629. // var off_caps1 = 27;
  77630. var off_caps2 = 28;
  77631. // var off_caps3 = 29;
  77632. // var off_caps4 = 30;
  77633. var off_dxgiFormat = 32;
  77634. ;
  77635. var DDSTools = /** @class */ (function () {
  77636. function DDSTools() {
  77637. }
  77638. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77639. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77640. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77641. var mipmapCount = 1;
  77642. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77643. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77644. }
  77645. var fourCC = header[off_pfFourCC];
  77646. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77647. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77648. switch (fourCC) {
  77649. case FOURCC_D3DFMT_R16G16B16A16F:
  77650. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77651. break;
  77652. case FOURCC_D3DFMT_R32G32B32A32F:
  77653. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77654. break;
  77655. case FOURCC_DX10:
  77656. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77657. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77658. break;
  77659. }
  77660. }
  77661. return {
  77662. width: header[off_width],
  77663. height: header[off_height],
  77664. mipmapCount: mipmapCount,
  77665. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77666. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77667. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77668. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77669. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77670. dxgiFormat: dxgiFormat,
  77671. textureType: textureType
  77672. };
  77673. };
  77674. DDSTools._ToHalfFloat = function (value) {
  77675. if (!DDSTools._FloatView) {
  77676. DDSTools._FloatView = new Float32Array(1);
  77677. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77678. }
  77679. DDSTools._FloatView[0] = value;
  77680. var x = DDSTools._Int32View[0];
  77681. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77682. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77683. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77684. /* If zero, or denormal, or exponent underflows too much for a denormal
  77685. * half, return signed zero. */
  77686. if (e < 103) {
  77687. return bits;
  77688. }
  77689. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77690. if (e > 142) {
  77691. bits |= 0x7c00;
  77692. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77693. * not Inf, so make sure we set one mantissa bit too. */
  77694. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77695. return bits;
  77696. }
  77697. /* If exponent underflows but not too much, return a denormal */
  77698. if (e < 113) {
  77699. m |= 0x0800;
  77700. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77701. * to 1, which is OK. */
  77702. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77703. return bits;
  77704. }
  77705. bits |= ((e - 112) << 10) | (m >> 1);
  77706. bits += m & 1;
  77707. return bits;
  77708. };
  77709. DDSTools._FromHalfFloat = function (value) {
  77710. var s = (value & 0x8000) >> 15;
  77711. var e = (value & 0x7C00) >> 10;
  77712. var f = value & 0x03FF;
  77713. if (e === 0) {
  77714. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77715. }
  77716. else if (e == 0x1F) {
  77717. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77718. }
  77719. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77720. };
  77721. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77722. var destArray = new Float32Array(dataLength);
  77723. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77724. var index = 0;
  77725. for (var y = 0; y < height; y++) {
  77726. for (var x = 0; x < width; x++) {
  77727. var srcPos = (x + y * width) * 4;
  77728. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77729. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77730. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77731. if (DDSTools.StoreLODInAlphaChannel) {
  77732. destArray[index + 3] = lod;
  77733. }
  77734. else {
  77735. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77736. }
  77737. index += 4;
  77738. }
  77739. }
  77740. return destArray;
  77741. };
  77742. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77743. if (DDSTools.StoreLODInAlphaChannel) {
  77744. var destArray = new Uint16Array(dataLength);
  77745. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77746. var index = 0;
  77747. for (var y = 0; y < height; y++) {
  77748. for (var x = 0; x < width; x++) {
  77749. var srcPos = (x + y * width) * 4;
  77750. destArray[index] = srcData[srcPos];
  77751. destArray[index + 1] = srcData[srcPos + 1];
  77752. destArray[index + 2] = srcData[srcPos + 2];
  77753. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77754. index += 4;
  77755. }
  77756. }
  77757. return destArray;
  77758. }
  77759. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77760. };
  77761. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77762. if (DDSTools.StoreLODInAlphaChannel) {
  77763. var destArray = new Float32Array(dataLength);
  77764. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77765. var index = 0;
  77766. for (var y = 0; y < height; y++) {
  77767. for (var x = 0; x < width; x++) {
  77768. var srcPos = (x + y * width) * 4;
  77769. destArray[index] = srcData[srcPos];
  77770. destArray[index + 1] = srcData[srcPos + 1];
  77771. destArray[index + 2] = srcData[srcPos + 2];
  77772. destArray[index + 3] = lod;
  77773. index += 4;
  77774. }
  77775. }
  77776. return destArray;
  77777. }
  77778. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77779. };
  77780. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77781. var destArray = new Uint8Array(dataLength);
  77782. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77783. var index = 0;
  77784. for (var y = 0; y < height; y++) {
  77785. for (var x = 0; x < width; x++) {
  77786. var srcPos = (x + y * width) * 4;
  77787. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77788. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77789. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77790. if (DDSTools.StoreLODInAlphaChannel) {
  77791. destArray[index + 3] = lod;
  77792. }
  77793. else {
  77794. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77795. }
  77796. index += 4;
  77797. }
  77798. }
  77799. return destArray;
  77800. };
  77801. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77802. var destArray = new Uint8Array(dataLength);
  77803. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77804. var index = 0;
  77805. for (var y = 0; y < height; y++) {
  77806. for (var x = 0; x < width; x++) {
  77807. var srcPos = (x + y * width) * 4;
  77808. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77809. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77810. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77811. if (DDSTools.StoreLODInAlphaChannel) {
  77812. destArray[index + 3] = lod;
  77813. }
  77814. else {
  77815. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77816. }
  77817. index += 4;
  77818. }
  77819. }
  77820. return destArray;
  77821. };
  77822. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77823. var byteArray = new Uint8Array(dataLength);
  77824. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77825. var index = 0;
  77826. for (var y = 0; y < height; y++) {
  77827. for (var x = 0; x < width; x++) {
  77828. var srcPos = (x + y * width) * 4;
  77829. byteArray[index] = srcData[srcPos + rOffset];
  77830. byteArray[index + 1] = srcData[srcPos + gOffset];
  77831. byteArray[index + 2] = srcData[srcPos + bOffset];
  77832. byteArray[index + 3] = srcData[srcPos + aOffset];
  77833. index += 4;
  77834. }
  77835. }
  77836. return byteArray;
  77837. };
  77838. DDSTools._ExtractLongWordOrder = function (value) {
  77839. if (value === 0 || value === 255 || value === -16777216) {
  77840. return 0;
  77841. }
  77842. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77843. };
  77844. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77845. var byteArray = new Uint8Array(dataLength);
  77846. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77847. var index = 0;
  77848. for (var y = 0; y < height; y++) {
  77849. for (var x = 0; x < width; x++) {
  77850. var srcPos = (x + y * width) * 3;
  77851. byteArray[index] = srcData[srcPos + rOffset];
  77852. byteArray[index + 1] = srcData[srcPos + gOffset];
  77853. byteArray[index + 2] = srcData[srcPos + bOffset];
  77854. index += 3;
  77855. }
  77856. }
  77857. return byteArray;
  77858. };
  77859. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77860. var byteArray = new Uint8Array(dataLength);
  77861. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77862. var index = 0;
  77863. for (var y = 0; y < height; y++) {
  77864. for (var x = 0; x < width; x++) {
  77865. var srcPos = (x + y * width);
  77866. byteArray[index] = srcData[srcPos];
  77867. index++;
  77868. }
  77869. }
  77870. return byteArray;
  77871. };
  77872. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77873. if (lodIndex === void 0) { lodIndex = -1; }
  77874. var ext = engine.getCaps().s3tc;
  77875. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77876. var fourCC, width, height, dataLength = 0, dataOffset;
  77877. var byteArray, mipmapCount, mip;
  77878. var internalFormat = 0;
  77879. var format = 0;
  77880. var blockBytes = 1;
  77881. if (header[off_magic] !== DDS_MAGIC) {
  77882. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77883. return;
  77884. }
  77885. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77886. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77887. return;
  77888. }
  77889. if (info.isCompressed && !ext) {
  77890. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77891. return;
  77892. }
  77893. var bpp = header[off_RGBbpp];
  77894. dataOffset = header[off_size] + 4;
  77895. var computeFormats = false;
  77896. if (info.isFourCC) {
  77897. fourCC = header[off_pfFourCC];
  77898. switch (fourCC) {
  77899. case FOURCC_DXT1:
  77900. blockBytes = 8;
  77901. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77902. break;
  77903. case FOURCC_DXT3:
  77904. blockBytes = 16;
  77905. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77906. break;
  77907. case FOURCC_DXT5:
  77908. blockBytes = 16;
  77909. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77910. break;
  77911. case FOURCC_D3DFMT_R16G16B16A16F:
  77912. computeFormats = true;
  77913. break;
  77914. case FOURCC_D3DFMT_R32G32B32A32F:
  77915. computeFormats = true;
  77916. break;
  77917. case FOURCC_DX10:
  77918. // There is an additionnal header so dataOffset need to be changed
  77919. dataOffset += 5 * 4; // 5 uints
  77920. var supported = false;
  77921. switch (info.dxgiFormat) {
  77922. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77923. computeFormats = true;
  77924. supported = true;
  77925. break;
  77926. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77927. info.isRGB = true;
  77928. info.isFourCC = false;
  77929. bpp = 32;
  77930. supported = true;
  77931. break;
  77932. }
  77933. if (supported) {
  77934. break;
  77935. }
  77936. default:
  77937. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77938. return;
  77939. }
  77940. }
  77941. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77942. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77943. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77944. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77945. if (computeFormats) {
  77946. format = engine._getWebGLTextureType(info.textureType);
  77947. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77948. }
  77949. mipmapCount = 1;
  77950. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77951. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77952. }
  77953. for (var face = 0; face < faces; face++) {
  77954. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77955. width = header[off_width];
  77956. height = header[off_height];
  77957. for (mip = 0; mip < mipmapCount; ++mip) {
  77958. if (lodIndex === -1 || lodIndex === mip) {
  77959. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77960. var i = (lodIndex === -1) ? mip : 0;
  77961. if (!info.isCompressed && info.isFourCC) {
  77962. dataLength = width * height * 4;
  77963. var floatArray = null;
  77964. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77965. if (bpp === 128) {
  77966. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77967. }
  77968. else if (bpp === 64) {
  77969. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77970. }
  77971. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77972. format = engine._getWebGLTextureType(info.textureType);
  77973. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77974. }
  77975. else {
  77976. if (bpp === 128) {
  77977. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77978. }
  77979. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77980. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77981. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77982. format = engine._getWebGLTextureType(info.textureType);
  77983. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77984. }
  77985. else {
  77986. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77987. }
  77988. }
  77989. if (floatArray) {
  77990. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77991. }
  77992. }
  77993. else if (info.isRGB) {
  77994. if (bpp === 24) {
  77995. dataLength = width * height * 3;
  77996. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77997. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77998. }
  77999. else {
  78000. dataLength = width * height * 4;
  78001. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78002. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78003. }
  78004. }
  78005. else if (info.isLuminance) {
  78006. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78007. var unpaddedRowSize = width;
  78008. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78009. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78010. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78011. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78012. }
  78013. else {
  78014. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78015. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78016. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78017. }
  78018. }
  78019. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78020. width *= 0.5;
  78021. height *= 0.5;
  78022. width = Math.max(1.0, width);
  78023. height = Math.max(1.0, height);
  78024. }
  78025. if (currentFace !== undefined) {
  78026. // Loading a single face
  78027. break;
  78028. }
  78029. }
  78030. };
  78031. DDSTools.StoreLODInAlphaChannel = false;
  78032. return DDSTools;
  78033. }());
  78034. BABYLON.DDSTools = DDSTools;
  78035. })(BABYLON || (BABYLON = {}));
  78036. //# sourceMappingURL=babylon.dds.js.map
  78037. var BABYLON;
  78038. (function (BABYLON) {
  78039. /**
  78040. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78041. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78042. */
  78043. var KhronosTextureContainer = /** @class */ (function () {
  78044. /**
  78045. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78046. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78047. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78048. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78049. */
  78050. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78051. this.arrayBuffer = arrayBuffer;
  78052. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78053. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78054. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78055. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78056. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78057. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78058. BABYLON.Tools.Error("texture missing KTX identifier");
  78059. return;
  78060. }
  78061. // load the reset of the header in native 32 bit int
  78062. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78063. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78064. var oppositeEndianess = header[0] === 0x01020304;
  78065. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78066. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78067. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78068. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78069. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78070. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78071. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78072. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78073. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78074. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78075. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78076. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78077. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78078. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78079. if (this.glType !== 0) {
  78080. BABYLON.Tools.Error("only compressed formats currently supported");
  78081. return;
  78082. }
  78083. else {
  78084. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78085. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78086. }
  78087. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78088. BABYLON.Tools.Error("only 2D textures currently supported");
  78089. return;
  78090. }
  78091. if (this.numberOfArrayElements !== 0) {
  78092. BABYLON.Tools.Error("texture arrays not currently supported");
  78093. return;
  78094. }
  78095. if (this.numberOfFaces !== facesExpected) {
  78096. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78097. return;
  78098. }
  78099. // we now have a completely validated file, so could use existence of loadType as success
  78100. // would need to make this more elaborate & adjust checks above to support more than one load type
  78101. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78102. }
  78103. // not as fast hardware based, but will probably never need to use
  78104. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78105. return ((val & 0xFF) << 24)
  78106. | ((val & 0xFF00) << 8)
  78107. | ((val >> 8) & 0xFF00)
  78108. | ((val >> 24) & 0xFF);
  78109. };
  78110. /**
  78111. * It is assumed that the texture has already been created & is currently bound
  78112. */
  78113. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78114. switch (this.loadType) {
  78115. case KhronosTextureContainer.COMPRESSED_2D:
  78116. this._upload2DCompressedLevels(gl, loadMipmaps);
  78117. break;
  78118. case KhronosTextureContainer.TEX_2D:
  78119. case KhronosTextureContainer.COMPRESSED_3D:
  78120. case KhronosTextureContainer.TEX_3D:
  78121. }
  78122. };
  78123. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78124. // initialize width & height for level 1
  78125. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78126. var width = this.pixelWidth;
  78127. var height = this.pixelHeight;
  78128. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78129. for (var level = 0; level < mipmapCount; level++) {
  78130. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78131. for (var face = 0; face < this.numberOfFaces; face++) {
  78132. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78133. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78134. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78135. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78136. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78137. }
  78138. width = Math.max(1.0, width * 0.5);
  78139. height = Math.max(1.0, height * 0.5);
  78140. }
  78141. };
  78142. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78143. // load types
  78144. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78145. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78146. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78147. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78148. return KhronosTextureContainer;
  78149. }());
  78150. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78151. })(BABYLON || (BABYLON = {}));
  78152. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78153. var BABYLON;
  78154. (function (BABYLON) {
  78155. var Debug = /** @class */ (function () {
  78156. function Debug() {
  78157. }
  78158. Debug.AxesViewer = /** @class */ (function () {
  78159. function AxesViewer(scene, scaleLines) {
  78160. if (scaleLines === void 0) { scaleLines = 1; }
  78161. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78162. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78163. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78164. this.scaleLines = 1;
  78165. this.scaleLines = scaleLines;
  78166. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78167. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78168. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78169. this._xmesh.renderingGroupId = 2;
  78170. this._ymesh.renderingGroupId = 2;
  78171. this._zmesh.renderingGroupId = 2;
  78172. this._xmesh.material.checkReadyOnlyOnce = true;
  78173. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78174. this._ymesh.material.checkReadyOnlyOnce = true;
  78175. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78176. this._zmesh.material.checkReadyOnlyOnce = true;
  78177. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78178. this.scene = scene;
  78179. }
  78180. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78181. var scaleLines = this.scaleLines;
  78182. if (this._xmesh) {
  78183. this._xmesh.position.copyFrom(position);
  78184. }
  78185. if (this._ymesh) {
  78186. this._ymesh.position.copyFrom(position);
  78187. }
  78188. if (this._zmesh) {
  78189. this._zmesh.position.copyFrom(position);
  78190. }
  78191. var point2 = this._xline[1];
  78192. point2.x = xaxis.x * scaleLines;
  78193. point2.y = xaxis.y * scaleLines;
  78194. point2.z = xaxis.z * scaleLines;
  78195. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78196. point2 = this._yline[1];
  78197. point2.x = yaxis.x * scaleLines;
  78198. point2.y = yaxis.y * scaleLines;
  78199. point2.z = yaxis.z * scaleLines;
  78200. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78201. point2 = this._zline[1];
  78202. point2.x = zaxis.x * scaleLines;
  78203. point2.y = zaxis.y * scaleLines;
  78204. point2.z = zaxis.z * scaleLines;
  78205. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78206. };
  78207. AxesViewer.prototype.dispose = function () {
  78208. if (this._xmesh) {
  78209. this._xmesh.dispose();
  78210. }
  78211. if (this._ymesh) {
  78212. this._ymesh.dispose();
  78213. }
  78214. if (this._zmesh) {
  78215. this._zmesh.dispose();
  78216. }
  78217. this._xmesh = null;
  78218. this._ymesh = null;
  78219. this._zmesh = null;
  78220. this.scene = null;
  78221. };
  78222. return AxesViewer;
  78223. }());
  78224. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78225. __extends(BoneAxesViewer, _super);
  78226. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78227. if (scaleLines === void 0) { scaleLines = 1; }
  78228. var _this = _super.call(this, scene, scaleLines) || this;
  78229. _this.pos = BABYLON.Vector3.Zero();
  78230. _this.xaxis = BABYLON.Vector3.Zero();
  78231. _this.yaxis = BABYLON.Vector3.Zero();
  78232. _this.zaxis = BABYLON.Vector3.Zero();
  78233. _this.mesh = mesh;
  78234. _this.bone = bone;
  78235. return _this;
  78236. }
  78237. BoneAxesViewer.prototype.update = function () {
  78238. if (!this.mesh || !this.bone) {
  78239. return;
  78240. }
  78241. var bone = this.bone;
  78242. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78243. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78244. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78245. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78246. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78247. };
  78248. BoneAxesViewer.prototype.dispose = function () {
  78249. if (this.mesh) {
  78250. this.mesh = null;
  78251. this.bone = null;
  78252. _super.prototype.dispose.call(this);
  78253. }
  78254. };
  78255. return BoneAxesViewer;
  78256. }(Debug.AxesViewer));
  78257. Debug.PhysicsViewer = /** @class */ (function () {
  78258. function PhysicsViewer(scene) {
  78259. this._impostors = [];
  78260. this._meshes = [];
  78261. this._numMeshes = 0;
  78262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78263. var physicEngine = this._scene.getPhysicsEngine();
  78264. if (physicEngine) {
  78265. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78266. }
  78267. }
  78268. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78269. var plugin = this._physicsEnginePlugin;
  78270. for (var i = 0; i < this._numMeshes; i++) {
  78271. var impostor = this._impostors[i];
  78272. if (!impostor) {
  78273. continue;
  78274. }
  78275. if (impostor.isDisposed) {
  78276. this.hideImpostor(this._impostors[i--]);
  78277. }
  78278. else {
  78279. var mesh = this._meshes[i];
  78280. if (mesh && plugin) {
  78281. plugin.syncMeshWithImpostor(mesh, impostor);
  78282. }
  78283. }
  78284. }
  78285. };
  78286. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78287. if (!this._scene) {
  78288. return;
  78289. }
  78290. for (var i = 0; i < this._numMeshes; i++) {
  78291. if (this._impostors[i] == impostor) {
  78292. return;
  78293. }
  78294. }
  78295. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78296. if (debugMesh) {
  78297. this._impostors[this._numMeshes] = impostor;
  78298. this._meshes[this._numMeshes] = debugMesh;
  78299. if (this._numMeshes === 0) {
  78300. this._renderFunction = this._updateDebugMeshes.bind(this);
  78301. this._scene.registerBeforeRender(this._renderFunction);
  78302. }
  78303. this._numMeshes++;
  78304. }
  78305. };
  78306. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78307. if (!impostor || !this._scene) {
  78308. return;
  78309. }
  78310. var removed = false;
  78311. for (var i = 0; i < this._numMeshes; i++) {
  78312. if (this._impostors[i] == impostor) {
  78313. var mesh = this._meshes[i];
  78314. if (!mesh) {
  78315. continue;
  78316. }
  78317. this._scene.removeMesh(mesh);
  78318. mesh.dispose();
  78319. this._numMeshes--;
  78320. if (this._numMeshes > 0) {
  78321. this._meshes[i] = this._meshes[this._numMeshes];
  78322. this._impostors[i] = this._impostors[this._numMeshes];
  78323. this._meshes[this._numMeshes] = null;
  78324. this._impostors[this._numMeshes] = null;
  78325. }
  78326. else {
  78327. this._meshes[0] = null;
  78328. this._impostors[0] = null;
  78329. }
  78330. removed = true;
  78331. break;
  78332. }
  78333. }
  78334. if (removed && this._numMeshes === 0) {
  78335. this._scene.unregisterBeforeRender(this._renderFunction);
  78336. }
  78337. };
  78338. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78339. if (!this._debugMaterial) {
  78340. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78341. this._debugMaterial.wireframe = true;
  78342. }
  78343. return this._debugMaterial;
  78344. };
  78345. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78346. if (!this._debugBoxMesh) {
  78347. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78348. this._debugBoxMesh.renderingGroupId = 1;
  78349. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78350. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78351. scene.removeMesh(this._debugBoxMesh);
  78352. }
  78353. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78354. };
  78355. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78356. if (!this._debugSphereMesh) {
  78357. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78358. this._debugSphereMesh.renderingGroupId = 1;
  78359. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78360. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78361. scene.removeMesh(this._debugSphereMesh);
  78362. }
  78363. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78364. };
  78365. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78366. var mesh = null;
  78367. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78368. mesh = this._getDebugBoxMesh(scene);
  78369. impostor.getBoxSizeToRef(mesh.scaling);
  78370. }
  78371. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78372. mesh = this._getDebugSphereMesh(scene);
  78373. var radius = impostor.getRadius();
  78374. mesh.scaling.x = radius * 2;
  78375. mesh.scaling.y = radius * 2;
  78376. mesh.scaling.z = radius * 2;
  78377. }
  78378. return mesh;
  78379. };
  78380. PhysicsViewer.prototype.dispose = function () {
  78381. for (var i = 0; i < this._numMeshes; i++) {
  78382. this.hideImpostor(this._impostors[i]);
  78383. }
  78384. if (this._debugBoxMesh) {
  78385. this._debugBoxMesh.dispose();
  78386. }
  78387. if (this._debugSphereMesh) {
  78388. this._debugSphereMesh.dispose();
  78389. }
  78390. if (this._debugMaterial) {
  78391. this._debugMaterial.dispose();
  78392. }
  78393. this._impostors.length = 0;
  78394. this._scene = null;
  78395. this._physicsEnginePlugin = null;
  78396. };
  78397. return PhysicsViewer;
  78398. }());
  78399. Debug.SkeletonViewer = /** @class */ (function () {
  78400. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78401. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78402. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78403. this.skeleton = skeleton;
  78404. this.mesh = mesh;
  78405. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78406. this.renderingGroupId = renderingGroupId;
  78407. this.color = BABYLON.Color3.White();
  78408. this._debugLines = new Array();
  78409. this._isEnabled = false;
  78410. this._scene = scene;
  78411. this.update();
  78412. this._renderFunction = this.update.bind(this);
  78413. }
  78414. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78415. get: function () {
  78416. return this._isEnabled;
  78417. },
  78418. set: function (value) {
  78419. if (this._isEnabled === value) {
  78420. return;
  78421. }
  78422. this._isEnabled = value;
  78423. if (value) {
  78424. this._scene.registerBeforeRender(this._renderFunction);
  78425. }
  78426. else {
  78427. this._scene.unregisterBeforeRender(this._renderFunction);
  78428. }
  78429. },
  78430. enumerable: true,
  78431. configurable: true
  78432. });
  78433. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78434. if (x === void 0) { x = 0; }
  78435. if (y === void 0) { y = 0; }
  78436. if (z === void 0) { z = 0; }
  78437. var tmat = BABYLON.Tmp.Matrix[0];
  78438. var parentBone = bone.getParent();
  78439. tmat.copyFrom(bone.getLocalMatrix());
  78440. if (x !== 0 || y !== 0 || z !== 0) {
  78441. var tmat2 = BABYLON.Tmp.Matrix[1];
  78442. BABYLON.Matrix.IdentityToRef(tmat2);
  78443. tmat2.m[12] = x;
  78444. tmat2.m[13] = y;
  78445. tmat2.m[14] = z;
  78446. tmat2.multiplyToRef(tmat, tmat);
  78447. }
  78448. if (parentBone) {
  78449. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78450. }
  78451. tmat.multiplyToRef(meshMat, tmat);
  78452. position.x = tmat.m[12];
  78453. position.y = tmat.m[13];
  78454. position.z = tmat.m[14];
  78455. };
  78456. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78457. var len = bones.length;
  78458. var meshPos = this.mesh.position;
  78459. for (var i = 0; i < len; i++) {
  78460. var bone = bones[i];
  78461. var points = this._debugLines[i];
  78462. if (!points) {
  78463. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78464. this._debugLines[i] = points;
  78465. }
  78466. this._getBonePosition(points[0], bone, meshMat);
  78467. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78468. points[0].subtractInPlace(meshPos);
  78469. points[1].subtractInPlace(meshPos);
  78470. }
  78471. };
  78472. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78473. var len = bones.length;
  78474. var boneNum = 0;
  78475. var meshPos = this.mesh.position;
  78476. for (var i = len - 1; i >= 0; i--) {
  78477. var childBone = bones[i];
  78478. var parentBone = childBone.getParent();
  78479. if (!parentBone) {
  78480. continue;
  78481. }
  78482. var points = this._debugLines[boneNum];
  78483. if (!points) {
  78484. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78485. this._debugLines[boneNum] = points;
  78486. }
  78487. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78488. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78489. points[0].subtractInPlace(meshPos);
  78490. points[1].subtractInPlace(meshPos);
  78491. boneNum++;
  78492. }
  78493. };
  78494. SkeletonViewer.prototype.update = function () {
  78495. if (this.autoUpdateBonesMatrices) {
  78496. this.skeleton.computeAbsoluteTransforms();
  78497. }
  78498. if (this.skeleton.bones[0].length === undefined) {
  78499. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78500. }
  78501. else {
  78502. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78503. }
  78504. if (!this._debugMesh) {
  78505. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78506. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78507. }
  78508. else {
  78509. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78510. }
  78511. this._debugMesh.position.copyFrom(this.mesh.position);
  78512. this._debugMesh.color = this.color;
  78513. };
  78514. SkeletonViewer.prototype.dispose = function () {
  78515. if (this._debugMesh) {
  78516. this.isEnabled = false;
  78517. this._debugMesh.dispose();
  78518. this._debugMesh = null;
  78519. }
  78520. };
  78521. return SkeletonViewer;
  78522. }());
  78523. return Debug;
  78524. }());
  78525. BABYLON.Debug = Debug;
  78526. })(BABYLON || (BABYLON = {}));
  78527. //# sourceMappingURL=babylon.debugModules.js.map
  78528. var BABYLON;
  78529. (function (BABYLON) {
  78530. var RayHelper = /** @class */ (function () {
  78531. function RayHelper(ray) {
  78532. this.ray = ray;
  78533. }
  78534. RayHelper.CreateAndShow = function (ray, scene, color) {
  78535. var helper = new RayHelper(ray);
  78536. helper.show(scene, color);
  78537. return helper;
  78538. };
  78539. RayHelper.prototype.show = function (scene, color) {
  78540. if (!this._renderFunction && this.ray) {
  78541. var ray = this.ray;
  78542. this._renderFunction = this._render.bind(this);
  78543. this._scene = scene;
  78544. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78545. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78546. if (this._renderFunction) {
  78547. this._scene.registerBeforeRender(this._renderFunction);
  78548. }
  78549. }
  78550. if (color && this._renderLine) {
  78551. this._renderLine.color.copyFrom(color);
  78552. }
  78553. };
  78554. RayHelper.prototype.hide = function () {
  78555. if (this._renderFunction && this._scene) {
  78556. this._scene.unregisterBeforeRender(this._renderFunction);
  78557. this._scene = null;
  78558. this._renderFunction = null;
  78559. if (this._renderLine) {
  78560. this._renderLine.dispose();
  78561. this._renderLine = null;
  78562. }
  78563. this._renderPoints = [];
  78564. }
  78565. };
  78566. RayHelper.prototype._render = function () {
  78567. var ray = this.ray;
  78568. if (!ray) {
  78569. return;
  78570. }
  78571. var point = this._renderPoints[1];
  78572. var len = Math.min(ray.length, 1000000);
  78573. point.copyFrom(ray.direction);
  78574. point.scaleInPlace(len);
  78575. point.addInPlace(ray.origin);
  78576. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78577. };
  78578. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78579. this._attachedToMesh = mesh;
  78580. var ray = this.ray;
  78581. if (!ray) {
  78582. return;
  78583. }
  78584. if (!ray.direction) {
  78585. ray.direction = BABYLON.Vector3.Zero();
  78586. }
  78587. if (!ray.origin) {
  78588. ray.origin = BABYLON.Vector3.Zero();
  78589. }
  78590. if (length) {
  78591. ray.length = length;
  78592. }
  78593. if (!meshSpaceOrigin) {
  78594. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78595. }
  78596. if (!meshSpaceDirection) {
  78597. // -1 so that this will work with Mesh.lookAt
  78598. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78599. }
  78600. if (!this._meshSpaceDirection) {
  78601. this._meshSpaceDirection = meshSpaceDirection.clone();
  78602. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78603. }
  78604. else {
  78605. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78606. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78607. }
  78608. if (!this._updateToMeshFunction) {
  78609. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78610. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78611. }
  78612. this._updateToMesh();
  78613. };
  78614. RayHelper.prototype.detachFromMesh = function () {
  78615. if (this._attachedToMesh) {
  78616. if (this._updateToMeshFunction) {
  78617. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78618. }
  78619. this._attachedToMesh = null;
  78620. this._updateToMeshFunction = null;
  78621. }
  78622. };
  78623. RayHelper.prototype._updateToMesh = function () {
  78624. var ray = this.ray;
  78625. if (!this._attachedToMesh || !ray) {
  78626. return;
  78627. }
  78628. if (this._attachedToMesh._isDisposed) {
  78629. this.detachFromMesh();
  78630. return;
  78631. }
  78632. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78633. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78634. };
  78635. RayHelper.prototype.dispose = function () {
  78636. this.hide();
  78637. this.detachFromMesh();
  78638. this.ray = null;
  78639. };
  78640. return RayHelper;
  78641. }());
  78642. BABYLON.RayHelper = RayHelper;
  78643. })(BABYLON || (BABYLON = {}));
  78644. //# sourceMappingURL=babylon.rayHelper.js.map
  78645. var BABYLON;
  78646. (function (BABYLON) {
  78647. // load the inspector using require, if not present in the global namespace.
  78648. var DebugLayer = /** @class */ (function () {
  78649. function DebugLayer(scene) {
  78650. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78651. this._scene = scene;
  78652. // load inspector using require, if it doesn't exist on the global namespace.
  78653. }
  78654. /** Creates the inspector window. */
  78655. DebugLayer.prototype._createInspector = function (config) {
  78656. if (config === void 0) { config = {}; }
  78657. var popup = config.popup || false;
  78658. var initialTab = config.initialTab || 0;
  78659. var parentElement = config.parentElement || null;
  78660. if (!this._inspector) {
  78661. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78662. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78663. } // else nothing to do,; instance is already existing
  78664. };
  78665. DebugLayer.prototype.isVisible = function () {
  78666. if (!this._inspector) {
  78667. return false;
  78668. }
  78669. return true;
  78670. };
  78671. DebugLayer.prototype.hide = function () {
  78672. if (this._inspector) {
  78673. try {
  78674. this._inspector.dispose();
  78675. }
  78676. catch (e) {
  78677. // If the inspector has been removed directly from the inspector tool
  78678. }
  78679. this._inspector = null;
  78680. }
  78681. };
  78682. DebugLayer.prototype.show = function (config) {
  78683. if (config === void 0) { config = {}; }
  78684. if (typeof this.BJSINSPECTOR == 'undefined') {
  78685. // Load inspector and add it to the DOM
  78686. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78687. }
  78688. else {
  78689. // Otherwise creates the inspector
  78690. this._createInspector(config);
  78691. }
  78692. };
  78693. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78694. return DebugLayer;
  78695. }());
  78696. BABYLON.DebugLayer = DebugLayer;
  78697. })(BABYLON || (BABYLON = {}));
  78698. //# sourceMappingURL=babylon.debugLayer.js.map
  78699. var BABYLON;
  78700. (function (BABYLON) {
  78701. var BoundingBoxRenderer = /** @class */ (function () {
  78702. function BoundingBoxRenderer(scene) {
  78703. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78704. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78705. this.showBackLines = true;
  78706. this.renderList = new BABYLON.SmartArray(32);
  78707. this._vertexBuffers = {};
  78708. this._scene = scene;
  78709. }
  78710. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78711. if (this._colorShader) {
  78712. return;
  78713. }
  78714. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78715. attributes: [BABYLON.VertexBuffer.PositionKind],
  78716. uniforms: ["world", "viewProjection", "color"]
  78717. });
  78718. var engine = this._scene.getEngine();
  78719. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78721. this._createIndexBuffer();
  78722. };
  78723. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78724. var engine = this._scene.getEngine();
  78725. 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]);
  78726. };
  78727. BoundingBoxRenderer.prototype._rebuild = function () {
  78728. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78729. if (vb) {
  78730. vb._rebuild();
  78731. }
  78732. this._createIndexBuffer();
  78733. };
  78734. BoundingBoxRenderer.prototype.reset = function () {
  78735. this.renderList.reset();
  78736. };
  78737. BoundingBoxRenderer.prototype.render = function () {
  78738. if (this.renderList.length === 0) {
  78739. return;
  78740. }
  78741. this._prepareRessources();
  78742. if (!this._colorShader.isReady()) {
  78743. return;
  78744. }
  78745. var engine = this._scene.getEngine();
  78746. engine.setDepthWrite(false);
  78747. this._colorShader._preBind();
  78748. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78749. var boundingBox = this.renderList.data[boundingBoxIndex];
  78750. var min = boundingBox.minimum;
  78751. var max = boundingBox.maximum;
  78752. var diff = max.subtract(min);
  78753. var median = min.add(diff.scale(0.5));
  78754. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78755. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78756. .multiply(boundingBox.getWorldMatrix());
  78757. // VBOs
  78758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78759. if (this.showBackLines) {
  78760. // Back
  78761. engine.setDepthFunctionToGreaterOrEqual();
  78762. this._scene.resetCachedMaterial();
  78763. this._colorShader.setColor4("color", this.backColor.toColor4());
  78764. this._colorShader.bind(worldMatrix);
  78765. // Draw order
  78766. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78767. }
  78768. // Front
  78769. engine.setDepthFunctionToLess();
  78770. this._scene.resetCachedMaterial();
  78771. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78772. this._colorShader.bind(worldMatrix);
  78773. // Draw order
  78774. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78775. }
  78776. this._colorShader.unbind();
  78777. engine.setDepthFunctionToLessOrEqual();
  78778. engine.setDepthWrite(true);
  78779. };
  78780. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78781. this._prepareRessources();
  78782. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78783. return;
  78784. }
  78785. var engine = this._scene.getEngine();
  78786. engine.setDepthWrite(false);
  78787. engine.setColorWrite(false);
  78788. this._colorShader._preBind();
  78789. var boundingBox = mesh._boundingInfo.boundingBox;
  78790. var min = boundingBox.minimum;
  78791. var max = boundingBox.maximum;
  78792. var diff = max.subtract(min);
  78793. var median = min.add(diff.scale(0.5));
  78794. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78795. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78796. .multiply(boundingBox.getWorldMatrix());
  78797. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78798. engine.setDepthFunctionToLess();
  78799. this._scene.resetCachedMaterial();
  78800. this._colorShader.bind(worldMatrix);
  78801. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78802. this._colorShader.unbind();
  78803. engine.setDepthFunctionToLessOrEqual();
  78804. engine.setDepthWrite(true);
  78805. engine.setColorWrite(true);
  78806. };
  78807. BoundingBoxRenderer.prototype.dispose = function () {
  78808. if (!this._colorShader) {
  78809. return;
  78810. }
  78811. this.renderList.dispose();
  78812. this._colorShader.dispose();
  78813. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78814. if (buffer) {
  78815. buffer.dispose();
  78816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78817. }
  78818. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78819. };
  78820. return BoundingBoxRenderer;
  78821. }());
  78822. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78823. })(BABYLON || (BABYLON = {}));
  78824. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78825. var BABYLON;
  78826. (function (BABYLON) {
  78827. var MorphTarget = /** @class */ (function () {
  78828. function MorphTarget(name, influence) {
  78829. if (influence === void 0) { influence = 0; }
  78830. this.name = name;
  78831. this.animations = new Array();
  78832. this._positions = null;
  78833. this._normals = null;
  78834. this._tangents = null;
  78835. this.onInfluenceChanged = new BABYLON.Observable();
  78836. this.influence = influence;
  78837. }
  78838. Object.defineProperty(MorphTarget.prototype, "influence", {
  78839. get: function () {
  78840. return this._influence;
  78841. },
  78842. set: function (influence) {
  78843. if (this._influence === influence) {
  78844. return;
  78845. }
  78846. var previous = this._influence;
  78847. this._influence = influence;
  78848. if (this.onInfluenceChanged.hasObservers) {
  78849. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78850. }
  78851. },
  78852. enumerable: true,
  78853. configurable: true
  78854. });
  78855. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78856. get: function () {
  78857. return !!this._positions;
  78858. },
  78859. enumerable: true,
  78860. configurable: true
  78861. });
  78862. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78863. get: function () {
  78864. return !!this._normals;
  78865. },
  78866. enumerable: true,
  78867. configurable: true
  78868. });
  78869. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78870. get: function () {
  78871. return !!this._tangents;
  78872. },
  78873. enumerable: true,
  78874. configurable: true
  78875. });
  78876. MorphTarget.prototype.setPositions = function (data) {
  78877. this._positions = data;
  78878. };
  78879. MorphTarget.prototype.getPositions = function () {
  78880. return this._positions;
  78881. };
  78882. MorphTarget.prototype.setNormals = function (data) {
  78883. this._normals = data;
  78884. };
  78885. MorphTarget.prototype.getNormals = function () {
  78886. return this._normals;
  78887. };
  78888. MorphTarget.prototype.setTangents = function (data) {
  78889. this._tangents = data;
  78890. };
  78891. MorphTarget.prototype.getTangents = function () {
  78892. return this._tangents;
  78893. };
  78894. /**
  78895. * Serializes the current target into a Serialization object.
  78896. * Returns the serialized object.
  78897. */
  78898. MorphTarget.prototype.serialize = function () {
  78899. var serializationObject = {};
  78900. serializationObject.name = this.name;
  78901. serializationObject.influence = this.influence;
  78902. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78903. if (this.hasNormals) {
  78904. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78905. }
  78906. if (this.hasTangents) {
  78907. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78908. }
  78909. // Animations
  78910. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78911. return serializationObject;
  78912. };
  78913. // Statics
  78914. MorphTarget.Parse = function (serializationObject) {
  78915. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78916. result.setPositions(serializationObject.positions);
  78917. if (serializationObject.normals) {
  78918. result.setNormals(serializationObject.normals);
  78919. }
  78920. if (serializationObject.tangents) {
  78921. result.setTangents(serializationObject.tangents);
  78922. }
  78923. // Animations
  78924. if (serializationObject.animations) {
  78925. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78926. var parsedAnimation = serializationObject.animations[animationIndex];
  78927. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78928. }
  78929. }
  78930. return result;
  78931. };
  78932. MorphTarget.FromMesh = function (mesh, name, influence) {
  78933. if (!name) {
  78934. name = mesh.name;
  78935. }
  78936. var result = new MorphTarget(name, influence);
  78937. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78939. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78940. }
  78941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78942. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78943. }
  78944. return result;
  78945. };
  78946. return MorphTarget;
  78947. }());
  78948. BABYLON.MorphTarget = MorphTarget;
  78949. })(BABYLON || (BABYLON = {}));
  78950. //# sourceMappingURL=babylon.morphTarget.js.map
  78951. var BABYLON;
  78952. (function (BABYLON) {
  78953. var MorphTargetManager = /** @class */ (function () {
  78954. function MorphTargetManager(scene) {
  78955. if (scene === void 0) { scene = null; }
  78956. this._targets = new Array();
  78957. this._targetObservable = new Array();
  78958. this._activeTargets = new BABYLON.SmartArray(16);
  78959. this._supportsNormals = false;
  78960. this._supportsTangents = false;
  78961. this._vertexCount = 0;
  78962. this._uniqueId = 0;
  78963. this._tempInfluences = new Array();
  78964. if (!scene) {
  78965. scene = BABYLON.Engine.LastCreatedScene;
  78966. }
  78967. this._scene = scene;
  78968. if (this._scene) {
  78969. this._scene.morphTargetManagers.push(this);
  78970. this._uniqueId = this._scene.getUniqueId();
  78971. }
  78972. }
  78973. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78974. get: function () {
  78975. return this._uniqueId;
  78976. },
  78977. enumerable: true,
  78978. configurable: true
  78979. });
  78980. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78981. get: function () {
  78982. return this._vertexCount;
  78983. },
  78984. enumerable: true,
  78985. configurable: true
  78986. });
  78987. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78988. get: function () {
  78989. return this._supportsNormals;
  78990. },
  78991. enumerable: true,
  78992. configurable: true
  78993. });
  78994. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78995. get: function () {
  78996. return this._supportsTangents;
  78997. },
  78998. enumerable: true,
  78999. configurable: true
  79000. });
  79001. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79002. get: function () {
  79003. return this._targets.length;
  79004. },
  79005. enumerable: true,
  79006. configurable: true
  79007. });
  79008. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79009. get: function () {
  79010. return this._activeTargets.length;
  79011. },
  79012. enumerable: true,
  79013. configurable: true
  79014. });
  79015. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79016. get: function () {
  79017. return this._influences;
  79018. },
  79019. enumerable: true,
  79020. configurable: true
  79021. });
  79022. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79023. return this._activeTargets.data[index];
  79024. };
  79025. MorphTargetManager.prototype.getTarget = function (index) {
  79026. return this._targets[index];
  79027. };
  79028. MorphTargetManager.prototype.addTarget = function (target) {
  79029. var _this = this;
  79030. this._targets.push(target);
  79031. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79032. _this._syncActiveTargets(needUpdate);
  79033. }));
  79034. this._syncActiveTargets(true);
  79035. };
  79036. MorphTargetManager.prototype.removeTarget = function (target) {
  79037. var index = this._targets.indexOf(target);
  79038. if (index >= 0) {
  79039. this._targets.splice(index, 1);
  79040. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79041. this._syncActiveTargets(true);
  79042. }
  79043. };
  79044. /**
  79045. * Serializes the current manager into a Serialization object.
  79046. * Returns the serialized object.
  79047. */
  79048. MorphTargetManager.prototype.serialize = function () {
  79049. var serializationObject = {};
  79050. serializationObject.id = this.uniqueId;
  79051. serializationObject.targets = [];
  79052. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79053. var target = _a[_i];
  79054. serializationObject.targets.push(target.serialize());
  79055. }
  79056. return serializationObject;
  79057. };
  79058. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79059. var influenceCount = 0;
  79060. this._activeTargets.reset();
  79061. this._supportsNormals = true;
  79062. this._supportsTangents = true;
  79063. this._vertexCount = 0;
  79064. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79065. var target = _a[_i];
  79066. this._activeTargets.push(target);
  79067. this._tempInfluences[influenceCount++] = target.influence;
  79068. var positions = target.getPositions();
  79069. if (positions) {
  79070. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79071. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79072. var vertexCount = positions.length / 3;
  79073. if (this._vertexCount === 0) {
  79074. this._vertexCount = vertexCount;
  79075. }
  79076. else if (this._vertexCount !== vertexCount) {
  79077. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79078. return;
  79079. }
  79080. }
  79081. }
  79082. if (!this._influences || this._influences.length !== influenceCount) {
  79083. this._influences = new Float32Array(influenceCount);
  79084. }
  79085. for (var index = 0; index < influenceCount; index++) {
  79086. this._influences[index] = this._tempInfluences[index];
  79087. }
  79088. if (needUpdate && this._scene) {
  79089. // Flag meshes as dirty to resync with the active targets
  79090. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79091. var mesh = _c[_b];
  79092. if (mesh.morphTargetManager === this) {
  79093. mesh._syncGeometryWithMorphTargetManager();
  79094. }
  79095. }
  79096. }
  79097. };
  79098. // Statics
  79099. MorphTargetManager.Parse = function (serializationObject, scene) {
  79100. var result = new MorphTargetManager(scene);
  79101. result._uniqueId = serializationObject.id;
  79102. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79103. var targetData = _a[_i];
  79104. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79105. }
  79106. return result;
  79107. };
  79108. return MorphTargetManager;
  79109. }());
  79110. BABYLON.MorphTargetManager = MorphTargetManager;
  79111. })(BABYLON || (BABYLON = {}));
  79112. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79113. var BABYLON;
  79114. (function (BABYLON) {
  79115. var Octree = /** @class */ (function () {
  79116. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79117. if (maxDepth === void 0) { maxDepth = 2; }
  79118. this.maxDepth = maxDepth;
  79119. this.dynamicContent = new Array();
  79120. this._maxBlockCapacity = maxBlockCapacity || 64;
  79121. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79122. this._creationFunc = creationFunc;
  79123. }
  79124. // Methods
  79125. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79126. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79127. };
  79128. Octree.prototype.addMesh = function (entry) {
  79129. for (var index = 0; index < this.blocks.length; index++) {
  79130. var block = this.blocks[index];
  79131. block.addEntry(entry);
  79132. }
  79133. };
  79134. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79135. this._selectionContent.reset();
  79136. for (var index = 0; index < this.blocks.length; index++) {
  79137. var block = this.blocks[index];
  79138. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79139. }
  79140. if (allowDuplicate) {
  79141. this._selectionContent.concat(this.dynamicContent);
  79142. }
  79143. else {
  79144. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79145. }
  79146. return this._selectionContent;
  79147. };
  79148. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79149. this._selectionContent.reset();
  79150. for (var index = 0; index < this.blocks.length; index++) {
  79151. var block = this.blocks[index];
  79152. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79153. }
  79154. if (allowDuplicate) {
  79155. this._selectionContent.concat(this.dynamicContent);
  79156. }
  79157. else {
  79158. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79159. }
  79160. return this._selectionContent;
  79161. };
  79162. Octree.prototype.intersectsRay = function (ray) {
  79163. this._selectionContent.reset();
  79164. for (var index = 0; index < this.blocks.length; index++) {
  79165. var block = this.blocks[index];
  79166. block.intersectsRay(ray, this._selectionContent);
  79167. }
  79168. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79169. return this._selectionContent;
  79170. };
  79171. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79172. target.blocks = new Array();
  79173. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79174. // Segmenting space
  79175. for (var x = 0; x < 2; x++) {
  79176. for (var y = 0; y < 2; y++) {
  79177. for (var z = 0; z < 2; z++) {
  79178. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79179. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79180. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79181. block.addEntries(entries);
  79182. target.blocks.push(block);
  79183. }
  79184. }
  79185. }
  79186. };
  79187. Octree.CreationFuncForMeshes = function (entry, block) {
  79188. var boundingInfo = entry.getBoundingInfo();
  79189. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79190. block.entries.push(entry);
  79191. }
  79192. };
  79193. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79194. var boundingInfo = entry.getBoundingInfo();
  79195. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79196. block.entries.push(entry);
  79197. }
  79198. };
  79199. return Octree;
  79200. }());
  79201. BABYLON.Octree = Octree;
  79202. })(BABYLON || (BABYLON = {}));
  79203. //# sourceMappingURL=babylon.octree.js.map
  79204. var BABYLON;
  79205. (function (BABYLON) {
  79206. var OctreeBlock = /** @class */ (function () {
  79207. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79208. this.entries = new Array();
  79209. this._boundingVectors = new Array();
  79210. this._capacity = capacity;
  79211. this._depth = depth;
  79212. this._maxDepth = maxDepth;
  79213. this._creationFunc = creationFunc;
  79214. this._minPoint = minPoint;
  79215. this._maxPoint = maxPoint;
  79216. this._boundingVectors.push(minPoint.clone());
  79217. this._boundingVectors.push(maxPoint.clone());
  79218. this._boundingVectors.push(minPoint.clone());
  79219. this._boundingVectors[2].x = maxPoint.x;
  79220. this._boundingVectors.push(minPoint.clone());
  79221. this._boundingVectors[3].y = maxPoint.y;
  79222. this._boundingVectors.push(minPoint.clone());
  79223. this._boundingVectors[4].z = maxPoint.z;
  79224. this._boundingVectors.push(maxPoint.clone());
  79225. this._boundingVectors[5].z = minPoint.z;
  79226. this._boundingVectors.push(maxPoint.clone());
  79227. this._boundingVectors[6].x = minPoint.x;
  79228. this._boundingVectors.push(maxPoint.clone());
  79229. this._boundingVectors[7].y = minPoint.y;
  79230. }
  79231. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79232. // Property
  79233. get: function () {
  79234. return this._capacity;
  79235. },
  79236. enumerable: true,
  79237. configurable: true
  79238. });
  79239. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79240. get: function () {
  79241. return this._minPoint;
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79247. get: function () {
  79248. return this._maxPoint;
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. // Methods
  79254. OctreeBlock.prototype.addEntry = function (entry) {
  79255. if (this.blocks) {
  79256. for (var index = 0; index < this.blocks.length; index++) {
  79257. var block = this.blocks[index];
  79258. block.addEntry(entry);
  79259. }
  79260. return;
  79261. }
  79262. this._creationFunc(entry, this);
  79263. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79264. this.createInnerBlocks();
  79265. }
  79266. };
  79267. OctreeBlock.prototype.addEntries = function (entries) {
  79268. for (var index = 0; index < entries.length; index++) {
  79269. var mesh = entries[index];
  79270. this.addEntry(mesh);
  79271. }
  79272. };
  79273. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79274. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79275. if (this.blocks) {
  79276. for (var index = 0; index < this.blocks.length; index++) {
  79277. var block = this.blocks[index];
  79278. block.select(frustumPlanes, selection, allowDuplicate);
  79279. }
  79280. return;
  79281. }
  79282. if (allowDuplicate) {
  79283. selection.concat(this.entries);
  79284. }
  79285. else {
  79286. selection.concatWithNoDuplicate(this.entries);
  79287. }
  79288. }
  79289. };
  79290. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79291. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79292. if (this.blocks) {
  79293. for (var index = 0; index < this.blocks.length; index++) {
  79294. var block = this.blocks[index];
  79295. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79296. }
  79297. return;
  79298. }
  79299. if (allowDuplicate) {
  79300. selection.concat(this.entries);
  79301. }
  79302. else {
  79303. selection.concatWithNoDuplicate(this.entries);
  79304. }
  79305. }
  79306. };
  79307. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79308. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79309. if (this.blocks) {
  79310. for (var index = 0; index < this.blocks.length; index++) {
  79311. var block = this.blocks[index];
  79312. block.intersectsRay(ray, selection);
  79313. }
  79314. return;
  79315. }
  79316. selection.concatWithNoDuplicate(this.entries);
  79317. }
  79318. };
  79319. OctreeBlock.prototype.createInnerBlocks = function () {
  79320. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79321. };
  79322. return OctreeBlock;
  79323. }());
  79324. BABYLON.OctreeBlock = OctreeBlock;
  79325. })(BABYLON || (BABYLON = {}));
  79326. //# sourceMappingURL=babylon.octreeBlock.js.map
  79327. var BABYLON;
  79328. (function (BABYLON) {
  79329. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79330. __extends(VRDistortionCorrectionPostProcess, _super);
  79331. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79332. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79333. 'LensCenter',
  79334. 'Scale',
  79335. 'ScaleIn',
  79336. 'HmdWarpParam'
  79337. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79338. _this._isRightEye = isRightEye;
  79339. _this._distortionFactors = vrMetrics.distortionK;
  79340. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79341. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79342. _this.adaptScaleToCurrentViewport = true;
  79343. _this.onSizeChangedObservable.add(function () {
  79344. _this.aspectRatio = _this.width * .5 / _this.height;
  79345. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79346. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79347. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79348. });
  79349. _this.onApplyObservable.add(function (effect) {
  79350. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79351. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79352. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79353. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79354. });
  79355. return _this;
  79356. }
  79357. return VRDistortionCorrectionPostProcess;
  79358. }(BABYLON.PostProcess));
  79359. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79360. })(BABYLON || (BABYLON = {}));
  79361. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79362. var BABYLON;
  79363. (function (BABYLON) {
  79364. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79365. __extends(AnaglyphPostProcess, _super);
  79366. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79367. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79368. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79369. _this.onApplyObservable.add(function (effect) {
  79370. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79371. });
  79372. return _this;
  79373. }
  79374. return AnaglyphPostProcess;
  79375. }(BABYLON.PostProcess));
  79376. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79377. })(BABYLON || (BABYLON = {}));
  79378. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79382. __extends(StereoscopicInterlacePostProcess, _super);
  79383. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79384. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79385. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79386. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79387. _this.onSizeChangedObservable.add(function () {
  79388. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79389. });
  79390. _this.onApplyObservable.add(function (effect) {
  79391. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79392. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79393. });
  79394. return _this;
  79395. }
  79396. return StereoscopicInterlacePostProcess;
  79397. }(BABYLON.PostProcess));
  79398. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79399. })(BABYLON || (BABYLON = {}));
  79400. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79401. var BABYLON;
  79402. (function (BABYLON) {
  79403. /**
  79404. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79405. * Screen rotation is taken into account.
  79406. */
  79407. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79408. function FreeCameraDeviceOrientationInput() {
  79409. var _this = this;
  79410. this._screenOrientationAngle = 0;
  79411. this._screenQuaternion = new BABYLON.Quaternion();
  79412. this._alpha = 0;
  79413. this._beta = 0;
  79414. this._gamma = 0;
  79415. this._orientationChanged = function () {
  79416. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79417. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79418. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79419. };
  79420. this._deviceOrientation = function (evt) {
  79421. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79422. _this._beta = evt.beta !== null ? evt.beta : 0;
  79423. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79424. };
  79425. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79426. this._orientationChanged();
  79427. }
  79428. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79429. get: function () {
  79430. return this._camera;
  79431. },
  79432. set: function (camera) {
  79433. this._camera = camera;
  79434. if (this._camera != null && !this._camera.rotationQuaternion) {
  79435. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79436. }
  79437. },
  79438. enumerable: true,
  79439. configurable: true
  79440. });
  79441. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79442. window.addEventListener("orientationchange", this._orientationChanged);
  79443. window.addEventListener("deviceorientation", this._deviceOrientation);
  79444. //In certain cases, the attach control is called AFTER orientation was changed,
  79445. //So this is needed.
  79446. this._orientationChanged();
  79447. };
  79448. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79449. window.removeEventListener("orientationchange", this._orientationChanged);
  79450. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79451. };
  79452. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79453. //if no device orientation provided, don't update the rotation.
  79454. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79455. if (!this._alpha)
  79456. return;
  79457. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79458. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79459. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79460. //Mirror on XY Plane
  79461. this._camera.rotationQuaternion.z *= -1;
  79462. this._camera.rotationQuaternion.w *= -1;
  79463. };
  79464. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79465. return "FreeCameraDeviceOrientationInput";
  79466. };
  79467. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79468. return "deviceOrientation";
  79469. };
  79470. return FreeCameraDeviceOrientationInput;
  79471. }());
  79472. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79473. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79474. })(BABYLON || (BABYLON = {}));
  79475. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79476. var BABYLON;
  79477. (function (BABYLON) {
  79478. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79479. function ArcRotateCameraVRDeviceOrientationInput() {
  79480. this.alphaCorrection = 1;
  79481. this.betaCorrection = 1;
  79482. this.gammaCorrection = 1;
  79483. this._alpha = 0;
  79484. this._gamma = 0;
  79485. this._dirty = false;
  79486. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79487. }
  79488. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79489. this.camera.attachControl(element, noPreventDefault);
  79490. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79491. };
  79492. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79493. if (evt.alpha !== null) {
  79494. this._alpha = +evt.alpha | 0;
  79495. }
  79496. if (evt.gamma !== null) {
  79497. this._gamma = +evt.gamma | 0;
  79498. }
  79499. this._dirty = true;
  79500. };
  79501. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79502. if (this._dirty) {
  79503. this._dirty = false;
  79504. if (this._gamma < 0) {
  79505. this._gamma = 180 + this._gamma;
  79506. }
  79507. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79508. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79509. }
  79510. };
  79511. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79512. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79513. };
  79514. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79515. return "ArcRotateCameraVRDeviceOrientationInput";
  79516. };
  79517. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79518. return "VRDeviceOrientation";
  79519. };
  79520. return ArcRotateCameraVRDeviceOrientationInput;
  79521. }());
  79522. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79523. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79524. })(BABYLON || (BABYLON = {}));
  79525. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79526. var BABYLON;
  79527. (function (BABYLON) {
  79528. var VRCameraMetrics = /** @class */ (function () {
  79529. function VRCameraMetrics() {
  79530. this.compensateDistortion = true;
  79531. }
  79532. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79533. get: function () {
  79534. return this.hResolution / (2 * this.vResolution);
  79535. },
  79536. enumerable: true,
  79537. configurable: true
  79538. });
  79539. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79540. get: function () {
  79541. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79542. },
  79543. enumerable: true,
  79544. configurable: true
  79545. });
  79546. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79547. get: function () {
  79548. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79549. var h = (4 * meters) / this.hScreenSize;
  79550. return BABYLON.Matrix.Translation(h, 0, 0);
  79551. },
  79552. enumerable: true,
  79553. configurable: true
  79554. });
  79555. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79556. get: function () {
  79557. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79558. var h = (4 * meters) / this.hScreenSize;
  79559. return BABYLON.Matrix.Translation(-h, 0, 0);
  79560. },
  79561. enumerable: true,
  79562. configurable: true
  79563. });
  79564. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79565. get: function () {
  79566. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79567. },
  79568. enumerable: true,
  79569. configurable: true
  79570. });
  79571. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79572. get: function () {
  79573. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79574. },
  79575. enumerable: true,
  79576. configurable: true
  79577. });
  79578. VRCameraMetrics.GetDefault = function () {
  79579. var result = new VRCameraMetrics();
  79580. result.hResolution = 1280;
  79581. result.vResolution = 800;
  79582. result.hScreenSize = 0.149759993;
  79583. result.vScreenSize = 0.0935999975;
  79584. result.vScreenCenter = 0.0467999987;
  79585. result.eyeToScreenDistance = 0.0410000011;
  79586. result.lensSeparationDistance = 0.0635000020;
  79587. result.interpupillaryDistance = 0.0640000030;
  79588. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79589. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79590. result.postProcessScaleFactor = 1.714605507808412;
  79591. result.lensCenterOffset = 0.151976421;
  79592. return result;
  79593. };
  79594. return VRCameraMetrics;
  79595. }());
  79596. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79597. })(BABYLON || (BABYLON = {}));
  79598. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79599. var BABYLON;
  79600. (function (BABYLON) {
  79601. /**
  79602. * This represents a WebVR camera.
  79603. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79604. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79605. */
  79606. var WebVRFreeCamera = /** @class */ (function (_super) {
  79607. __extends(WebVRFreeCamera, _super);
  79608. /**
  79609. * Instantiates a WebVRFreeCamera.
  79610. * @param name The name of the WebVRFreeCamera
  79611. * @param position The starting anchor position for the camera
  79612. * @param scene The scene the camera belongs to
  79613. * @param webVROptions a set of customizable options for the webVRCamera
  79614. */
  79615. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79616. if (webVROptions === void 0) { webVROptions = {}; }
  79617. var _this = _super.call(this, name, position, scene) || this;
  79618. _this.webVROptions = webVROptions;
  79619. /**
  79620. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79621. */
  79622. _this._vrDevice = null;
  79623. /**
  79624. * The rawPose of the vrDevice.
  79625. */
  79626. _this.rawPose = null;
  79627. _this._specsVersion = "1.1";
  79628. _this._attached = false;
  79629. _this._descendants = [];
  79630. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79631. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79632. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79633. _this._standingMatrix = null;
  79634. /**
  79635. * Represents device position in babylon space.
  79636. */
  79637. _this.devicePosition = BABYLON.Vector3.Zero();
  79638. /**
  79639. * Represents device rotation in babylon space.
  79640. */
  79641. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79642. /**
  79643. * The scale of the device to be used when translating from device space to babylon space.
  79644. */
  79645. _this.deviceScaleFactor = 1;
  79646. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79647. _this._worldToDevice = BABYLON.Matrix.Identity();
  79648. /**
  79649. * References to the webVR controllers for the vrDevice.
  79650. */
  79651. _this.controllers = [];
  79652. /**
  79653. * Emits an event when a controller is attached.
  79654. */
  79655. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79656. /**
  79657. * Emits an event when a controller's mesh has been loaded;
  79658. */
  79659. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79660. /**
  79661. * If the rig cameras be used as parent instead of this camera.
  79662. */
  79663. _this.rigParenting = true;
  79664. _this._defaultHeight = undefined;
  79665. _this._workingVector = BABYLON.Vector3.Zero();
  79666. _this._oneVector = BABYLON.Vector3.One();
  79667. _this._workingMatrix = BABYLON.Matrix.Identity();
  79668. _this._cache.position = BABYLON.Vector3.Zero();
  79669. if (webVROptions.defaultHeight) {
  79670. _this._defaultHeight = webVROptions.defaultHeight;
  79671. _this.position.y = _this._defaultHeight;
  79672. }
  79673. _this.minZ = 0.1;
  79674. //legacy support - the compensation boolean was removed.
  79675. if (arguments.length === 5) {
  79676. _this.webVROptions = arguments[4];
  79677. }
  79678. // default webVR options
  79679. if (_this.webVROptions.trackPosition == undefined) {
  79680. _this.webVROptions.trackPosition = true;
  79681. }
  79682. if (_this.webVROptions.controllerMeshes == undefined) {
  79683. _this.webVROptions.controllerMeshes = true;
  79684. }
  79685. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79686. _this.webVROptions.defaultLightingOnControllers = true;
  79687. }
  79688. _this.rotationQuaternion = new BABYLON.Quaternion();
  79689. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79690. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79691. }
  79692. //enable VR
  79693. var engine = _this.getEngine();
  79694. _this._onVREnabled = function (success) { if (success) {
  79695. _this.initControllers();
  79696. } };
  79697. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79698. engine.initWebVR().add(function (event) {
  79699. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79700. return;
  79701. }
  79702. _this._vrDevice = event.vrDisplay;
  79703. //reset the rig parameters.
  79704. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79705. if (_this._attached) {
  79706. _this.getEngine().enableVR();
  79707. }
  79708. });
  79709. if (typeof (VRFrameData) !== "undefined")
  79710. _this._frameData = new VRFrameData();
  79711. /**
  79712. * The idea behind the following lines:
  79713. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79714. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79715. * the second will not show it correctly.
  79716. *
  79717. * To solve this - each object that has the camera as parent will be added to a protected array.
  79718. * When the rig camera renders, it will take this array and set all of those to be its children.
  79719. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79720. * Amazing!
  79721. */
  79722. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79723. if (camera.parent === _this && _this.rigParenting) {
  79724. _this._descendants = _this.getDescendants(true, function (n) {
  79725. // don't take the cameras or the controllers!
  79726. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79727. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79728. return !isController && !isRigCamera;
  79729. });
  79730. _this._descendants.forEach(function (node) {
  79731. node.parent = camera;
  79732. });
  79733. }
  79734. });
  79735. scene.onAfterCameraRenderObservable.add(function (camera) {
  79736. if (camera.parent === _this && _this.rigParenting) {
  79737. _this._descendants.forEach(function (node) {
  79738. node.parent = _this;
  79739. });
  79740. }
  79741. });
  79742. return _this;
  79743. }
  79744. /**
  79745. * Gets the device distance from the ground in meters.
  79746. * @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.
  79747. */
  79748. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79749. if (this._standingMatrix) {
  79750. // Add standing matrix offset to get real offset from ground in room
  79751. this._standingMatrix.getTranslationToRef(this._workingVector);
  79752. return this._deviceRoomPosition.y + this._workingVector.y;
  79753. }
  79754. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79755. return this._defaultHeight || 0;
  79756. };
  79757. /**
  79758. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79759. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79760. */
  79761. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79762. var _this = this;
  79763. if (callback === void 0) { callback = function (bool) { }; }
  79764. // Use standing matrix if available
  79765. this.getEngine().initWebVRAsync().then(function (result) {
  79766. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79767. callback(false);
  79768. }
  79769. else {
  79770. _this._standingMatrix = new BABYLON.Matrix();
  79771. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79772. if (!_this.getScene().useRightHandedSystem) {
  79773. [2, 6, 8, 9, 14].forEach(function (num) {
  79774. if (_this._standingMatrix) {
  79775. _this._standingMatrix.m[num] *= -1;
  79776. }
  79777. });
  79778. }
  79779. callback(true);
  79780. }
  79781. });
  79782. };
  79783. /**
  79784. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79785. * @returns A promise with a boolean set to if the standing matrix is supported.
  79786. */
  79787. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79788. var _this = this;
  79789. return new Promise(function (res, rej) {
  79790. _this.useStandingMatrix(function (supported) {
  79791. res(supported);
  79792. });
  79793. });
  79794. };
  79795. /**
  79796. * Disposes the camera
  79797. */
  79798. WebVRFreeCamera.prototype.dispose = function () {
  79799. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79800. _super.prototype.dispose.call(this);
  79801. };
  79802. /**
  79803. * Gets a vrController by name.
  79804. * @param name The name of the controller to retreive
  79805. * @returns the controller matching the name specified or null if not found
  79806. */
  79807. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79808. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79809. var gp = _a[_i];
  79810. if (gp.hand === name) {
  79811. return gp;
  79812. }
  79813. }
  79814. return null;
  79815. };
  79816. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79817. /**
  79818. * The controller corrisponding to the users left hand.
  79819. */
  79820. get: function () {
  79821. if (!this._leftController) {
  79822. this._leftController = this.getControllerByName("left");
  79823. }
  79824. return this._leftController;
  79825. },
  79826. enumerable: true,
  79827. configurable: true
  79828. });
  79829. ;
  79830. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79831. /**
  79832. * The controller corrisponding to the users right hand.
  79833. */
  79834. get: function () {
  79835. if (!this._rightController) {
  79836. this._rightController = this.getControllerByName("right");
  79837. }
  79838. return this._rightController;
  79839. },
  79840. enumerable: true,
  79841. configurable: true
  79842. });
  79843. ;
  79844. /**
  79845. * Casts a ray forward from the vrCamera's gaze.
  79846. * @param length Length of the ray (default: 100)
  79847. * @returns the ray corrisponding to the gaze
  79848. */
  79849. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79850. if (length === void 0) { length = 100; }
  79851. if (this.leftCamera) {
  79852. // Use left eye to avoid computation to compute center on every call
  79853. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79854. }
  79855. else {
  79856. return _super.prototype.getForwardRay.call(this, length);
  79857. }
  79858. };
  79859. /**
  79860. * Updates the camera based on device's frame data
  79861. */
  79862. WebVRFreeCamera.prototype._checkInputs = function () {
  79863. if (this._vrDevice && this._vrDevice.isPresenting) {
  79864. this._vrDevice.getFrameData(this._frameData);
  79865. this.updateFromDevice(this._frameData.pose);
  79866. }
  79867. _super.prototype._checkInputs.call(this);
  79868. };
  79869. /**
  79870. * Updates the poseControlled values based on the input device pose.
  79871. * @param poseData Pose coming from the device
  79872. */
  79873. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79874. if (poseData && poseData.orientation) {
  79875. this.rawPose = poseData;
  79876. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79877. if (this.getScene().useRightHandedSystem) {
  79878. this._deviceRoomRotationQuaternion.z *= -1;
  79879. this._deviceRoomRotationQuaternion.w *= -1;
  79880. }
  79881. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79882. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79883. if (this.getScene().useRightHandedSystem) {
  79884. this._deviceRoomPosition.z *= -1;
  79885. }
  79886. }
  79887. }
  79888. };
  79889. /**
  79890. * WebVR's attach control will start broadcasting frames to the device.
  79891. * Note that in certain browsers (chrome for example) this function must be called
  79892. * within a user-interaction callback. Example:
  79893. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79894. *
  79895. * @param element html element to attach the vrDevice to
  79896. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79897. */
  79898. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79899. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79900. this._attached = true;
  79901. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79902. if (this._vrDevice) {
  79903. this.getEngine().enableVR();
  79904. }
  79905. };
  79906. /**
  79907. * Detaches the camera from the html element and disables VR
  79908. *
  79909. * @param element html element to detach from
  79910. */
  79911. WebVRFreeCamera.prototype.detachControl = function (element) {
  79912. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79913. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79914. _super.prototype.detachControl.call(this, element);
  79915. this._attached = false;
  79916. this.getEngine().disableVR();
  79917. };
  79918. /**
  79919. * @returns the name of this class
  79920. */
  79921. WebVRFreeCamera.prototype.getClassName = function () {
  79922. return "WebVRFreeCamera";
  79923. };
  79924. /**
  79925. * Calls resetPose on the vrDisplay
  79926. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79927. */
  79928. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79929. //uses the vrDisplay's "resetPose()".
  79930. //pitch and roll won't be affected.
  79931. this._vrDevice.resetPose();
  79932. };
  79933. /**
  79934. * Updates the rig cameras (left and right eye)
  79935. */
  79936. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79937. var camLeft = this._rigCameras[0];
  79938. var camRight = this._rigCameras[1];
  79939. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79940. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79941. camLeft.position.copyFrom(this._deviceRoomPosition);
  79942. camRight.position.copyFrom(this._deviceRoomPosition);
  79943. };
  79944. /**
  79945. * Updates the cached values of the camera
  79946. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79947. */
  79948. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79949. var _this = this;
  79950. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79951. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79952. if (!this.updateCacheCalled) {
  79953. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79954. this.updateCacheCalled = true;
  79955. this.update();
  79956. }
  79957. // Set working vector to the device position in room space rotated by the new rotation
  79958. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79959. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79960. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79961. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79962. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79963. // Add translation from anchor position
  79964. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79965. this._workingVector.addInPlace(this.position);
  79966. this._workingVector.subtractInPlace(this._cache.position);
  79967. this._deviceToWorld.setTranslation(this._workingVector);
  79968. // Set an inverted matrix to be used when updating the camera
  79969. this._deviceToWorld.invertToRef(this._worldToDevice);
  79970. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79971. this.controllers.forEach(function (controller) {
  79972. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79973. controller.update();
  79974. });
  79975. }
  79976. if (!ignoreParentClass) {
  79977. _super.prototype._updateCache.call(this);
  79978. }
  79979. this.updateCacheCalled = false;
  79980. };
  79981. /**
  79982. * Updates the current device position and rotation in the babylon world
  79983. */
  79984. WebVRFreeCamera.prototype.update = function () {
  79985. // Get current device position in babylon world
  79986. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79987. // Get current device rotation in babylon world
  79988. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79989. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79990. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79991. _super.prototype.update.call(this);
  79992. };
  79993. /**
  79994. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79995. * @returns an identity matrix
  79996. */
  79997. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79998. return BABYLON.Matrix.Identity();
  79999. };
  80000. /**
  80001. * This function is called by the two RIG cameras.
  80002. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80003. */
  80004. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80005. var _this = this;
  80006. // Update the parent camera prior to using a child camera to avoid desynchronization
  80007. var parentCamera = this._cameraRigParams["parentCamera"];
  80008. parentCamera._updateCache();
  80009. //WebVR 1.1
  80010. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80011. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80012. if (!this.getScene().useRightHandedSystem) {
  80013. [2, 6, 8, 9, 14].forEach(function (num) {
  80014. _this._webvrViewMatrix.m[num] *= -1;
  80015. });
  80016. }
  80017. // update the camera rotation matrix
  80018. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80019. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80020. // Computing target and final matrix
  80021. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80022. // should the view matrix be updated with scale and position offset?
  80023. if (parentCamera.deviceScaleFactor !== 1) {
  80024. this._webvrViewMatrix.invert();
  80025. // scale the position, if set
  80026. if (parentCamera.deviceScaleFactor) {
  80027. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80028. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80029. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80030. }
  80031. this._webvrViewMatrix.invert();
  80032. }
  80033. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80034. return this._webvrViewMatrix;
  80035. };
  80036. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80037. var _this = this;
  80038. var parentCamera = this.parent;
  80039. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80040. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80041. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80042. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80043. //babylon compatible matrix
  80044. if (!this.getScene().useRightHandedSystem) {
  80045. [8, 9, 10, 11].forEach(function (num) {
  80046. _this._projectionMatrix.m[num] *= -1;
  80047. });
  80048. }
  80049. return this._projectionMatrix;
  80050. };
  80051. /**
  80052. * Initializes the controllers and their meshes
  80053. */
  80054. WebVRFreeCamera.prototype.initControllers = function () {
  80055. var _this = this;
  80056. this.controllers = [];
  80057. var manager = this.getScene().gamepadManager;
  80058. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80059. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80060. var webVrController = gamepad;
  80061. if (webVrController.defaultModel) {
  80062. webVrController.defaultModel.setEnabled(false);
  80063. }
  80064. if (webVrController.hand === "right") {
  80065. _this._rightController = null;
  80066. }
  80067. if (webVrController.hand === "left") {
  80068. _this._leftController = null;
  80069. }
  80070. var controllerIndex = _this.controllers.indexOf(webVrController);
  80071. if (controllerIndex !== -1) {
  80072. _this.controllers.splice(controllerIndex, 1);
  80073. }
  80074. }
  80075. });
  80076. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80077. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80078. var webVrController_1 = gamepad;
  80079. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80080. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80081. if (_this.webVROptions.controllerMeshes) {
  80082. if (webVrController_1.defaultModel) {
  80083. webVrController_1.defaultModel.setEnabled(true);
  80084. }
  80085. else {
  80086. // Load the meshes
  80087. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80088. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80089. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80090. if (_this.webVROptions.defaultLightingOnControllers) {
  80091. if (!_this._lightOnControllers) {
  80092. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80093. }
  80094. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80095. var children = mesh.getChildren();
  80096. if (children.length !== 0) {
  80097. children.forEach(function (mesh) {
  80098. light.includedOnlyMeshes.push(mesh);
  80099. activateLightOnSubMeshes_1(mesh, light);
  80100. });
  80101. }
  80102. };
  80103. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80104. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80105. }
  80106. });
  80107. }
  80108. }
  80109. webVrController_1.attachToPoseControlledCamera(_this);
  80110. // since this is async - sanity check. Is the controller already stored?
  80111. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80112. //add to the controllers array
  80113. _this.controllers.push(webVrController_1);
  80114. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80115. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80116. // So we're overriding setting left & right manually to be sure
  80117. var firstViveWandDetected = false;
  80118. for (var i = 0; i < _this.controllers.length; i++) {
  80119. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80120. if (!firstViveWandDetected) {
  80121. firstViveWandDetected = true;
  80122. _this.controllers[i].hand = "left";
  80123. }
  80124. else {
  80125. _this.controllers[i].hand = "right";
  80126. }
  80127. }
  80128. }
  80129. //did we find enough controllers? Great! let the developer know.
  80130. if (_this.controllers.length >= 2) {
  80131. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80132. }
  80133. }
  80134. }
  80135. });
  80136. };
  80137. return WebVRFreeCamera;
  80138. }(BABYLON.FreeCamera));
  80139. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80140. })(BABYLON || (BABYLON = {}));
  80141. //# sourceMappingURL=babylon.webVRCamera.js.map
  80142. var BABYLON;
  80143. (function (BABYLON) {
  80144. // We're mainly based on the logic defined into the FreeCamera code
  80145. /**
  80146. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80147. * being tilted forward or back and left or right.
  80148. */
  80149. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80150. __extends(DeviceOrientationCamera, _super);
  80151. /**
  80152. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80153. * @param name The name of the camera
  80154. * @param position The start position camera
  80155. * @param scene The scene the camera belongs to
  80156. */
  80157. function DeviceOrientationCamera(name, position, scene) {
  80158. var _this = _super.call(this, name, position, scene) || this;
  80159. _this._quaternionCache = new BABYLON.Quaternion();
  80160. _this.inputs.addDeviceOrientation();
  80161. return _this;
  80162. }
  80163. /**
  80164. * Gets the current instance class name ("DeviceOrientationCamera").
  80165. * This helps avoiding instanceof at run time.
  80166. * @returns the class name
  80167. */
  80168. DeviceOrientationCamera.prototype.getClassName = function () {
  80169. return "DeviceOrientationCamera";
  80170. };
  80171. /**
  80172. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80173. */
  80174. DeviceOrientationCamera.prototype._checkInputs = function () {
  80175. _super.prototype._checkInputs.call(this);
  80176. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80177. if (this._initialQuaternion) {
  80178. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80179. }
  80180. };
  80181. /**
  80182. * Reset the camera to its default orientation on the specified axis only.
  80183. * @param axis The axis to reset
  80184. */
  80185. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80186. var _this = this;
  80187. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80188. //can only work if this camera has a rotation quaternion already.
  80189. if (!this.rotationQuaternion)
  80190. return;
  80191. if (!this._initialQuaternion) {
  80192. this._initialQuaternion = new BABYLON.Quaternion();
  80193. }
  80194. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80195. ['x', 'y', 'z'].forEach(function (axisName) {
  80196. if (!axis[axisName]) {
  80197. _this._initialQuaternion[axisName] = 0;
  80198. }
  80199. else {
  80200. _this._initialQuaternion[axisName] *= -1;
  80201. }
  80202. });
  80203. this._initialQuaternion.normalize();
  80204. //force rotation update
  80205. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80206. };
  80207. return DeviceOrientationCamera;
  80208. }(BABYLON.FreeCamera));
  80209. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80210. })(BABYLON || (BABYLON = {}));
  80211. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80212. var BABYLON;
  80213. (function (BABYLON) {
  80214. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80215. __extends(VRDeviceOrientationFreeCamera, _super);
  80216. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80217. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80218. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80219. var _this = _super.call(this, name, position, scene) || this;
  80220. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80221. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80222. return _this;
  80223. }
  80224. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80225. return "VRDeviceOrientationFreeCamera";
  80226. };
  80227. return VRDeviceOrientationFreeCamera;
  80228. }(BABYLON.DeviceOrientationCamera));
  80229. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80230. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80231. __extends(VRDeviceOrientationGamepadCamera, _super);
  80232. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80233. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80234. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80235. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80236. _this.inputs.addGamepad();
  80237. return _this;
  80238. }
  80239. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80240. return "VRDeviceOrientationGamepadCamera";
  80241. };
  80242. return VRDeviceOrientationGamepadCamera;
  80243. }(VRDeviceOrientationFreeCamera));
  80244. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80245. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80246. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80247. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80248. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80249. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80250. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80251. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80252. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80253. _this.inputs.addVRDeviceOrientation();
  80254. return _this;
  80255. }
  80256. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80257. return "VRDeviceOrientationArcRotateCamera";
  80258. };
  80259. return VRDeviceOrientationArcRotateCamera;
  80260. }(BABYLON.ArcRotateCamera));
  80261. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80262. })(BABYLON || (BABYLON = {}));
  80263. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80264. var BABYLON;
  80265. (function (BABYLON) {
  80266. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80267. __extends(AnaglyphFreeCamera, _super);
  80268. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80269. var _this = _super.call(this, name, position, scene) || this;
  80270. _this.interaxialDistance = interaxialDistance;
  80271. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80272. return _this;
  80273. }
  80274. AnaglyphFreeCamera.prototype.getClassName = function () {
  80275. return "AnaglyphFreeCamera";
  80276. };
  80277. return AnaglyphFreeCamera;
  80278. }(BABYLON.FreeCamera));
  80279. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80280. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80281. __extends(AnaglyphArcRotateCamera, _super);
  80282. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80283. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80284. _this.interaxialDistance = interaxialDistance;
  80285. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80286. return _this;
  80287. }
  80288. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80289. return "AnaglyphArcRotateCamera";
  80290. };
  80291. return AnaglyphArcRotateCamera;
  80292. }(BABYLON.ArcRotateCamera));
  80293. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80294. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80295. __extends(AnaglyphGamepadCamera, _super);
  80296. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80297. var _this = _super.call(this, name, position, scene) || this;
  80298. _this.interaxialDistance = interaxialDistance;
  80299. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80300. return _this;
  80301. }
  80302. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80303. return "AnaglyphGamepadCamera";
  80304. };
  80305. return AnaglyphGamepadCamera;
  80306. }(BABYLON.GamepadCamera));
  80307. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80308. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80309. __extends(AnaglyphUniversalCamera, _super);
  80310. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80311. var _this = _super.call(this, name, position, scene) || this;
  80312. _this.interaxialDistance = interaxialDistance;
  80313. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80314. return _this;
  80315. }
  80316. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80317. return "AnaglyphUniversalCamera";
  80318. };
  80319. return AnaglyphUniversalCamera;
  80320. }(BABYLON.UniversalCamera));
  80321. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80322. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80323. __extends(StereoscopicFreeCamera, _super);
  80324. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80325. var _this = _super.call(this, name, position, scene) || this;
  80326. _this.interaxialDistance = interaxialDistance;
  80327. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80328. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80329. return _this;
  80330. }
  80331. StereoscopicFreeCamera.prototype.getClassName = function () {
  80332. return "StereoscopicFreeCamera";
  80333. };
  80334. return StereoscopicFreeCamera;
  80335. }(BABYLON.FreeCamera));
  80336. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80337. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80338. __extends(StereoscopicArcRotateCamera, _super);
  80339. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80340. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80341. _this.interaxialDistance = interaxialDistance;
  80342. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80343. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80344. return _this;
  80345. }
  80346. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80347. return "StereoscopicArcRotateCamera";
  80348. };
  80349. return StereoscopicArcRotateCamera;
  80350. }(BABYLON.ArcRotateCamera));
  80351. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80352. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80353. __extends(StereoscopicGamepadCamera, _super);
  80354. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80355. var _this = _super.call(this, name, position, scene) || this;
  80356. _this.interaxialDistance = interaxialDistance;
  80357. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80358. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80359. return _this;
  80360. }
  80361. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80362. return "StereoscopicGamepadCamera";
  80363. };
  80364. return StereoscopicGamepadCamera;
  80365. }(BABYLON.GamepadCamera));
  80366. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80367. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80368. __extends(StereoscopicUniversalCamera, _super);
  80369. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80370. var _this = _super.call(this, name, position, scene) || this;
  80371. _this.interaxialDistance = interaxialDistance;
  80372. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80373. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80374. return _this;
  80375. }
  80376. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80377. return "StereoscopicUniversalCamera";
  80378. };
  80379. return StereoscopicUniversalCamera;
  80380. }(BABYLON.UniversalCamera));
  80381. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80382. })(BABYLON || (BABYLON = {}));
  80383. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80384. var BABYLON;
  80385. (function (BABYLON) {
  80386. var VRExperienceHelperGazer = /** @class */ (function () {
  80387. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80388. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80389. this.scene = scene;
  80390. this._pointerDownOnMeshAsked = false;
  80391. this._isActionableMesh = false;
  80392. this._teleportationRequestInitiated = false;
  80393. this._teleportationBackRequestInitiated = false;
  80394. this._dpadPressed = true;
  80395. this._activePointer = false;
  80396. this._id = VRExperienceHelperGazer._idCounter++;
  80397. // Gaze tracker
  80398. if (!gazeTrackerToClone) {
  80399. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80400. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80401. this._gazeTracker.isPickable = false;
  80402. this._gazeTracker.isVisible = false;
  80403. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80404. targetMat.specularColor = BABYLON.Color3.Black();
  80405. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80406. targetMat.backFaceCulling = false;
  80407. this._gazeTracker.material = targetMat;
  80408. }
  80409. else {
  80410. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80411. }
  80412. }
  80413. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80414. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80415. };
  80416. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80417. this._pointerDownOnMeshAsked = true;
  80418. if (this._currentMeshSelected && this._currentHit) {
  80419. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80420. }
  80421. };
  80422. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80423. if (this._currentMeshSelected && this._currentHit) {
  80424. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80425. }
  80426. this._pointerDownOnMeshAsked = false;
  80427. };
  80428. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80429. this._activePointer = true;
  80430. };
  80431. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80432. this._activePointer = false;
  80433. };
  80434. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80435. };
  80436. VRExperienceHelperGazer.prototype.dispose = function () {
  80437. this._interactionsEnabled = false;
  80438. this._teleportationEnabled = false;
  80439. };
  80440. VRExperienceHelperGazer._idCounter = 0;
  80441. return VRExperienceHelperGazer;
  80442. }());
  80443. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80444. __extends(VRExperienceHelperControllerGazer, _super);
  80445. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80446. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80447. _this.webVRController = webVRController;
  80448. // Laser pointer
  80449. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80450. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80451. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80452. laserPointerMaterial.alpha = 0.6;
  80453. _this._laserPointer.material = laserPointerMaterial;
  80454. _this._laserPointer.rotation.x = Math.PI / 2;
  80455. _this._laserPointer.position.z = -0.5;
  80456. _this._laserPointer.isVisible = false;
  80457. if (!webVRController.mesh) {
  80458. // Create an empty mesh that is used prior to loading the high quality model
  80459. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80460. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80461. preloadPointerPose.rotation.x = -0.7;
  80462. preloadMesh.addChild(preloadPointerPose);
  80463. webVRController.attachToMesh(preloadMesh);
  80464. }
  80465. _this._setLaserPointerParent(webVRController.mesh);
  80466. return _this;
  80467. }
  80468. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80469. return this.webVRController.getForwardRay(length);
  80470. };
  80471. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80472. _super.prototype._activatePointer.call(this);
  80473. this._laserPointer.isVisible = true;
  80474. };
  80475. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80476. _super.prototype._deactivatePointer.call(this);
  80477. this._laserPointer.isVisible = false;
  80478. };
  80479. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80480. this._laserPointer.material.emissiveColor = color;
  80481. };
  80482. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80483. var makeNotPick = function (root) {
  80484. root.name += " laserPointer";
  80485. root.getChildMeshes().forEach(function (c) {
  80486. makeNotPick(c);
  80487. });
  80488. };
  80489. makeNotPick(mesh);
  80490. var childMeshes = mesh.getChildMeshes();
  80491. this.webVRController._pointingPoseNode = null;
  80492. for (var i = 0; i < childMeshes.length; i++) {
  80493. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80494. mesh = childMeshes[i];
  80495. this.webVRController._pointingPoseNode = mesh;
  80496. break;
  80497. }
  80498. }
  80499. this._laserPointer.parent = mesh;
  80500. };
  80501. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80502. this._laserPointer.scaling.y = distance;
  80503. this._laserPointer.position.z = -distance / 2;
  80504. };
  80505. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80506. _super.prototype.dispose.call(this);
  80507. this._laserPointer.dispose();
  80508. };
  80509. return VRExperienceHelperControllerGazer;
  80510. }(VRExperienceHelperGazer));
  80511. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80512. __extends(VRExperienceHelperCameraGazer, _super);
  80513. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80514. var _this = _super.call(this, scene) || this;
  80515. _this.getCamera = getCamera;
  80516. return _this;
  80517. }
  80518. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80519. var camera = this.getCamera();
  80520. if (camera) {
  80521. return camera.getForwardRay(length);
  80522. }
  80523. else {
  80524. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80525. }
  80526. };
  80527. return VRExperienceHelperCameraGazer;
  80528. }(VRExperienceHelperGazer));
  80529. /**
  80530. * Helps to quickly add VR support to an existing scene.
  80531. * See http://doc.babylonjs.com/how_to/webvr_helper
  80532. */
  80533. var VRExperienceHelper = /** @class */ (function () {
  80534. /**
  80535. * Instantiates a VRExperienceHelper.
  80536. * Helps to quickly add VR support to an existing scene.
  80537. * @param scene The scene the VRExperienceHelper belongs to.
  80538. * @param webVROptions Options to modify the vr experience helper's behavior.
  80539. */
  80540. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80541. if (webVROptions === void 0) { webVROptions = {}; }
  80542. var _this = this;
  80543. this.webVROptions = webVROptions;
  80544. // Can the system support WebVR, even if a headset isn't plugged in?
  80545. this._webVRsupported = false;
  80546. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80547. this._webVRready = false;
  80548. // Are we waiting for the requestPresent callback to complete?
  80549. this._webVRrequesting = false;
  80550. // Are we presenting to the headset right now?
  80551. this._webVRpresenting = false;
  80552. // Are we presenting in the fullscreen fallback?
  80553. this._fullscreenVRpresenting = false;
  80554. /**
  80555. * Observable raised when entering VR.
  80556. */
  80557. this.onEnteringVRObservable = new BABYLON.Observable();
  80558. /**
  80559. * Observable raised when exiting VR.
  80560. */
  80561. this.onExitingVRObservable = new BABYLON.Observable();
  80562. /**
  80563. * Observable raised when controller mesh is loaded.
  80564. */
  80565. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80566. this._useCustomVRButton = false;
  80567. this._teleportationRequested = false;
  80568. this._teleportActive = false;
  80569. this._floorMeshesCollection = [];
  80570. this._rotationAllowed = true;
  80571. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80572. this._rotationRightAsked = false;
  80573. this._rotationLeftAsked = false;
  80574. this._isDefaultTeleportationTarget = true;
  80575. this._teleportationFillColor = "#444444";
  80576. this._teleportationBorderColor = "#FFFFFF";
  80577. this._rotationAngle = 0;
  80578. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80579. this._padSensibilityUp = 0.65;
  80580. this._padSensibilityDown = 0.35;
  80581. this.leftController = null;
  80582. this.rightController = null;
  80583. /**
  80584. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80585. */
  80586. this.onNewMeshSelected = new BABYLON.Observable();
  80587. /**
  80588. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80589. */
  80590. this.onNewMeshPicked = new BABYLON.Observable();
  80591. /**
  80592. * Observable raised before camera teleportation
  80593. */
  80594. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80595. /**
  80596. * Observable raised after camera teleportation
  80597. */
  80598. this.onAfterCameraTeleport = new BABYLON.Observable();
  80599. /**
  80600. * Observable raised when current selected mesh gets unselected
  80601. */
  80602. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80603. /**
  80604. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80605. */
  80606. this.teleportationEnabled = true;
  80607. this._teleportationInitialized = false;
  80608. this._interactionsEnabled = false;
  80609. this._interactionsRequested = false;
  80610. this._displayGaze = true;
  80611. this._displayLaserPointer = true;
  80612. this._onResize = function () {
  80613. _this.moveButtonToBottomRight();
  80614. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80615. _this.exitVR();
  80616. }
  80617. };
  80618. this._onFullscreenChange = function () {
  80619. if (document.fullscreen !== undefined) {
  80620. _this._fullscreenVRpresenting = document.fullscreen;
  80621. }
  80622. else if (document.mozFullScreen !== undefined) {
  80623. _this._fullscreenVRpresenting = document.mozFullScreen;
  80624. }
  80625. else if (document.webkitIsFullScreen !== undefined) {
  80626. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80627. }
  80628. else if (document.msIsFullScreen !== undefined) {
  80629. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80630. }
  80631. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80632. _this.exitVR();
  80633. if (!_this._useCustomVRButton) {
  80634. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80635. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80636. }
  80637. }
  80638. };
  80639. this.beforeRender = function () {
  80640. if (_this.leftController && _this.leftController._activePointer) {
  80641. _this._castRayAndSelectObject(_this.leftController);
  80642. }
  80643. if (_this.rightController && _this.rightController._activePointer) {
  80644. _this._castRayAndSelectObject(_this.rightController);
  80645. }
  80646. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80647. _this._castRayAndSelectObject(_this._cameraGazer);
  80648. }
  80649. else {
  80650. _this._cameraGazer._gazeTracker.isVisible = false;
  80651. }
  80652. };
  80653. this._onNewGamepadConnected = function (gamepad) {
  80654. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80655. if (gamepad.leftStick) {
  80656. gamepad.onleftstickchanged(function (stickValues) {
  80657. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80658. // Listening to classic/xbox gamepad only if no VR controller is active
  80659. if ((!_this.leftController && !_this.rightController) ||
  80660. ((_this.leftController && !_this.leftController._activePointer) &&
  80661. (_this.rightController && !_this.rightController._activePointer))) {
  80662. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80663. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80664. }
  80665. }
  80666. });
  80667. }
  80668. if (gamepad.rightStick) {
  80669. gamepad.onrightstickchanged(function (stickValues) {
  80670. if (_this._teleportationInitialized) {
  80671. _this._checkRotate(stickValues, _this._cameraGazer);
  80672. }
  80673. });
  80674. }
  80675. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80676. gamepad.onbuttondown(function (buttonPressed) {
  80677. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80678. _this._cameraGazer._selectionPointerDown();
  80679. }
  80680. });
  80681. gamepad.onbuttonup(function (buttonPressed) {
  80682. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80683. _this._cameraGazer._selectionPointerUp();
  80684. }
  80685. });
  80686. }
  80687. }
  80688. else {
  80689. var webVRController = gamepad;
  80690. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80691. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80692. _this.rightController = controller;
  80693. }
  80694. else {
  80695. _this.leftController = controller;
  80696. }
  80697. _this._tryEnableInteractionOnController(controller);
  80698. }
  80699. };
  80700. // 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
  80701. this._tryEnableInteractionOnController = function (controller) {
  80702. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80703. _this._enableInteractionOnController(controller);
  80704. }
  80705. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80706. _this._enableTeleportationOnController(controller);
  80707. }
  80708. };
  80709. this._onNewGamepadDisconnected = function (gamepad) {
  80710. if (gamepad instanceof BABYLON.WebVRController) {
  80711. if (gamepad.hand === "left" && _this.leftController != null) {
  80712. _this.leftController.dispose();
  80713. _this.leftController = null;
  80714. }
  80715. if (gamepad.hand === "right" && _this.rightController != null) {
  80716. _this.rightController.dispose();
  80717. _this.rightController = null;
  80718. }
  80719. }
  80720. };
  80721. this._workingVector = BABYLON.Vector3.Zero();
  80722. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80723. this._workingMatrix = BABYLON.Matrix.Identity();
  80724. this._scene = scene;
  80725. this._canvas = scene.getEngine().getRenderingCanvas();
  80726. // Parse options
  80727. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80728. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80729. }
  80730. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80731. webVROptions.createDeviceOrientationCamera = true;
  80732. }
  80733. if (webVROptions.defaultHeight === undefined) {
  80734. webVROptions.defaultHeight = 1.7;
  80735. }
  80736. if (webVROptions.useCustomVRButton) {
  80737. this._useCustomVRButton = true;
  80738. if (webVROptions.customVRButton) {
  80739. this._btnVR = webVROptions.customVRButton;
  80740. }
  80741. }
  80742. if (webVROptions.rayLength) {
  80743. this._rayLength = webVROptions.rayLength;
  80744. }
  80745. this._defaultHeight = webVROptions.defaultHeight;
  80746. if (webVROptions.positionScale) {
  80747. this._rayLength *= webVROptions.positionScale;
  80748. this._defaultHeight *= webVROptions.positionScale;
  80749. }
  80750. // Set position
  80751. if (this._scene.activeCamera) {
  80752. this._position = this._scene.activeCamera.position.clone();
  80753. }
  80754. else {
  80755. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80756. }
  80757. // Set non-vr camera
  80758. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80759. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80760. // Copy data from existing camera
  80761. if (this._scene.activeCamera) {
  80762. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80763. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80764. // Set rotation from previous camera
  80765. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80766. var targetCamera = this._scene.activeCamera;
  80767. if (targetCamera.rotationQuaternion) {
  80768. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80769. }
  80770. else {
  80771. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80772. }
  80773. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80774. }
  80775. }
  80776. this._scene.activeCamera = this._deviceOrientationCamera;
  80777. if (this._canvas) {
  80778. this._scene.activeCamera.attachControl(this._canvas);
  80779. }
  80780. }
  80781. else {
  80782. this._existingCamera = this._scene.activeCamera;
  80783. }
  80784. // Create VR cameras
  80785. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80786. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80787. }
  80788. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80789. this._webVRCamera.useStandingMatrix();
  80790. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80791. // Create default button
  80792. if (!this._useCustomVRButton) {
  80793. this._btnVR = document.createElement("BUTTON");
  80794. this._btnVR.className = "babylonVRicon";
  80795. this._btnVR.id = "babylonVRiconbtn";
  80796. this._btnVR.title = "Click to switch to VR";
  80797. 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) }";
  80798. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80799. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80800. // css += ".babylonVRicon.vrdisplaysupported { }";
  80801. // css += ".babylonVRicon.vrdisplayready { }";
  80802. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80803. var style = document.createElement('style');
  80804. style.appendChild(document.createTextNode(css));
  80805. document.getElementsByTagName('head')[0].appendChild(style);
  80806. this.moveButtonToBottomRight();
  80807. }
  80808. // VR button click event
  80809. if (this._btnVR) {
  80810. this._btnVR.addEventListener("click", function () {
  80811. if (!_this.isInVRMode) {
  80812. _this.enterVR();
  80813. }
  80814. else {
  80815. _this.exitVR();
  80816. }
  80817. });
  80818. }
  80819. // Window events
  80820. window.addEventListener("resize", this._onResize);
  80821. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80822. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80823. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80824. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80825. // Display vr button when headset is connected
  80826. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80827. this.displayVRButton();
  80828. }
  80829. else {
  80830. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80831. if (e.vrDisplay) {
  80832. _this.displayVRButton();
  80833. }
  80834. });
  80835. }
  80836. // Exiting VR mode using 'ESC' key on desktop
  80837. this._onKeyDown = function (event) {
  80838. if (event.keyCode === 27 && _this.isInVRMode) {
  80839. _this.exitVR();
  80840. }
  80841. };
  80842. document.addEventListener("keydown", this._onKeyDown);
  80843. // Exiting VR mode double tapping the touch screen
  80844. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80845. if (_this.isInVRMode) {
  80846. _this.exitVR();
  80847. if (_this._fullscreenVRpresenting) {
  80848. _this._scene.getEngine().switchFullscreen(true);
  80849. }
  80850. }
  80851. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80852. // Listen for WebVR display changes
  80853. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80854. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80855. this._onVRRequestPresentStart = function () {
  80856. _this._webVRrequesting = true;
  80857. _this.updateButtonVisibility();
  80858. };
  80859. this._onVRRequestPresentComplete = function (success) {
  80860. _this._webVRrequesting = false;
  80861. _this.updateButtonVisibility();
  80862. };
  80863. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80864. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80865. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80866. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80867. scene.onDisposeObservable.add(function () {
  80868. _this.dispose();
  80869. });
  80870. // Gamepad connection events
  80871. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80872. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80873. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80874. this.updateButtonVisibility();
  80875. //create easing functions
  80876. this._circleEase = new BABYLON.CircleEase();
  80877. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80878. }
  80879. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80880. /** Return this.onEnteringVRObservable
  80881. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80882. */
  80883. get: function () {
  80884. return this.onEnteringVRObservable;
  80885. },
  80886. enumerable: true,
  80887. configurable: true
  80888. });
  80889. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80890. /** Return this.onExitingVRObservable
  80891. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80892. */
  80893. get: function () {
  80894. return this.onExitingVRObservable;
  80895. },
  80896. enumerable: true,
  80897. configurable: true
  80898. });
  80899. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80900. /** Return this.onControllerMeshLoadedObservable
  80901. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80902. */
  80903. get: function () {
  80904. return this.onControllerMeshLoadedObservable;
  80905. },
  80906. enumerable: true,
  80907. configurable: true
  80908. });
  80909. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80910. /**
  80911. * The mesh used to display where the user is going to teleport.
  80912. */
  80913. get: function () {
  80914. return this._teleportationTarget;
  80915. },
  80916. /**
  80917. * Sets the mesh to be used to display where the user is going to teleport.
  80918. */
  80919. set: function (value) {
  80920. if (value) {
  80921. value.name = "teleportationTarget";
  80922. this._isDefaultTeleportationTarget = false;
  80923. this._teleportationTarget = value;
  80924. }
  80925. },
  80926. enumerable: true,
  80927. configurable: true
  80928. });
  80929. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80930. /**
  80931. * The mesh used to display where the user is selecting,
  80932. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80933. * See http://doc.babylonjs.com/resources/baking_transformations
  80934. */
  80935. get: function () {
  80936. return this._cameraGazer._gazeTracker;
  80937. },
  80938. set: function (value) {
  80939. if (value) {
  80940. this._cameraGazer._gazeTracker = value;
  80941. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80942. this._cameraGazer._gazeTracker.isPickable = false;
  80943. this._cameraGazer._gazeTracker.isVisible = false;
  80944. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80945. if (this.leftController) {
  80946. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80947. }
  80948. if (this.rightController) {
  80949. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80950. }
  80951. }
  80952. },
  80953. enumerable: true,
  80954. configurable: true
  80955. });
  80956. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80957. /**
  80958. * If the ray of the gaze should be displayed.
  80959. */
  80960. get: function () {
  80961. return this._displayGaze;
  80962. },
  80963. /**
  80964. * Sets if the ray of the gaze should be displayed.
  80965. */
  80966. set: function (value) {
  80967. this._displayGaze = value;
  80968. if (!value) {
  80969. this._cameraGazer._gazeTracker.isVisible = false;
  80970. if (this.leftController) {
  80971. this.leftController._gazeTracker.isVisible = false;
  80972. }
  80973. if (this.rightController) {
  80974. this.rightController._gazeTracker.isVisible = false;
  80975. }
  80976. }
  80977. },
  80978. enumerable: true,
  80979. configurable: true
  80980. });
  80981. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80982. /**
  80983. * If the ray of the LaserPointer should be displayed.
  80984. */
  80985. get: function () {
  80986. return this._displayLaserPointer;
  80987. },
  80988. /**
  80989. * Sets if the ray of the LaserPointer should be displayed.
  80990. */
  80991. set: function (value) {
  80992. this._displayLaserPointer = value;
  80993. if (!value) {
  80994. if (this.rightController) {
  80995. this.rightController._deactivatePointer();
  80996. this.rightController._gazeTracker.isVisible = false;
  80997. }
  80998. if (this.leftController) {
  80999. this.leftController._deactivatePointer();
  81000. this.leftController._gazeTracker.isVisible = false;
  81001. }
  81002. }
  81003. else {
  81004. if (this.rightController) {
  81005. this.rightController._activatePointer();
  81006. }
  81007. else if (this.leftController) {
  81008. this.leftController._activatePointer();
  81009. }
  81010. }
  81011. },
  81012. enumerable: true,
  81013. configurable: true
  81014. });
  81015. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81016. /**
  81017. * The deviceOrientationCamera used as the camera when not in VR.
  81018. */
  81019. get: function () {
  81020. return this._deviceOrientationCamera;
  81021. },
  81022. enumerable: true,
  81023. configurable: true
  81024. });
  81025. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81026. /**
  81027. * Based on the current WebVR support, returns the current VR camera used.
  81028. */
  81029. get: function () {
  81030. if (this._webVRready) {
  81031. return this._webVRCamera;
  81032. }
  81033. else {
  81034. return this._scene.activeCamera;
  81035. }
  81036. },
  81037. enumerable: true,
  81038. configurable: true
  81039. });
  81040. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81041. /**
  81042. * The webVRCamera which is used when in VR.
  81043. */
  81044. get: function () {
  81045. return this._webVRCamera;
  81046. },
  81047. enumerable: true,
  81048. configurable: true
  81049. });
  81050. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81051. /**
  81052. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81053. */
  81054. get: function () {
  81055. return this._vrDeviceOrientationCamera;
  81056. },
  81057. enumerable: true,
  81058. configurable: true
  81059. });
  81060. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81061. get: function () {
  81062. var result = this._cameraGazer._teleportationRequestInitiated
  81063. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81064. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81065. return result;
  81066. },
  81067. enumerable: true,
  81068. configurable: true
  81069. });
  81070. // Raised when one of the controller has loaded successfully its associated default mesh
  81071. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81072. if (this.leftController && this.leftController.webVRController == webVRController) {
  81073. if (webVRController.mesh) {
  81074. this.leftController._setLaserPointerParent(webVRController.mesh);
  81075. }
  81076. }
  81077. if (this.rightController && this.rightController.webVRController == webVRController) {
  81078. if (webVRController.mesh) {
  81079. this.rightController._setLaserPointerParent(webVRController.mesh);
  81080. }
  81081. }
  81082. try {
  81083. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81084. }
  81085. catch (err) {
  81086. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81087. }
  81088. };
  81089. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81090. /**
  81091. * Gets a value indicating if we are currently in VR mode.
  81092. */
  81093. get: function () {
  81094. return this._webVRpresenting || this._fullscreenVRpresenting;
  81095. },
  81096. enumerable: true,
  81097. configurable: true
  81098. });
  81099. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81100. var vrDisplay = this._scene.getEngine().getVRDevice();
  81101. if (vrDisplay) {
  81102. var wasPresenting = this._webVRpresenting;
  81103. // A VR display is connected
  81104. this._webVRpresenting = vrDisplay.isPresenting;
  81105. if (wasPresenting && !this._webVRpresenting)
  81106. this.exitVR();
  81107. }
  81108. else {
  81109. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81110. }
  81111. this.updateButtonVisibility();
  81112. };
  81113. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81114. this._webVRsupported = eventArgs.vrSupported;
  81115. this._webVRready = !!eventArgs.vrDisplay;
  81116. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81117. this.updateButtonVisibility();
  81118. };
  81119. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81120. if (this._canvas && !this._useCustomVRButton) {
  81121. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81122. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81123. }
  81124. };
  81125. VRExperienceHelper.prototype.displayVRButton = function () {
  81126. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81127. document.body.appendChild(this._btnVR);
  81128. this._btnVRDisplayed = true;
  81129. }
  81130. };
  81131. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81132. if (!this._btnVR || this._useCustomVRButton) {
  81133. return;
  81134. }
  81135. this._btnVR.className = "babylonVRicon";
  81136. if (this.isInVRMode) {
  81137. this._btnVR.className += " vrdisplaypresenting";
  81138. }
  81139. else {
  81140. if (this._webVRready)
  81141. this._btnVR.className += " vrdisplayready";
  81142. if (this._webVRsupported)
  81143. this._btnVR.className += " vrdisplaysupported";
  81144. if (this._webVRrequesting)
  81145. this._btnVR.className += " vrdisplayrequesting";
  81146. }
  81147. };
  81148. /**
  81149. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81150. * Otherwise, will use the fullscreen API.
  81151. */
  81152. VRExperienceHelper.prototype.enterVR = function () {
  81153. if (this.onEnteringVRObservable) {
  81154. try {
  81155. this.onEnteringVRObservable.notifyObservers(this);
  81156. }
  81157. catch (err) {
  81158. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81159. }
  81160. }
  81161. if (this._scene.activeCamera) {
  81162. this._position = this._scene.activeCamera.position.clone();
  81163. // make sure that we return to the last active camera
  81164. this._existingCamera = this._scene.activeCamera;
  81165. }
  81166. if (this._webVRrequesting)
  81167. return;
  81168. // If WebVR is supported and a headset is connected
  81169. if (this._webVRready) {
  81170. if (!this._webVRpresenting) {
  81171. this._webVRCamera.position = this._position;
  81172. this._scene.activeCamera = this._webVRCamera;
  81173. }
  81174. }
  81175. else if (this._vrDeviceOrientationCamera) {
  81176. this._vrDeviceOrientationCamera.position = this._position;
  81177. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81178. this._scene.getEngine().switchFullscreen(true);
  81179. this.updateButtonVisibility();
  81180. }
  81181. if (this._scene.activeCamera && this._canvas) {
  81182. this._scene.activeCamera.attachControl(this._canvas);
  81183. }
  81184. if (this._interactionsEnabled) {
  81185. this._scene.registerBeforeRender(this.beforeRender);
  81186. }
  81187. };
  81188. /**
  81189. * Attempt to exit VR, or fullscreen.
  81190. */
  81191. VRExperienceHelper.prototype.exitVR = function () {
  81192. if (this.onExitingVRObservable) {
  81193. try {
  81194. this.onExitingVRObservable.notifyObservers(this);
  81195. }
  81196. catch (err) {
  81197. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81198. }
  81199. }
  81200. if (this._webVRpresenting) {
  81201. this._scene.getEngine().disableVR();
  81202. }
  81203. if (this._scene.activeCamera) {
  81204. this._position = this._scene.activeCamera.position.clone();
  81205. }
  81206. if (this._deviceOrientationCamera) {
  81207. this._deviceOrientationCamera.position = this._position;
  81208. this._scene.activeCamera = this._deviceOrientationCamera;
  81209. if (this._canvas) {
  81210. this._scene.activeCamera.attachControl(this._canvas);
  81211. }
  81212. }
  81213. else if (this._existingCamera) {
  81214. this._existingCamera.position = this._position;
  81215. this._scene.activeCamera = this._existingCamera;
  81216. }
  81217. this.updateButtonVisibility();
  81218. if (this._interactionsEnabled) {
  81219. this._scene.unregisterBeforeRender(this.beforeRender);
  81220. }
  81221. };
  81222. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81223. /**
  81224. * The position of the vr experience helper.
  81225. */
  81226. get: function () {
  81227. return this._position;
  81228. },
  81229. /**
  81230. * Sets the position of the vr experience helper.
  81231. */
  81232. set: function (value) {
  81233. this._position = value;
  81234. if (this._scene.activeCamera) {
  81235. this._scene.activeCamera.position = value;
  81236. }
  81237. },
  81238. enumerable: true,
  81239. configurable: true
  81240. });
  81241. /**
  81242. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81243. */
  81244. VRExperienceHelper.prototype.enableInteractions = function () {
  81245. var _this = this;
  81246. if (!this._interactionsEnabled) {
  81247. this._interactionsRequested = true;
  81248. if (this.leftController) {
  81249. this._enableInteractionOnController(this.leftController);
  81250. }
  81251. if (this.rightController) {
  81252. this._enableInteractionOnController(this.rightController);
  81253. }
  81254. this.raySelectionPredicate = function (mesh) {
  81255. return mesh.isVisible;
  81256. };
  81257. this.meshSelectionPredicate = function (mesh) {
  81258. return true;
  81259. };
  81260. this._raySelectionPredicate = function (mesh) {
  81261. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81262. && mesh.name.indexOf("teleportationTarget") === -1
  81263. && mesh.name.indexOf("torusTeleportation") === -1
  81264. && mesh.name.indexOf("laserPointer") === -1)) {
  81265. return _this.raySelectionPredicate(mesh);
  81266. }
  81267. return false;
  81268. };
  81269. this._interactionsEnabled = true;
  81270. }
  81271. };
  81272. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81273. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81274. if (this._floorMeshesCollection[i].id === mesh.id) {
  81275. return true;
  81276. }
  81277. }
  81278. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81279. return true;
  81280. }
  81281. return false;
  81282. };
  81283. /**
  81284. * Adds a floor mesh to be used for teleportation.
  81285. * @param floorMesh the mesh to be used for teleportation.
  81286. */
  81287. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81288. if (!this._floorMeshesCollection) {
  81289. return;
  81290. }
  81291. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81292. return;
  81293. }
  81294. this._floorMeshesCollection.push(floorMesh);
  81295. };
  81296. /**
  81297. * Removes a floor mesh from being used for teleportation.
  81298. * @param floorMesh the mesh to be removed.
  81299. */
  81300. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81301. if (!this._floorMeshesCollection) {
  81302. return;
  81303. }
  81304. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81305. if (meshIndex !== -1) {
  81306. this._floorMeshesCollection.splice(meshIndex, 1);
  81307. }
  81308. };
  81309. /**
  81310. * Enables interactions and teleportation using the VR controllers and gaze.
  81311. * @param vrTeleportationOptions options to modify teleportation behavior.
  81312. */
  81313. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81314. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81315. if (!this._teleportationInitialized) {
  81316. this._teleportationRequested = true;
  81317. this.enableInteractions();
  81318. if (vrTeleportationOptions.floorMeshName) {
  81319. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81320. }
  81321. if (vrTeleportationOptions.floorMeshes) {
  81322. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81323. }
  81324. if (this.leftController != null) {
  81325. this._enableTeleportationOnController(this.leftController);
  81326. }
  81327. if (this.rightController != null) {
  81328. this._enableTeleportationOnController(this.rightController);
  81329. }
  81330. // Creates an image processing post process for the vignette not relying
  81331. // on the main scene configuration for image processing to reduce setup and spaces
  81332. // (gamma/linear) conflicts.
  81333. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81334. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81335. imageProcessingConfiguration.vignetteEnabled = true;
  81336. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81337. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81338. this._teleportationInitialized = true;
  81339. if (this._isDefaultTeleportationTarget) {
  81340. this._createTeleportationCircles();
  81341. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81342. }
  81343. }
  81344. };
  81345. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81346. var _this = this;
  81347. var controllerMesh = controller.webVRController.mesh;
  81348. if (controllerMesh) {
  81349. controller._interactionsEnabled = true;
  81350. controller._activatePointer();
  81351. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81352. // Enabling / disabling laserPointer
  81353. if (_this._displayLaserPointer && stateObject.value === 1) {
  81354. if (controller._activePointer) {
  81355. controller._deactivatePointer();
  81356. }
  81357. else {
  81358. controller._activatePointer();
  81359. }
  81360. if (_this.displayGaze) {
  81361. controller._gazeTracker.isVisible = controller._activePointer;
  81362. }
  81363. }
  81364. });
  81365. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81366. if (!controller._pointerDownOnMeshAsked) {
  81367. if (stateObject.value > _this._padSensibilityUp) {
  81368. controller._selectionPointerDown();
  81369. }
  81370. }
  81371. else if (stateObject.value < _this._padSensibilityDown) {
  81372. controller._selectionPointerUp();
  81373. }
  81374. });
  81375. }
  81376. };
  81377. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81378. // Dont teleport if another gaze already requested teleportation
  81379. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81380. return;
  81381. }
  81382. if (!gazer._teleportationRequestInitiated) {
  81383. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81384. gazer._activatePointer();
  81385. gazer._teleportationRequestInitiated = true;
  81386. }
  81387. }
  81388. else {
  81389. // Listening to the proper controller values changes to confirm teleportation
  81390. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81391. if (this._teleportActive) {
  81392. this._teleportCamera(this._haloCenter);
  81393. }
  81394. gazer._teleportationRequestInitiated = false;
  81395. }
  81396. }
  81397. };
  81398. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81399. // Only rotate when user is not currently selecting a teleportation location
  81400. if (gazer._teleportationRequestInitiated) {
  81401. return;
  81402. }
  81403. if (!this._rotationLeftAsked) {
  81404. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81405. this._rotationLeftAsked = true;
  81406. if (this._rotationAllowed) {
  81407. this._rotateCamera(false);
  81408. }
  81409. }
  81410. }
  81411. else {
  81412. if (stateObject.x > -this._padSensibilityDown) {
  81413. this._rotationLeftAsked = false;
  81414. }
  81415. }
  81416. if (!this._rotationRightAsked) {
  81417. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81418. this._rotationRightAsked = true;
  81419. if (this._rotationAllowed) {
  81420. this._rotateCamera(true);
  81421. }
  81422. }
  81423. }
  81424. else {
  81425. if (stateObject.x < this._padSensibilityDown) {
  81426. this._rotationRightAsked = false;
  81427. }
  81428. }
  81429. };
  81430. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81431. // Only teleport backwards when user is not currently selecting a teleportation location
  81432. if (gazer._teleportationRequestInitiated) {
  81433. return;
  81434. }
  81435. // Teleport backwards
  81436. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81437. if (!gazer._teleportationBackRequestInitiated) {
  81438. if (!this.currentVRCamera) {
  81439. return;
  81440. }
  81441. // Get rotation and position of the current camera
  81442. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81443. var position = this.currentVRCamera.position;
  81444. // If the camera has device position, use that instead
  81445. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81446. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81447. position = this.currentVRCamera.devicePosition;
  81448. }
  81449. // Get matrix with only the y rotation of the device rotation
  81450. rotation.toEulerAnglesToRef(this._workingVector);
  81451. this._workingVector.z = 0;
  81452. this._workingVector.x = 0;
  81453. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81454. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81455. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81456. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81457. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81458. var ray = new BABYLON.Ray(position, this._workingVector);
  81459. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81460. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81461. this._teleportCamera(hit.pickedPoint);
  81462. }
  81463. gazer._teleportationBackRequestInitiated = true;
  81464. }
  81465. }
  81466. else {
  81467. gazer._teleportationBackRequestInitiated = false;
  81468. }
  81469. };
  81470. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81471. var _this = this;
  81472. var controllerMesh = controller.webVRController.mesh;
  81473. if (controllerMesh) {
  81474. if (!controller._interactionsEnabled) {
  81475. this._enableInteractionOnController(controller);
  81476. }
  81477. controller._interactionsEnabled = true;
  81478. controller._teleportationEnabled = true;
  81479. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81480. controller._dpadPressed = false;
  81481. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81482. controller._dpadPressed = stateObject.pressed;
  81483. if (!controller._dpadPressed) {
  81484. _this._rotationLeftAsked = false;
  81485. _this._rotationRightAsked = false;
  81486. controller._teleportationBackRequestInitiated = false;
  81487. }
  81488. });
  81489. }
  81490. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81491. if (_this.teleportationEnabled) {
  81492. _this._checkTeleportBackwards(stateObject, controller);
  81493. _this._checkTeleportWithRay(stateObject, controller);
  81494. }
  81495. _this._checkRotate(stateObject, controller);
  81496. });
  81497. }
  81498. };
  81499. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81500. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81501. this._teleportationTarget.isPickable = false;
  81502. var length = 512;
  81503. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81504. dynamicTexture.hasAlpha = true;
  81505. var context = dynamicTexture.getContext();
  81506. var centerX = length / 2;
  81507. var centerY = length / 2;
  81508. var radius = 200;
  81509. context.beginPath();
  81510. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81511. context.fillStyle = this._teleportationFillColor;
  81512. context.fill();
  81513. context.lineWidth = 10;
  81514. context.strokeStyle = this._teleportationBorderColor;
  81515. context.stroke();
  81516. context.closePath();
  81517. dynamicTexture.update();
  81518. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81519. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81520. this._teleportationTarget.material = teleportationCircleMaterial;
  81521. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81522. torus.isPickable = false;
  81523. torus.parent = this._teleportationTarget;
  81524. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81525. var keys = [];
  81526. keys.push({
  81527. frame: 0,
  81528. value: 0
  81529. });
  81530. keys.push({
  81531. frame: 30,
  81532. value: 0.4
  81533. });
  81534. keys.push({
  81535. frame: 60,
  81536. value: 0
  81537. });
  81538. animationInnerCircle.setKeys(keys);
  81539. var easingFunction = new BABYLON.SineEase();
  81540. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81541. animationInnerCircle.setEasingFunction(easingFunction);
  81542. torus.animations = [];
  81543. torus.animations.push(animationInnerCircle);
  81544. this._scene.beginAnimation(torus, 0, 60, true);
  81545. this._hideTeleportationTarget();
  81546. };
  81547. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81548. this._teleportActive = true;
  81549. if (this._teleportationInitialized) {
  81550. this._teleportationTarget.isVisible = true;
  81551. if (this._isDefaultTeleportationTarget) {
  81552. this._teleportationTarget.getChildren()[0].isVisible = true;
  81553. }
  81554. }
  81555. };
  81556. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81557. this._teleportActive = false;
  81558. if (this._teleportationInitialized) {
  81559. this._teleportationTarget.isVisible = false;
  81560. if (this._isDefaultTeleportationTarget) {
  81561. this._teleportationTarget.getChildren()[0].isVisible = false;
  81562. }
  81563. }
  81564. };
  81565. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81566. var _this = this;
  81567. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81568. return;
  81569. }
  81570. if (right) {
  81571. this._rotationAngle++;
  81572. }
  81573. else {
  81574. this._rotationAngle--;
  81575. }
  81576. this.currentVRCamera.animations = [];
  81577. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81578. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81579. var animationRotationKeys = [];
  81580. animationRotationKeys.push({
  81581. frame: 0,
  81582. value: this.currentVRCamera.rotationQuaternion
  81583. });
  81584. animationRotationKeys.push({
  81585. frame: 6,
  81586. value: target
  81587. });
  81588. animationRotation.setKeys(animationRotationKeys);
  81589. animationRotation.setEasingFunction(this._circleEase);
  81590. this.currentVRCamera.animations.push(animationRotation);
  81591. this._postProcessMove.animations = [];
  81592. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81593. var vignetteWeightKeys = [];
  81594. vignetteWeightKeys.push({
  81595. frame: 0,
  81596. value: 0
  81597. });
  81598. vignetteWeightKeys.push({
  81599. frame: 3,
  81600. value: 4
  81601. });
  81602. vignetteWeightKeys.push({
  81603. frame: 6,
  81604. value: 0
  81605. });
  81606. animationPP.setKeys(vignetteWeightKeys);
  81607. animationPP.setEasingFunction(this._circleEase);
  81608. this._postProcessMove.animations.push(animationPP);
  81609. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81610. var vignetteStretchKeys = [];
  81611. vignetteStretchKeys.push({
  81612. frame: 0,
  81613. value: 0
  81614. });
  81615. vignetteStretchKeys.push({
  81616. frame: 3,
  81617. value: 10
  81618. });
  81619. vignetteStretchKeys.push({
  81620. frame: 6,
  81621. value: 0
  81622. });
  81623. animationPP2.setKeys(vignetteStretchKeys);
  81624. animationPP2.setEasingFunction(this._circleEase);
  81625. this._postProcessMove.animations.push(animationPP2);
  81626. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81627. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81628. this._postProcessMove.samples = 4;
  81629. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81630. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81631. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81632. });
  81633. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81634. };
  81635. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81636. if (hit.pickedPoint) {
  81637. if (gazer._teleportationRequestInitiated) {
  81638. this._displayTeleportationTarget();
  81639. this._haloCenter.copyFrom(hit.pickedPoint);
  81640. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81641. }
  81642. var pickNormal = hit.getNormal(true, false);
  81643. if (pickNormal) {
  81644. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81645. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81646. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81647. }
  81648. this._teleportationTarget.position.y += 0.1;
  81649. }
  81650. };
  81651. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81652. var _this = this;
  81653. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81654. return;
  81655. }
  81656. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81657. // offset of the headset from the anchor.
  81658. if (this.webVRCamera.leftCamera) {
  81659. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81660. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81661. location.subtractToRef(this._workingVector, this._workingVector);
  81662. }
  81663. else {
  81664. this._workingVector.copyFrom(location);
  81665. }
  81666. // Add height to account for user's height offset
  81667. if (this.isInVRMode) {
  81668. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81669. }
  81670. else {
  81671. this._workingVector.y += this._defaultHeight;
  81672. }
  81673. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81674. // Create animation from the camera's position to the new location
  81675. this.currentVRCamera.animations = [];
  81676. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81677. var animationCameraTeleportationKeys = [{
  81678. frame: 0,
  81679. value: this.currentVRCamera.position
  81680. },
  81681. {
  81682. frame: 11,
  81683. value: this._workingVector
  81684. }
  81685. ];
  81686. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81687. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81688. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81689. this._postProcessMove.animations = [];
  81690. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81691. var vignetteWeightKeys = [];
  81692. vignetteWeightKeys.push({
  81693. frame: 0,
  81694. value: 0
  81695. });
  81696. vignetteWeightKeys.push({
  81697. frame: 5,
  81698. value: 8
  81699. });
  81700. vignetteWeightKeys.push({
  81701. frame: 11,
  81702. value: 0
  81703. });
  81704. animationPP.setKeys(vignetteWeightKeys);
  81705. this._postProcessMove.animations.push(animationPP);
  81706. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81707. var vignetteStretchKeys = [];
  81708. vignetteStretchKeys.push({
  81709. frame: 0,
  81710. value: 0
  81711. });
  81712. vignetteStretchKeys.push({
  81713. frame: 5,
  81714. value: 10
  81715. });
  81716. vignetteStretchKeys.push({
  81717. frame: 11,
  81718. value: 0
  81719. });
  81720. animationPP2.setKeys(vignetteStretchKeys);
  81721. this._postProcessMove.animations.push(animationPP2);
  81722. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81723. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81724. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81725. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81726. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81727. });
  81728. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81729. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81730. });
  81731. this._hideTeleportationTarget();
  81732. };
  81733. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81734. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81735. return;
  81736. }
  81737. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81738. // Moving the gazeTracker on the mesh face targetted
  81739. if (hit && hit.pickedPoint) {
  81740. if (this._displayGaze) {
  81741. var multiplier = 1;
  81742. gazer._gazeTracker.isVisible = true;
  81743. if (gazer._isActionableMesh) {
  81744. multiplier = 3;
  81745. }
  81746. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81747. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81748. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81749. var pickNormal = hit.getNormal();
  81750. // To avoid z-fighting
  81751. var deltaFighting = 0.002;
  81752. if (pickNormal) {
  81753. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81754. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81755. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81756. }
  81757. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81758. if (gazer._gazeTracker.position.x < 0) {
  81759. gazer._gazeTracker.position.x += deltaFighting;
  81760. }
  81761. else {
  81762. gazer._gazeTracker.position.x -= deltaFighting;
  81763. }
  81764. if (gazer._gazeTracker.position.y < 0) {
  81765. gazer._gazeTracker.position.y += deltaFighting;
  81766. }
  81767. else {
  81768. gazer._gazeTracker.position.y -= deltaFighting;
  81769. }
  81770. if (gazer._gazeTracker.position.z < 0) {
  81771. gazer._gazeTracker.position.z += deltaFighting;
  81772. }
  81773. else {
  81774. gazer._gazeTracker.position.z -= deltaFighting;
  81775. }
  81776. }
  81777. // Changing the size of the laser pointer based on the distance from the targetted point
  81778. gazer._updatePointerDistance(hit.distance);
  81779. }
  81780. else {
  81781. gazer._gazeTracker.isVisible = false;
  81782. }
  81783. if (hit && hit.pickedMesh) {
  81784. gazer._currentHit = hit;
  81785. if (gazer._pointerDownOnMeshAsked) {
  81786. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81787. }
  81788. // The object selected is the floor, we're in a teleportation scenario
  81789. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81790. // Moving the teleportation area to this targetted point
  81791. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81792. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81793. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81794. }
  81795. gazer._currentMeshSelected = null;
  81796. if (gazer._teleportationRequestInitiated) {
  81797. this._moveTeleportationSelectorTo(hit, gazer);
  81798. }
  81799. return;
  81800. }
  81801. // If not, we're in a selection scenario
  81802. //this._teleportationAllowed = false;
  81803. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81804. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81805. this.onNewMeshPicked.notifyObservers(hit);
  81806. gazer._currentMeshSelected = hit.pickedMesh;
  81807. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81808. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81809. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81810. gazer._isActionableMesh = true;
  81811. }
  81812. else {
  81813. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81814. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81815. gazer._isActionableMesh = false;
  81816. }
  81817. try {
  81818. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81819. }
  81820. catch (err) {
  81821. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81822. }
  81823. }
  81824. else {
  81825. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81826. gazer._currentMeshSelected = null;
  81827. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81828. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81829. }
  81830. }
  81831. }
  81832. else {
  81833. gazer._currentHit = null;
  81834. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81835. gazer._currentMeshSelected = null;
  81836. //this._teleportationAllowed = false;
  81837. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81838. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81839. }
  81840. };
  81841. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81842. if (mesh) {
  81843. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81844. }
  81845. };
  81846. /**
  81847. * Sets the color of the laser ray from the vr controllers.
  81848. * @param color new color for the ray.
  81849. */
  81850. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81851. if (this.leftController) {
  81852. this.leftController._setLaserPointerColor(color);
  81853. }
  81854. if (this.rightController) {
  81855. this.rightController._setLaserPointerColor(color);
  81856. }
  81857. };
  81858. /**
  81859. * Sets the color of the ray from the vr headsets gaze.
  81860. * @param color new color for the ray.
  81861. */
  81862. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81863. if (!this._cameraGazer._gazeTracker.material) {
  81864. return;
  81865. }
  81866. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81867. if (this.leftController) {
  81868. this.leftController._gazeTracker.material.emissiveColor = color;
  81869. }
  81870. if (this.rightController) {
  81871. this.rightController._gazeTracker.material.emissiveColor = color;
  81872. }
  81873. };
  81874. /**
  81875. * Exits VR and disposes of the vr experience helper
  81876. */
  81877. VRExperienceHelper.prototype.dispose = function () {
  81878. if (this.isInVRMode) {
  81879. this.exitVR();
  81880. }
  81881. if (this._postProcessMove) {
  81882. this._postProcessMove.dispose();
  81883. }
  81884. if (this._webVRCamera) {
  81885. this._webVRCamera.dispose();
  81886. }
  81887. if (this._vrDeviceOrientationCamera) {
  81888. this._vrDeviceOrientationCamera.dispose();
  81889. }
  81890. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81891. document.body.removeChild(this._btnVR);
  81892. }
  81893. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81894. this._deviceOrientationCamera.dispose();
  81895. }
  81896. if (this._cameraGazer) {
  81897. this._cameraGazer.dispose();
  81898. }
  81899. if (this.leftController) {
  81900. this.leftController.dispose();
  81901. }
  81902. if (this.rightController) {
  81903. this.rightController.dispose();
  81904. }
  81905. if (this._teleportationTarget) {
  81906. this._teleportationTarget.dispose();
  81907. }
  81908. this._floorMeshesCollection = [];
  81909. document.removeEventListener("keydown", this._onKeyDown);
  81910. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81911. window.removeEventListener("resize", this._onResize);
  81912. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81913. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81914. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81915. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81916. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81917. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81918. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81919. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81920. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81921. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81922. this._scene.unregisterBeforeRender(this.beforeRender);
  81923. };
  81924. /**
  81925. * Gets the name of the VRExperienceHelper class
  81926. * @returns "VRExperienceHelper"
  81927. */
  81928. VRExperienceHelper.prototype.getClassName = function () {
  81929. return "VRExperienceHelper";
  81930. };
  81931. return VRExperienceHelper;
  81932. }());
  81933. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81934. })(BABYLON || (BABYLON = {}));
  81935. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81936. // Mainly based on these 2 articles :
  81937. // 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
  81938. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81939. var BABYLON;
  81940. (function (BABYLON) {
  81941. var JoystickAxis;
  81942. (function (JoystickAxis) {
  81943. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81944. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81945. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81946. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81947. var VirtualJoystick = /** @class */ (function () {
  81948. function VirtualJoystick(leftJoystick) {
  81949. var _this = this;
  81950. if (leftJoystick) {
  81951. this._leftJoystick = true;
  81952. }
  81953. else {
  81954. this._leftJoystick = false;
  81955. }
  81956. VirtualJoystick._globalJoystickIndex++;
  81957. // By default left & right arrow keys are moving the X
  81958. // and up & down keys are moving the Y
  81959. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81960. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81961. this.reverseLeftRight = false;
  81962. this.reverseUpDown = false;
  81963. // collections of pointers
  81964. this._touches = new BABYLON.StringDictionary();
  81965. this.deltaPosition = BABYLON.Vector3.Zero();
  81966. this._joystickSensibility = 25;
  81967. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81968. this._onResize = function (evt) {
  81969. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81970. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81971. if (VirtualJoystick.vjCanvas) {
  81972. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81973. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81974. }
  81975. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81976. };
  81977. // injecting a canvas element on top of the canvas 3D game
  81978. if (!VirtualJoystick.vjCanvas) {
  81979. window.addEventListener("resize", this._onResize, false);
  81980. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81981. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81982. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81983. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81984. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81985. VirtualJoystick.vjCanvas.style.width = "100%";
  81986. VirtualJoystick.vjCanvas.style.height = "100%";
  81987. VirtualJoystick.vjCanvas.style.position = "absolute";
  81988. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81989. VirtualJoystick.vjCanvas.style.top = "0px";
  81990. VirtualJoystick.vjCanvas.style.left = "0px";
  81991. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81992. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81993. // Support for jQuery PEP polyfill
  81994. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81995. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81996. if (!context) {
  81997. throw new Error("Unable to create canvas for virtual joystick");
  81998. }
  81999. VirtualJoystick.vjCanvasContext = context;
  82000. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82001. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82002. document.body.appendChild(VirtualJoystick.vjCanvas);
  82003. }
  82004. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82005. this.pressed = false;
  82006. // default joystick color
  82007. this._joystickColor = "cyan";
  82008. this._joystickPointerID = -1;
  82009. // current joystick position
  82010. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82011. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82012. // origin joystick position
  82013. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82014. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82015. this._onPointerDownHandlerRef = function (evt) {
  82016. _this._onPointerDown(evt);
  82017. };
  82018. this._onPointerMoveHandlerRef = function (evt) {
  82019. _this._onPointerMove(evt);
  82020. };
  82021. this._onPointerUpHandlerRef = function (evt) {
  82022. _this._onPointerUp(evt);
  82023. };
  82024. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82025. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82026. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82027. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82028. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82029. evt.preventDefault(); // Disables system menu
  82030. }, false);
  82031. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82032. }
  82033. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82034. this._joystickSensibility = newJoystickSensibility;
  82035. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82036. };
  82037. VirtualJoystick.prototype._onPointerDown = function (e) {
  82038. var positionOnScreenCondition;
  82039. e.preventDefault();
  82040. if (this._leftJoystick === true) {
  82041. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82042. }
  82043. else {
  82044. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82045. }
  82046. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82047. // First contact will be dedicated to the virtual joystick
  82048. this._joystickPointerID = e.pointerId;
  82049. this._joystickPointerStartPos.x = e.clientX;
  82050. this._joystickPointerStartPos.y = e.clientY;
  82051. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82052. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82053. this._deltaJoystickVector.x = 0;
  82054. this._deltaJoystickVector.y = 0;
  82055. this.pressed = true;
  82056. this._touches.add(e.pointerId.toString(), e);
  82057. }
  82058. else {
  82059. // You can only trigger the action buttons with a joystick declared
  82060. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82061. this._action();
  82062. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82063. }
  82064. }
  82065. };
  82066. VirtualJoystick.prototype._onPointerMove = function (e) {
  82067. // If the current pointer is the one associated to the joystick (first touch contact)
  82068. if (this._joystickPointerID == e.pointerId) {
  82069. this._joystickPointerPos.x = e.clientX;
  82070. this._joystickPointerPos.y = e.clientY;
  82071. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82072. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82073. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82074. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82075. switch (this._axisTargetedByLeftAndRight) {
  82076. case JoystickAxis.X:
  82077. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82078. break;
  82079. case JoystickAxis.Y:
  82080. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82081. break;
  82082. case JoystickAxis.Z:
  82083. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82084. break;
  82085. }
  82086. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82087. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82088. switch (this._axisTargetedByUpAndDown) {
  82089. case JoystickAxis.X:
  82090. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82091. break;
  82092. case JoystickAxis.Y:
  82093. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82094. break;
  82095. case JoystickAxis.Z:
  82096. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82097. break;
  82098. }
  82099. }
  82100. else {
  82101. var data = this._touches.get(e.pointerId.toString());
  82102. if (data) {
  82103. data.x = e.clientX;
  82104. data.y = e.clientY;
  82105. }
  82106. }
  82107. };
  82108. VirtualJoystick.prototype._onPointerUp = function (e) {
  82109. if (this._joystickPointerID == e.pointerId) {
  82110. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82111. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82112. this._joystickPointerID = -1;
  82113. this.pressed = false;
  82114. }
  82115. else {
  82116. var touch = this._touches.get(e.pointerId.toString());
  82117. if (touch) {
  82118. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82119. }
  82120. }
  82121. this._deltaJoystickVector.x = 0;
  82122. this._deltaJoystickVector.y = 0;
  82123. this._touches.remove(e.pointerId.toString());
  82124. };
  82125. /**
  82126. * Change the color of the virtual joystick
  82127. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82128. */
  82129. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82130. this._joystickColor = newColor;
  82131. };
  82132. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82133. this._action = action;
  82134. };
  82135. // Define which axis you'd like to control for left & right
  82136. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82137. switch (axis) {
  82138. case JoystickAxis.X:
  82139. case JoystickAxis.Y:
  82140. case JoystickAxis.Z:
  82141. this._axisTargetedByLeftAndRight = axis;
  82142. break;
  82143. default:
  82144. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82145. break;
  82146. }
  82147. };
  82148. // Define which axis you'd like to control for up & down
  82149. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82150. switch (axis) {
  82151. case JoystickAxis.X:
  82152. case JoystickAxis.Y:
  82153. case JoystickAxis.Z:
  82154. this._axisTargetedByUpAndDown = axis;
  82155. break;
  82156. default:
  82157. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82158. break;
  82159. }
  82160. };
  82161. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82162. var _this = this;
  82163. if (this.pressed) {
  82164. this._touches.forEach(function (key, touch) {
  82165. if (touch.pointerId === _this._joystickPointerID) {
  82166. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82167. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82168. VirtualJoystick.vjCanvasContext.beginPath();
  82169. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82170. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82171. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82172. VirtualJoystick.vjCanvasContext.stroke();
  82173. VirtualJoystick.vjCanvasContext.closePath();
  82174. VirtualJoystick.vjCanvasContext.beginPath();
  82175. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82176. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82177. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82178. VirtualJoystick.vjCanvasContext.stroke();
  82179. VirtualJoystick.vjCanvasContext.closePath();
  82180. VirtualJoystick.vjCanvasContext.beginPath();
  82181. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82182. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82183. VirtualJoystick.vjCanvasContext.stroke();
  82184. VirtualJoystick.vjCanvasContext.closePath();
  82185. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82186. }
  82187. else {
  82188. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82189. VirtualJoystick.vjCanvasContext.beginPath();
  82190. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82191. VirtualJoystick.vjCanvasContext.beginPath();
  82192. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82193. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82194. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82195. VirtualJoystick.vjCanvasContext.stroke();
  82196. VirtualJoystick.vjCanvasContext.closePath();
  82197. touch.prevX = touch.x;
  82198. touch.prevY = touch.y;
  82199. }
  82200. ;
  82201. });
  82202. }
  82203. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82204. };
  82205. VirtualJoystick.prototype.releaseCanvas = function () {
  82206. if (VirtualJoystick.vjCanvas) {
  82207. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82208. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82209. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82210. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82211. window.removeEventListener("resize", this._onResize);
  82212. document.body.removeChild(VirtualJoystick.vjCanvas);
  82213. VirtualJoystick.vjCanvas = null;
  82214. }
  82215. };
  82216. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82217. VirtualJoystick._globalJoystickIndex = 0;
  82218. return VirtualJoystick;
  82219. }());
  82220. BABYLON.VirtualJoystick = VirtualJoystick;
  82221. })(BABYLON || (BABYLON = {}));
  82222. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82223. var BABYLON;
  82224. (function (BABYLON) {
  82225. // We're mainly based on the logic defined into the FreeCamera code
  82226. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82227. __extends(VirtualJoysticksCamera, _super);
  82228. function VirtualJoysticksCamera(name, position, scene) {
  82229. var _this = _super.call(this, name, position, scene) || this;
  82230. _this.inputs.addVirtualJoystick();
  82231. return _this;
  82232. }
  82233. VirtualJoysticksCamera.prototype.getClassName = function () {
  82234. return "VirtualJoysticksCamera";
  82235. };
  82236. return VirtualJoysticksCamera;
  82237. }(BABYLON.FreeCamera));
  82238. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82239. })(BABYLON || (BABYLON = {}));
  82240. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82241. var BABYLON;
  82242. (function (BABYLON) {
  82243. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82244. function FreeCameraVirtualJoystickInput() {
  82245. }
  82246. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82247. return this._leftjoystick;
  82248. };
  82249. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82250. return this._rightjoystick;
  82251. };
  82252. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82253. if (this._leftjoystick) {
  82254. var camera = this.camera;
  82255. var speed = camera._computeLocalCameraSpeed() * 50;
  82256. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82257. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82258. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82259. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82260. if (!this._leftjoystick.pressed) {
  82261. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82262. }
  82263. if (!this._rightjoystick.pressed) {
  82264. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82265. }
  82266. }
  82267. };
  82268. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82269. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82270. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82271. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82272. this._leftjoystick.setJoystickSensibility(0.15);
  82273. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82274. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82275. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82276. this._rightjoystick.reverseUpDown = true;
  82277. this._rightjoystick.setJoystickSensibility(0.05);
  82278. this._rightjoystick.setJoystickColor("yellow");
  82279. };
  82280. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82281. this._leftjoystick.releaseCanvas();
  82282. this._rightjoystick.releaseCanvas();
  82283. };
  82284. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82285. return "FreeCameraVirtualJoystickInput";
  82286. };
  82287. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82288. return "virtualJoystick";
  82289. };
  82290. return FreeCameraVirtualJoystickInput;
  82291. }());
  82292. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82293. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82294. })(BABYLON || (BABYLON = {}));
  82295. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82296. var BABYLON;
  82297. (function (BABYLON) {
  82298. var SimplificationSettings = /** @class */ (function () {
  82299. function SimplificationSettings(quality, distance, optimizeMesh) {
  82300. this.quality = quality;
  82301. this.distance = distance;
  82302. this.optimizeMesh = optimizeMesh;
  82303. }
  82304. return SimplificationSettings;
  82305. }());
  82306. BABYLON.SimplificationSettings = SimplificationSettings;
  82307. var SimplificationQueue = /** @class */ (function () {
  82308. function SimplificationQueue() {
  82309. this.running = false;
  82310. this._simplificationArray = [];
  82311. }
  82312. SimplificationQueue.prototype.addTask = function (task) {
  82313. this._simplificationArray.push(task);
  82314. };
  82315. SimplificationQueue.prototype.executeNext = function () {
  82316. var task = this._simplificationArray.pop();
  82317. if (task) {
  82318. this.running = true;
  82319. this.runSimplification(task);
  82320. }
  82321. else {
  82322. this.running = false;
  82323. }
  82324. };
  82325. SimplificationQueue.prototype.runSimplification = function (task) {
  82326. var _this = this;
  82327. if (task.parallelProcessing) {
  82328. //parallel simplifier
  82329. task.settings.forEach(function (setting) {
  82330. var simplifier = _this.getSimplifier(task);
  82331. simplifier.simplify(setting, function (newMesh) {
  82332. task.mesh.addLODLevel(setting.distance, newMesh);
  82333. newMesh.isVisible = true;
  82334. //check if it is the last
  82335. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82336. //all done, run the success callback.
  82337. task.successCallback();
  82338. }
  82339. _this.executeNext();
  82340. });
  82341. });
  82342. }
  82343. else {
  82344. //single simplifier.
  82345. var simplifier = this.getSimplifier(task);
  82346. var runDecimation = function (setting, callback) {
  82347. simplifier.simplify(setting, function (newMesh) {
  82348. task.mesh.addLODLevel(setting.distance, newMesh);
  82349. newMesh.isVisible = true;
  82350. //run the next quality level
  82351. callback();
  82352. });
  82353. };
  82354. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82355. runDecimation(task.settings[loop.index], function () {
  82356. loop.executeNext();
  82357. });
  82358. }, function () {
  82359. //execution ended, run the success callback.
  82360. if (task.successCallback) {
  82361. task.successCallback();
  82362. }
  82363. _this.executeNext();
  82364. });
  82365. }
  82366. };
  82367. SimplificationQueue.prototype.getSimplifier = function (task) {
  82368. switch (task.simplificationType) {
  82369. case SimplificationType.QUADRATIC:
  82370. default:
  82371. return new QuadraticErrorSimplification(task.mesh);
  82372. }
  82373. };
  82374. return SimplificationQueue;
  82375. }());
  82376. BABYLON.SimplificationQueue = SimplificationQueue;
  82377. /**
  82378. * The implemented types of simplification.
  82379. * At the moment only Quadratic Error Decimation is implemented.
  82380. */
  82381. var SimplificationType;
  82382. (function (SimplificationType) {
  82383. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82384. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82385. var DecimationTriangle = /** @class */ (function () {
  82386. function DecimationTriangle(vertices) {
  82387. this.vertices = vertices;
  82388. this.error = new Array(4);
  82389. this.deleted = false;
  82390. this.isDirty = false;
  82391. this.deletePending = false;
  82392. this.borderFactor = 0;
  82393. }
  82394. return DecimationTriangle;
  82395. }());
  82396. BABYLON.DecimationTriangle = DecimationTriangle;
  82397. var DecimationVertex = /** @class */ (function () {
  82398. function DecimationVertex(position, id) {
  82399. this.position = position;
  82400. this.id = id;
  82401. this.isBorder = true;
  82402. this.q = new QuadraticMatrix();
  82403. this.triangleCount = 0;
  82404. this.triangleStart = 0;
  82405. this.originalOffsets = [];
  82406. }
  82407. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82408. this.position.copyFrom(newPosition);
  82409. };
  82410. return DecimationVertex;
  82411. }());
  82412. BABYLON.DecimationVertex = DecimationVertex;
  82413. var QuadraticMatrix = /** @class */ (function () {
  82414. function QuadraticMatrix(data) {
  82415. this.data = new Array(10);
  82416. for (var i = 0; i < 10; ++i) {
  82417. if (data && data[i]) {
  82418. this.data[i] = data[i];
  82419. }
  82420. else {
  82421. this.data[i] = 0;
  82422. }
  82423. }
  82424. }
  82425. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82426. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82427. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82428. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82429. return det;
  82430. };
  82431. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82432. for (var i = 0; i < 10; ++i) {
  82433. this.data[i] += matrix.data[i];
  82434. }
  82435. };
  82436. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82437. for (var i = 0; i < 10; ++i) {
  82438. this.data[i] += data[i];
  82439. }
  82440. };
  82441. QuadraticMatrix.prototype.add = function (matrix) {
  82442. var m = new QuadraticMatrix();
  82443. for (var i = 0; i < 10; ++i) {
  82444. m.data[i] = this.data[i] + matrix.data[i];
  82445. }
  82446. return m;
  82447. };
  82448. QuadraticMatrix.FromData = function (a, b, c, d) {
  82449. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82450. };
  82451. //returning an array to avoid garbage collection
  82452. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82453. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82454. };
  82455. return QuadraticMatrix;
  82456. }());
  82457. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82458. var Reference = /** @class */ (function () {
  82459. function Reference(vertexId, triangleId) {
  82460. this.vertexId = vertexId;
  82461. this.triangleId = triangleId;
  82462. }
  82463. return Reference;
  82464. }());
  82465. BABYLON.Reference = Reference;
  82466. /**
  82467. * An implementation of the Quadratic Error simplification algorithm.
  82468. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82469. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82470. * @author RaananW
  82471. */
  82472. var QuadraticErrorSimplification = /** @class */ (function () {
  82473. function QuadraticErrorSimplification(_mesh) {
  82474. this._mesh = _mesh;
  82475. this.syncIterations = 5000;
  82476. this.aggressiveness = 7;
  82477. this.decimationIterations = 100;
  82478. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82479. }
  82480. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82481. var _this = this;
  82482. this.initDecimatedMesh();
  82483. //iterating through the submeshes array, one after the other.
  82484. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82485. _this.initWithMesh(loop.index, function () {
  82486. _this.runDecimation(settings, loop.index, function () {
  82487. loop.executeNext();
  82488. });
  82489. }, settings.optimizeMesh);
  82490. }, function () {
  82491. setTimeout(function () {
  82492. successCallback(_this._reconstructedMesh);
  82493. }, 0);
  82494. });
  82495. };
  82496. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82497. var _this = this;
  82498. var targetCount = ~~(this.triangles.length * settings.quality);
  82499. var deletedTriangles = 0;
  82500. var triangleCount = this.triangles.length;
  82501. var iterationFunction = function (iteration, callback) {
  82502. setTimeout(function () {
  82503. if (iteration % 5 === 0) {
  82504. _this.updateMesh(iteration === 0);
  82505. }
  82506. for (var i = 0; i < _this.triangles.length; ++i) {
  82507. _this.triangles[i].isDirty = false;
  82508. }
  82509. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82510. var trianglesIterator = function (i) {
  82511. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82512. var t = _this.triangles[tIdx];
  82513. if (!t)
  82514. return;
  82515. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82516. return;
  82517. }
  82518. for (var j = 0; j < 3; ++j) {
  82519. if (t.error[j] < threshold) {
  82520. var deleted0 = [];
  82521. var deleted1 = [];
  82522. var v0 = t.vertices[j];
  82523. var v1 = t.vertices[(j + 1) % 3];
  82524. if (v0.isBorder || v1.isBorder)
  82525. continue;
  82526. var p = BABYLON.Vector3.Zero();
  82527. var n = BABYLON.Vector3.Zero();
  82528. var uv = BABYLON.Vector2.Zero();
  82529. var color = new BABYLON.Color4(0, 0, 0, 1);
  82530. _this.calculateError(v0, v1, p, n, uv, color);
  82531. var delTr = new Array();
  82532. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82533. continue;
  82534. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82535. continue;
  82536. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82537. continue;
  82538. var uniqueArray = new Array();
  82539. delTr.forEach(function (deletedT) {
  82540. if (uniqueArray.indexOf(deletedT) === -1) {
  82541. deletedT.deletePending = true;
  82542. uniqueArray.push(deletedT);
  82543. }
  82544. });
  82545. if (uniqueArray.length % 2 !== 0) {
  82546. continue;
  82547. }
  82548. v0.q = v1.q.add(v0.q);
  82549. v0.updatePosition(p);
  82550. var tStart = _this.references.length;
  82551. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82552. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82553. var tCount = _this.references.length - tStart;
  82554. if (tCount <= v0.triangleCount) {
  82555. if (tCount) {
  82556. for (var c = 0; c < tCount; c++) {
  82557. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82558. }
  82559. }
  82560. }
  82561. else {
  82562. v0.triangleStart = tStart;
  82563. }
  82564. v0.triangleCount = tCount;
  82565. break;
  82566. }
  82567. }
  82568. };
  82569. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82570. }, 0);
  82571. };
  82572. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82573. if (triangleCount - deletedTriangles <= targetCount)
  82574. loop.breakLoop();
  82575. else {
  82576. iterationFunction(loop.index, function () {
  82577. loop.executeNext();
  82578. });
  82579. }
  82580. }, function () {
  82581. setTimeout(function () {
  82582. //reconstruct this part of the mesh
  82583. _this.reconstructMesh(submeshIndex);
  82584. successCallback();
  82585. }, 0);
  82586. });
  82587. };
  82588. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82589. var _this = this;
  82590. this.vertices = [];
  82591. this.triangles = [];
  82592. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82593. var indices = this._mesh.getIndices();
  82594. var submesh = this._mesh.subMeshes[submeshIndex];
  82595. var findInVertices = function (positionToSearch) {
  82596. if (optimizeMesh) {
  82597. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82598. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82599. return _this.vertices[ii];
  82600. }
  82601. }
  82602. }
  82603. return null;
  82604. };
  82605. var vertexReferences = [];
  82606. var vertexInit = function (i) {
  82607. if (!positionData) {
  82608. return;
  82609. }
  82610. var offset = i + submesh.verticesStart;
  82611. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82612. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82613. vertex.originalOffsets.push(offset);
  82614. if (vertex.id === _this.vertices.length) {
  82615. _this.vertices.push(vertex);
  82616. }
  82617. vertexReferences.push(vertex.id);
  82618. };
  82619. //var totalVertices = mesh.getTotalVertices();
  82620. var totalVertices = submesh.verticesCount;
  82621. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82622. var indicesInit = function (i) {
  82623. if (!indices) {
  82624. return;
  82625. }
  82626. var offset = (submesh.indexStart / 3) + i;
  82627. var pos = (offset * 3);
  82628. var i0 = indices[pos + 0];
  82629. var i1 = indices[pos + 1];
  82630. var i2 = indices[pos + 2];
  82631. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82632. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82633. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82634. var triangle = new DecimationTriangle([v0, v1, v2]);
  82635. triangle.originalOffset = pos;
  82636. _this.triangles.push(triangle);
  82637. };
  82638. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82639. _this.init(callback);
  82640. });
  82641. });
  82642. };
  82643. QuadraticErrorSimplification.prototype.init = function (callback) {
  82644. var _this = this;
  82645. var triangleInit1 = function (i) {
  82646. var t = _this.triangles[i];
  82647. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82648. for (var j = 0; j < 3; j++) {
  82649. 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))));
  82650. }
  82651. };
  82652. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82653. var triangleInit2 = function (i) {
  82654. var t = _this.triangles[i];
  82655. for (var j = 0; j < 3; ++j) {
  82656. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82657. }
  82658. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82659. };
  82660. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82661. callback();
  82662. });
  82663. });
  82664. };
  82665. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82666. var newTriangles = [];
  82667. var i;
  82668. for (i = 0; i < this.vertices.length; ++i) {
  82669. this.vertices[i].triangleCount = 0;
  82670. }
  82671. var t;
  82672. var j;
  82673. for (i = 0; i < this.triangles.length; ++i) {
  82674. if (!this.triangles[i].deleted) {
  82675. t = this.triangles[i];
  82676. for (j = 0; j < 3; ++j) {
  82677. t.vertices[j].triangleCount = 1;
  82678. }
  82679. newTriangles.push(t);
  82680. }
  82681. }
  82682. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82683. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82684. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82685. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82686. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82687. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82688. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82689. var vertexCount = 0;
  82690. for (i = 0; i < this.vertices.length; ++i) {
  82691. var vertex = this.vertices[i];
  82692. vertex.id = vertexCount;
  82693. if (vertex.triangleCount) {
  82694. vertex.originalOffsets.forEach(function (originalOffset) {
  82695. if (!normalData) {
  82696. return;
  82697. }
  82698. newPositionData.push(vertex.position.x);
  82699. newPositionData.push(vertex.position.y);
  82700. newPositionData.push(vertex.position.z);
  82701. newNormalData.push(normalData[originalOffset * 3]);
  82702. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82703. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82704. if (uvs && uvs.length) {
  82705. newUVsData.push(uvs[(originalOffset * 2)]);
  82706. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82707. }
  82708. else if (colorsData && colorsData.length) {
  82709. newColorsData.push(colorsData[(originalOffset * 4)]);
  82710. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82711. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82712. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82713. }
  82714. ++vertexCount;
  82715. });
  82716. }
  82717. }
  82718. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82719. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82720. var submeshesArray = this._reconstructedMesh.subMeshes;
  82721. this._reconstructedMesh.subMeshes = [];
  82722. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82723. var originalIndices = this._mesh.getIndices();
  82724. for (i = 0; i < newTriangles.length; ++i) {
  82725. t = newTriangles[i]; //now get the new referencing point for each vertex
  82726. [0, 1, 2].forEach(function (idx) {
  82727. var id = originalIndices[t.originalOffset + idx];
  82728. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82729. if (offset < 0)
  82730. offset = 0;
  82731. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82732. });
  82733. }
  82734. //overwriting the old vertex buffers and indices.
  82735. this._reconstructedMesh.setIndices(newIndicesArray);
  82736. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82737. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82738. if (newUVsData.length > 0)
  82739. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82740. if (newColorsData.length > 0)
  82741. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82742. //create submesh
  82743. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82744. if (submeshIndex > 0) {
  82745. this._reconstructedMesh.subMeshes = [];
  82746. submeshesArray.forEach(function (submesh) {
  82747. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82748. });
  82749. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82750. }
  82751. };
  82752. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82753. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82754. this._reconstructedMesh.material = this._mesh.material;
  82755. this._reconstructedMesh.parent = this._mesh.parent;
  82756. this._reconstructedMesh.isVisible = false;
  82757. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82758. };
  82759. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82760. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82761. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82762. if (t.deleted)
  82763. continue;
  82764. var s = this.references[vertex1.triangleStart + i].vertexId;
  82765. var v1 = t.vertices[(s + 1) % 3];
  82766. var v2 = t.vertices[(s + 2) % 3];
  82767. if ((v1 === vertex2 || v2 === vertex2)) {
  82768. deletedArray[i] = true;
  82769. delTr.push(t);
  82770. continue;
  82771. }
  82772. var d1 = v1.position.subtract(point);
  82773. d1 = d1.normalize();
  82774. var d2 = v2.position.subtract(point);
  82775. d2 = d2.normalize();
  82776. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82777. return true;
  82778. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82779. deletedArray[i] = false;
  82780. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82781. return true;
  82782. }
  82783. return false;
  82784. };
  82785. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82786. var newDeleted = deletedTriangles;
  82787. for (var i = 0; i < vertex.triangleCount; ++i) {
  82788. var ref = this.references[vertex.triangleStart + i];
  82789. var t = this.triangles[ref.triangleId];
  82790. if (t.deleted)
  82791. continue;
  82792. if (deletedArray[i] && t.deletePending) {
  82793. t.deleted = true;
  82794. newDeleted++;
  82795. continue;
  82796. }
  82797. t.vertices[ref.vertexId] = origVertex;
  82798. t.isDirty = true;
  82799. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82800. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82801. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82802. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82803. this.references.push(ref);
  82804. }
  82805. return newDeleted;
  82806. };
  82807. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82808. for (var i = 0; i < this.vertices.length; ++i) {
  82809. var vCount = [];
  82810. var vId = [];
  82811. var v = this.vertices[i];
  82812. var j;
  82813. for (j = 0; j < v.triangleCount; ++j) {
  82814. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82815. for (var ii = 0; ii < 3; ii++) {
  82816. var ofs = 0;
  82817. var vv = triangle.vertices[ii];
  82818. while (ofs < vCount.length) {
  82819. if (vId[ofs] === vv.id)
  82820. break;
  82821. ++ofs;
  82822. }
  82823. if (ofs === vCount.length) {
  82824. vCount.push(1);
  82825. vId.push(vv.id);
  82826. }
  82827. else {
  82828. vCount[ofs]++;
  82829. }
  82830. }
  82831. }
  82832. for (j = 0; j < vCount.length; ++j) {
  82833. if (vCount[j] === 1) {
  82834. this.vertices[vId[j]].isBorder = true;
  82835. }
  82836. else {
  82837. this.vertices[vId[j]].isBorder = false;
  82838. }
  82839. }
  82840. }
  82841. };
  82842. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82843. if (identifyBorders === void 0) { identifyBorders = false; }
  82844. var i;
  82845. if (!identifyBorders) {
  82846. var newTrianglesVector = [];
  82847. for (i = 0; i < this.triangles.length; ++i) {
  82848. if (!this.triangles[i].deleted) {
  82849. newTrianglesVector.push(this.triangles[i]);
  82850. }
  82851. }
  82852. this.triangles = newTrianglesVector;
  82853. }
  82854. for (i = 0; i < this.vertices.length; ++i) {
  82855. this.vertices[i].triangleCount = 0;
  82856. this.vertices[i].triangleStart = 0;
  82857. }
  82858. var t;
  82859. var j;
  82860. var v;
  82861. for (i = 0; i < this.triangles.length; ++i) {
  82862. t = this.triangles[i];
  82863. for (j = 0; j < 3; ++j) {
  82864. v = t.vertices[j];
  82865. v.triangleCount++;
  82866. }
  82867. }
  82868. var tStart = 0;
  82869. for (i = 0; i < this.vertices.length; ++i) {
  82870. this.vertices[i].triangleStart = tStart;
  82871. tStart += this.vertices[i].triangleCount;
  82872. this.vertices[i].triangleCount = 0;
  82873. }
  82874. var newReferences = new Array(this.triangles.length * 3);
  82875. for (i = 0; i < this.triangles.length; ++i) {
  82876. t = this.triangles[i];
  82877. for (j = 0; j < 3; ++j) {
  82878. v = t.vertices[j];
  82879. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82880. v.triangleCount++;
  82881. }
  82882. }
  82883. this.references = newReferences;
  82884. if (identifyBorders) {
  82885. this.identifyBorder();
  82886. }
  82887. };
  82888. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82889. var x = point.x;
  82890. var y = point.y;
  82891. var z = point.z;
  82892. 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
  82893. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82894. };
  82895. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82896. var q = vertex1.q.add(vertex2.q);
  82897. var border = vertex1.isBorder && vertex2.isBorder;
  82898. var error = 0;
  82899. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82900. if (qDet !== 0 && !border) {
  82901. if (!pointResult) {
  82902. pointResult = BABYLON.Vector3.Zero();
  82903. }
  82904. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82905. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82906. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82907. error = this.vertexError(q, pointResult);
  82908. }
  82909. else {
  82910. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82911. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82912. var error1 = this.vertexError(q, vertex1.position);
  82913. var error2 = this.vertexError(q, vertex2.position);
  82914. var error3 = this.vertexError(q, p3);
  82915. error = Math.min(error1, error2, error3);
  82916. if (error === error1) {
  82917. if (pointResult) {
  82918. pointResult.copyFrom(vertex1.position);
  82919. }
  82920. }
  82921. else if (error === error2) {
  82922. if (pointResult) {
  82923. pointResult.copyFrom(vertex2.position);
  82924. }
  82925. }
  82926. else {
  82927. if (pointResult) {
  82928. pointResult.copyFrom(p3);
  82929. }
  82930. }
  82931. }
  82932. return error;
  82933. };
  82934. return QuadraticErrorSimplification;
  82935. }());
  82936. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82937. })(BABYLON || (BABYLON = {}));
  82938. //# sourceMappingURL=babylon.meshSimplification.js.map
  82939. var BABYLON;
  82940. (function (BABYLON) {
  82941. var MeshLODLevel = /** @class */ (function () {
  82942. function MeshLODLevel(distance, mesh) {
  82943. this.distance = distance;
  82944. this.mesh = mesh;
  82945. }
  82946. return MeshLODLevel;
  82947. }());
  82948. BABYLON.MeshLODLevel = MeshLODLevel;
  82949. })(BABYLON || (BABYLON = {}));
  82950. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82951. var BABYLON;
  82952. (function (BABYLON) {
  82953. /**
  82954. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82955. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82956. */
  82957. var SceneOptimization = /** @class */ (function () {
  82958. /**
  82959. * Creates the SceneOptimization object
  82960. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82961. * @param desc defines the description associated with the optimization
  82962. */
  82963. function SceneOptimization(
  82964. /**
  82965. * Defines the priority of this optimization (0 by default which means first in the list)
  82966. */
  82967. priority) {
  82968. if (priority === void 0) { priority = 0; }
  82969. this.priority = priority;
  82970. }
  82971. /**
  82972. * Gets a string describing the action executed by the current optimization
  82973. * @returns description string
  82974. */
  82975. SceneOptimization.prototype.getDescription = function () {
  82976. return "";
  82977. };
  82978. /**
  82979. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82980. * @param scene defines the current scene where to apply this optimization
  82981. * @param optimizer defines the current optimizer
  82982. * @returns true if everything that can be done was applied
  82983. */
  82984. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82985. return true;
  82986. };
  82987. ;
  82988. return SceneOptimization;
  82989. }());
  82990. BABYLON.SceneOptimization = SceneOptimization;
  82991. /**
  82992. * Defines an optimization used to reduce the size of render target textures
  82993. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82994. */
  82995. var TextureOptimization = /** @class */ (function (_super) {
  82996. __extends(TextureOptimization, _super);
  82997. /**
  82998. * Creates the TextureOptimization object
  82999. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83000. * @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
  83001. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83002. */
  83003. function TextureOptimization(
  83004. /**
  83005. * Defines the priority of this optimization (0 by default which means first in the list)
  83006. */
  83007. priority,
  83008. /**
  83009. * 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
  83010. */
  83011. maximumSize,
  83012. /**
  83013. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83014. */
  83015. step) {
  83016. if (priority === void 0) { priority = 0; }
  83017. if (maximumSize === void 0) { maximumSize = 1024; }
  83018. if (step === void 0) { step = 0.5; }
  83019. var _this = _super.call(this, priority) || this;
  83020. _this.priority = priority;
  83021. _this.maximumSize = maximumSize;
  83022. _this.step = step;
  83023. return _this;
  83024. }
  83025. /**
  83026. * Gets a string describing the action executed by the current optimization
  83027. * @returns description string
  83028. */
  83029. TextureOptimization.prototype.getDescription = function () {
  83030. return "Reducing render target texture size to " + this.maximumSize;
  83031. };
  83032. /**
  83033. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83034. * @param scene defines the current scene where to apply this optimization
  83035. * @param optimizer defines the current optimizer
  83036. * @returns true if everything that can be done was applied
  83037. */
  83038. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83039. var allDone = true;
  83040. for (var index = 0; index < scene.textures.length; index++) {
  83041. var texture = scene.textures[index];
  83042. if (!texture.canRescale || texture.getContext) {
  83043. continue;
  83044. }
  83045. var currentSize = texture.getSize();
  83046. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83047. if (maxDimension > this.maximumSize) {
  83048. texture.scale(this.step);
  83049. allDone = false;
  83050. }
  83051. }
  83052. return allDone;
  83053. };
  83054. return TextureOptimization;
  83055. }(SceneOptimization));
  83056. BABYLON.TextureOptimization = TextureOptimization;
  83057. /**
  83058. * Defines an optimization used to increase or decrease the rendering resolution
  83059. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83060. */
  83061. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83062. __extends(HardwareScalingOptimization, _super);
  83063. /**
  83064. * Creates the HardwareScalingOptimization object
  83065. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83066. * @param maximumScale defines the maximum scale to use (2 by default)
  83067. * @param step defines the step to use between two passes (0.5 by default)
  83068. */
  83069. function HardwareScalingOptimization(
  83070. /**
  83071. * Defines the priority of this optimization (0 by default which means first in the list)
  83072. */
  83073. priority,
  83074. /**
  83075. * Defines the maximum scale to use (2 by default)
  83076. */
  83077. maximumScale,
  83078. /**
  83079. * Defines the step to use between two passes (0.5 by default)
  83080. */
  83081. step) {
  83082. if (priority === void 0) { priority = 0; }
  83083. if (maximumScale === void 0) { maximumScale = 2; }
  83084. if (step === void 0) { step = 0.25; }
  83085. var _this = _super.call(this, priority) || this;
  83086. _this.priority = priority;
  83087. _this.maximumScale = maximumScale;
  83088. _this.step = step;
  83089. _this._currentScale = -1;
  83090. _this._directionOffset = 1;
  83091. return _this;
  83092. }
  83093. /**
  83094. * Gets a string describing the action executed by the current optimization
  83095. * @return description string
  83096. */
  83097. HardwareScalingOptimization.prototype.getDescription = function () {
  83098. return "Setting hardware scaling level to " + this._currentScale;
  83099. };
  83100. /**
  83101. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83102. * @param scene defines the current scene where to apply this optimization
  83103. * @param optimizer defines the current optimizer
  83104. * @returns true if everything that can be done was applied
  83105. */
  83106. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83107. if (this._currentScale === -1) {
  83108. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83109. if (this._currentScale > this.maximumScale) {
  83110. this._directionOffset = -1;
  83111. }
  83112. }
  83113. this._currentScale += this._directionOffset * this.step;
  83114. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83115. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83116. };
  83117. ;
  83118. return HardwareScalingOptimization;
  83119. }(SceneOptimization));
  83120. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83121. /**
  83122. * Defines an optimization used to remove shadows
  83123. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83124. */
  83125. var ShadowsOptimization = /** @class */ (function (_super) {
  83126. __extends(ShadowsOptimization, _super);
  83127. function ShadowsOptimization() {
  83128. return _super !== null && _super.apply(this, arguments) || this;
  83129. }
  83130. /**
  83131. * Gets a string describing the action executed by the current optimization
  83132. * @return description string
  83133. */
  83134. ShadowsOptimization.prototype.getDescription = function () {
  83135. return "Turning shadows on/off";
  83136. };
  83137. /**
  83138. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83139. * @param scene defines the current scene where to apply this optimization
  83140. * @param optimizer defines the current optimizer
  83141. * @returns true if everything that can be done was applied
  83142. */
  83143. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83144. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83145. return true;
  83146. };
  83147. ;
  83148. return ShadowsOptimization;
  83149. }(SceneOptimization));
  83150. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83151. /**
  83152. * Defines an optimization used to turn post-processes off
  83153. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83154. */
  83155. var PostProcessesOptimization = /** @class */ (function (_super) {
  83156. __extends(PostProcessesOptimization, _super);
  83157. function PostProcessesOptimization() {
  83158. return _super !== null && _super.apply(this, arguments) || this;
  83159. }
  83160. /**
  83161. * Gets a string describing the action executed by the current optimization
  83162. * @return description string
  83163. */
  83164. PostProcessesOptimization.prototype.getDescription = function () {
  83165. return "Turning post-processes on/off";
  83166. };
  83167. /**
  83168. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83169. * @param scene defines the current scene where to apply this optimization
  83170. * @param optimizer defines the current optimizer
  83171. * @returns true if everything that can be done was applied
  83172. */
  83173. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83174. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83175. return true;
  83176. };
  83177. ;
  83178. return PostProcessesOptimization;
  83179. }(SceneOptimization));
  83180. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83181. /**
  83182. * Defines an optimization used to turn lens flares off
  83183. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83184. */
  83185. var LensFlaresOptimization = /** @class */ (function (_super) {
  83186. __extends(LensFlaresOptimization, _super);
  83187. function LensFlaresOptimization() {
  83188. return _super !== null && _super.apply(this, arguments) || this;
  83189. }
  83190. /**
  83191. * Gets a string describing the action executed by the current optimization
  83192. * @return description string
  83193. */
  83194. LensFlaresOptimization.prototype.getDescription = function () {
  83195. return "Turning lens flares on/off";
  83196. };
  83197. /**
  83198. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83199. * @param scene defines the current scene where to apply this optimization
  83200. * @param optimizer defines the current optimizer
  83201. * @returns true if everything that can be done was applied
  83202. */
  83203. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83204. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83205. return true;
  83206. };
  83207. ;
  83208. return LensFlaresOptimization;
  83209. }(SceneOptimization));
  83210. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83211. /**
  83212. * Defines an optimization based on user defined callback.
  83213. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83214. */
  83215. var CustomOptimization = /** @class */ (function (_super) {
  83216. __extends(CustomOptimization, _super);
  83217. function CustomOptimization() {
  83218. return _super !== null && _super.apply(this, arguments) || this;
  83219. }
  83220. /**
  83221. * Gets a string describing the action executed by the current optimization
  83222. * @returns description string
  83223. */
  83224. CustomOptimization.prototype.getDescription = function () {
  83225. if (this.onGetDescription) {
  83226. return this.onGetDescription();
  83227. }
  83228. return "Running user defined callback";
  83229. };
  83230. /**
  83231. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83232. * @param scene defines the current scene where to apply this optimization
  83233. * @param optimizer defines the current optimizer
  83234. * @returns true if everything that can be done was applied
  83235. */
  83236. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83237. if (this.onApply) {
  83238. return this.onApply(scene, optimizer);
  83239. }
  83240. return true;
  83241. };
  83242. ;
  83243. return CustomOptimization;
  83244. }(SceneOptimization));
  83245. BABYLON.CustomOptimization = CustomOptimization;
  83246. /**
  83247. * Defines an optimization used to turn particles off
  83248. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83249. */
  83250. var ParticlesOptimization = /** @class */ (function (_super) {
  83251. __extends(ParticlesOptimization, _super);
  83252. function ParticlesOptimization() {
  83253. return _super !== null && _super.apply(this, arguments) || this;
  83254. }
  83255. /**
  83256. * Gets a string describing the action executed by the current optimization
  83257. * @return description string
  83258. */
  83259. ParticlesOptimization.prototype.getDescription = function () {
  83260. return "Turning particles on/off";
  83261. };
  83262. /**
  83263. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83264. * @param scene defines the current scene where to apply this optimization
  83265. * @param optimizer defines the current optimizer
  83266. * @returns true if everything that can be done was applied
  83267. */
  83268. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83269. scene.particlesEnabled = optimizer.isInImprovementMode;
  83270. return true;
  83271. };
  83272. ;
  83273. return ParticlesOptimization;
  83274. }(SceneOptimization));
  83275. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83276. /**
  83277. * Defines an optimization used to turn render targets off
  83278. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83279. */
  83280. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83281. __extends(RenderTargetsOptimization, _super);
  83282. function RenderTargetsOptimization() {
  83283. return _super !== null && _super.apply(this, arguments) || this;
  83284. }
  83285. /**
  83286. * Gets a string describing the action executed by the current optimization
  83287. * @return description string
  83288. */
  83289. RenderTargetsOptimization.prototype.getDescription = function () {
  83290. return "Turning render targets off";
  83291. };
  83292. /**
  83293. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83294. * @param scene defines the current scene where to apply this optimization
  83295. * @param optimizer defines the current optimizer
  83296. * @returns true if everything that can be done was applied
  83297. */
  83298. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83299. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83300. return true;
  83301. };
  83302. ;
  83303. return RenderTargetsOptimization;
  83304. }(SceneOptimization));
  83305. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83306. /**
  83307. * Defines an optimization used to merge meshes with compatible materials
  83308. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83309. */
  83310. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83311. __extends(MergeMeshesOptimization, _super);
  83312. function MergeMeshesOptimization() {
  83313. var _this = _super !== null && _super.apply(this, arguments) || this;
  83314. _this._canBeMerged = function (abstractMesh) {
  83315. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83316. return false;
  83317. }
  83318. var mesh = abstractMesh;
  83319. if (!mesh.isVisible || !mesh.isEnabled()) {
  83320. return false;
  83321. }
  83322. if (mesh.instances.length > 0) {
  83323. return false;
  83324. }
  83325. if (mesh.skeleton || mesh.hasLODLevels) {
  83326. return false;
  83327. }
  83328. if (mesh.parent) {
  83329. return false;
  83330. }
  83331. return true;
  83332. };
  83333. return _this;
  83334. }
  83335. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83336. /**
  83337. * Gets or sets a boolean which defines if optimization octree has to be updated
  83338. */
  83339. get: function () {
  83340. return MergeMeshesOptimization._UpdateSelectionTree;
  83341. },
  83342. /**
  83343. * Gets or sets a boolean which defines if optimization octree has to be updated
  83344. */
  83345. set: function (value) {
  83346. MergeMeshesOptimization._UpdateSelectionTree = value;
  83347. },
  83348. enumerable: true,
  83349. configurable: true
  83350. });
  83351. /**
  83352. * Gets a string describing the action executed by the current optimization
  83353. * @return description string
  83354. */
  83355. MergeMeshesOptimization.prototype.getDescription = function () {
  83356. return "Merging similar meshes together";
  83357. };
  83358. /**
  83359. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83360. * @param scene defines the current scene where to apply this optimization
  83361. * @param optimizer defines the current optimizer
  83362. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83363. * @returns true if everything that can be done was applied
  83364. */
  83365. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83366. var globalPool = scene.meshes.slice(0);
  83367. var globalLength = globalPool.length;
  83368. for (var index = 0; index < globalLength; index++) {
  83369. var currentPool = new Array();
  83370. var current = globalPool[index];
  83371. // Checks
  83372. if (!this._canBeMerged(current)) {
  83373. continue;
  83374. }
  83375. currentPool.push(current);
  83376. // Find compatible meshes
  83377. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83378. var otherMesh = globalPool[subIndex];
  83379. if (!this._canBeMerged(otherMesh)) {
  83380. continue;
  83381. }
  83382. if (otherMesh.material !== current.material) {
  83383. continue;
  83384. }
  83385. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83386. continue;
  83387. }
  83388. currentPool.push(otherMesh);
  83389. globalLength--;
  83390. globalPool.splice(subIndex, 1);
  83391. subIndex--;
  83392. }
  83393. if (currentPool.length < 2) {
  83394. continue;
  83395. }
  83396. // Merge meshes
  83397. BABYLON.Mesh.MergeMeshes(currentPool);
  83398. }
  83399. if (updateSelectionTree != undefined) {
  83400. if (updateSelectionTree) {
  83401. scene.createOrUpdateSelectionOctree();
  83402. }
  83403. }
  83404. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83405. scene.createOrUpdateSelectionOctree();
  83406. }
  83407. return true;
  83408. };
  83409. ;
  83410. MergeMeshesOptimization._UpdateSelectionTree = false;
  83411. return MergeMeshesOptimization;
  83412. }(SceneOptimization));
  83413. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83414. /**
  83415. * Defines a list of options used by SceneOptimizer
  83416. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83417. */
  83418. var SceneOptimizerOptions = /** @class */ (function () {
  83419. /**
  83420. * Creates a new list of options used by SceneOptimizer
  83421. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83422. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83423. */
  83424. function SceneOptimizerOptions(
  83425. /**
  83426. * Defines the target frame rate to reach (60 by default)
  83427. */
  83428. targetFrameRate,
  83429. /**
  83430. * Defines the interval between two checkes (2000ms by default)
  83431. */
  83432. trackerDuration) {
  83433. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83434. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83435. this.targetFrameRate = targetFrameRate;
  83436. this.trackerDuration = trackerDuration;
  83437. /**
  83438. * Gets the list of optimizations to apply
  83439. */
  83440. this.optimizations = new Array();
  83441. }
  83442. /**
  83443. * Add a new optimization
  83444. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83445. * @returns the current SceneOptimizerOptions
  83446. */
  83447. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83448. this.optimizations.push(optimization);
  83449. return this;
  83450. };
  83451. /**
  83452. * Add a new custom optimization
  83453. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83454. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83455. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83456. * @returns the current SceneOptimizerOptions
  83457. */
  83458. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83459. if (priority === void 0) { priority = 0; }
  83460. var optimization = new CustomOptimization(priority);
  83461. optimization.onApply = onApply;
  83462. optimization.onGetDescription = onGetDescription;
  83463. this.optimizations.push(optimization);
  83464. return this;
  83465. };
  83466. /**
  83467. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83468. * @param targetFrameRate defines the target frame rate (60 by default)
  83469. * @returns a SceneOptimizerOptions object
  83470. */
  83471. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83472. var result = new SceneOptimizerOptions(targetFrameRate);
  83473. var priority = 0;
  83474. result.addOptimization(new MergeMeshesOptimization(priority));
  83475. result.addOptimization(new ShadowsOptimization(priority));
  83476. result.addOptimization(new LensFlaresOptimization(priority));
  83477. // Next priority
  83478. priority++;
  83479. result.addOptimization(new PostProcessesOptimization(priority));
  83480. result.addOptimization(new ParticlesOptimization(priority));
  83481. // Next priority
  83482. priority++;
  83483. result.addOptimization(new TextureOptimization(priority, 1024));
  83484. return result;
  83485. };
  83486. /**
  83487. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83488. * @param targetFrameRate defines the target frame rate (60 by default)
  83489. * @returns a SceneOptimizerOptions object
  83490. */
  83491. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83492. var result = new SceneOptimizerOptions(targetFrameRate);
  83493. var priority = 0;
  83494. result.addOptimization(new MergeMeshesOptimization(priority));
  83495. result.addOptimization(new ShadowsOptimization(priority));
  83496. result.addOptimization(new LensFlaresOptimization(priority));
  83497. // Next priority
  83498. priority++;
  83499. result.addOptimization(new PostProcessesOptimization(priority));
  83500. result.addOptimization(new ParticlesOptimization(priority));
  83501. // Next priority
  83502. priority++;
  83503. result.addOptimization(new TextureOptimization(priority, 512));
  83504. // Next priority
  83505. priority++;
  83506. result.addOptimization(new RenderTargetsOptimization(priority));
  83507. // Next priority
  83508. priority++;
  83509. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83510. return result;
  83511. };
  83512. /**
  83513. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83514. * @param targetFrameRate defines the target frame rate (60 by default)
  83515. * @returns a SceneOptimizerOptions object
  83516. */
  83517. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83518. var result = new SceneOptimizerOptions(targetFrameRate);
  83519. var priority = 0;
  83520. result.addOptimization(new MergeMeshesOptimization(priority));
  83521. result.addOptimization(new ShadowsOptimization(priority));
  83522. result.addOptimization(new LensFlaresOptimization(priority));
  83523. // Next priority
  83524. priority++;
  83525. result.addOptimization(new PostProcessesOptimization(priority));
  83526. result.addOptimization(new ParticlesOptimization(priority));
  83527. // Next priority
  83528. priority++;
  83529. result.addOptimization(new TextureOptimization(priority, 256));
  83530. // Next priority
  83531. priority++;
  83532. result.addOptimization(new RenderTargetsOptimization(priority));
  83533. // Next priority
  83534. priority++;
  83535. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83536. return result;
  83537. };
  83538. return SceneOptimizerOptions;
  83539. }());
  83540. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83541. /**
  83542. * Class used to run optimizations in order to reach a target frame rate
  83543. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83544. */
  83545. var SceneOptimizer = /** @class */ (function () {
  83546. /**
  83547. * Creates a new SceneOptimizer
  83548. * @param scene defines the scene to work on
  83549. * @param options defines the options to use with the SceneOptimizer
  83550. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83551. * @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)
  83552. */
  83553. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83554. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83555. if (improvementMode === void 0) { improvementMode = false; }
  83556. var _this = this;
  83557. this._isRunning = false;
  83558. this._currentPriorityLevel = 0;
  83559. this._targetFrameRate = 60;
  83560. this._trackerDuration = 2000;
  83561. this._currentFrameRate = 0;
  83562. this._improvementMode = false;
  83563. /**
  83564. * Defines an observable called when the optimizer reaches the target frame rate
  83565. */
  83566. this.onSuccessObservable = new BABYLON.Observable();
  83567. /**
  83568. * Defines an observable called when the optimizer enables an optimization
  83569. */
  83570. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83571. /**
  83572. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83573. */
  83574. this.onFailureObservable = new BABYLON.Observable();
  83575. if (!options) {
  83576. this._options = new SceneOptimizerOptions();
  83577. }
  83578. else {
  83579. this._options = options;
  83580. }
  83581. if (this._options.targetFrameRate) {
  83582. this._targetFrameRate = this._options.targetFrameRate;
  83583. }
  83584. if (this._options.trackerDuration) {
  83585. this._trackerDuration = this._options.trackerDuration;
  83586. }
  83587. if (autoGeneratePriorities) {
  83588. var priority = 0;
  83589. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83590. var optim = _a[_i];
  83591. optim.priority = priority++;
  83592. }
  83593. }
  83594. this._improvementMode = improvementMode;
  83595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83596. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83597. _this._sceneDisposeObserver = null;
  83598. _this.dispose();
  83599. });
  83600. }
  83601. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83602. /**
  83603. * Gets a boolean indicating if the optimizer is in improvement mode
  83604. */
  83605. get: function () {
  83606. return this._improvementMode;
  83607. },
  83608. enumerable: true,
  83609. configurable: true
  83610. });
  83611. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83612. /**
  83613. * Gets the current priority level (0 at start)
  83614. */
  83615. get: function () {
  83616. return this._currentPriorityLevel;
  83617. },
  83618. enumerable: true,
  83619. configurable: true
  83620. });
  83621. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83622. /**
  83623. * Gets the current frame rate checked by the SceneOptimizer
  83624. */
  83625. get: function () {
  83626. return this._currentFrameRate;
  83627. },
  83628. enumerable: true,
  83629. configurable: true
  83630. });
  83631. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83632. /**
  83633. * Gets or sets the current target frame rate (60 by default)
  83634. */
  83635. get: function () {
  83636. return this._targetFrameRate;
  83637. },
  83638. /**
  83639. * Gets or sets the current target frame rate (60 by default)
  83640. */
  83641. set: function (value) {
  83642. this._targetFrameRate = value;
  83643. },
  83644. enumerable: true,
  83645. configurable: true
  83646. });
  83647. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83648. /**
  83649. * Gets or sets the current interval between two checks (every 2000ms by default)
  83650. */
  83651. get: function () {
  83652. return this._trackerDuration;
  83653. },
  83654. /**
  83655. * Gets or sets the current interval between two checks (every 2000ms by default)
  83656. */
  83657. set: function (value) {
  83658. this._trackerDuration = value;
  83659. },
  83660. enumerable: true,
  83661. configurable: true
  83662. });
  83663. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83664. /**
  83665. * Gets the list of active optimizations
  83666. */
  83667. get: function () {
  83668. return this._options.optimizations;
  83669. },
  83670. enumerable: true,
  83671. configurable: true
  83672. });
  83673. /**
  83674. * Stops the current optimizer
  83675. */
  83676. SceneOptimizer.prototype.stop = function () {
  83677. this._isRunning = false;
  83678. };
  83679. /**
  83680. * Reset the optimizer to initial step (current priority level = 0)
  83681. */
  83682. SceneOptimizer.prototype.reset = function () {
  83683. this._currentPriorityLevel = 0;
  83684. };
  83685. /**
  83686. * Start the optimizer. By default it will try to reach a specific framerate
  83687. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83688. */
  83689. SceneOptimizer.prototype.start = function () {
  83690. var _this = this;
  83691. if (this._isRunning) {
  83692. return;
  83693. }
  83694. this._isRunning = true;
  83695. // Let's wait for the scene to be ready before running our check
  83696. this._scene.executeWhenReady(function () {
  83697. setTimeout(function () {
  83698. _this._checkCurrentState();
  83699. }, _this._trackerDuration);
  83700. });
  83701. };
  83702. SceneOptimizer.prototype._checkCurrentState = function () {
  83703. var _this = this;
  83704. if (!this._isRunning) {
  83705. return;
  83706. }
  83707. var scene = this._scene;
  83708. var options = this._options;
  83709. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83710. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83711. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83712. this._isRunning = false;
  83713. this.onSuccessObservable.notifyObservers(this);
  83714. return;
  83715. }
  83716. // Apply current level of optimizations
  83717. var allDone = true;
  83718. var noOptimizationApplied = true;
  83719. for (var index = 0; index < options.optimizations.length; index++) {
  83720. var optimization = options.optimizations[index];
  83721. if (optimization.priority === this._currentPriorityLevel) {
  83722. noOptimizationApplied = false;
  83723. allDone = allDone && optimization.apply(scene, this);
  83724. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83725. }
  83726. }
  83727. // If no optimization was applied, this is a failure :(
  83728. if (noOptimizationApplied) {
  83729. this._isRunning = false;
  83730. this.onFailureObservable.notifyObservers(this);
  83731. return;
  83732. }
  83733. // If all optimizations were done, move to next level
  83734. if (allDone) {
  83735. this._currentPriorityLevel++;
  83736. }
  83737. // Let's the system running for a specific amount of time before checking FPS
  83738. scene.executeWhenReady(function () {
  83739. setTimeout(function () {
  83740. _this._checkCurrentState();
  83741. }, _this._trackerDuration);
  83742. });
  83743. };
  83744. /**
  83745. * Release all resources
  83746. */
  83747. SceneOptimizer.prototype.dispose = function () {
  83748. this.stop();
  83749. this.onSuccessObservable.clear();
  83750. this.onFailureObservable.clear();
  83751. this.onNewOptimizationAppliedObservable.clear();
  83752. if (this._sceneDisposeObserver) {
  83753. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83754. }
  83755. };
  83756. /**
  83757. * Helper function to create a SceneOptimizer with one single line of code
  83758. * @param scene defines the scene to work on
  83759. * @param options defines the options to use with the SceneOptimizer
  83760. * @param onSuccess defines a callback to call on success
  83761. * @param onFailure defines a callback to call on failure
  83762. * @returns the new SceneOptimizer object
  83763. */
  83764. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83765. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83766. if (onSuccess) {
  83767. optimizer.onSuccessObservable.add(function () {
  83768. onSuccess();
  83769. });
  83770. }
  83771. if (onFailure) {
  83772. optimizer.onFailureObservable.add(function () {
  83773. onFailure();
  83774. });
  83775. }
  83776. optimizer.start();
  83777. return optimizer;
  83778. };
  83779. return SceneOptimizer;
  83780. }());
  83781. BABYLON.SceneOptimizer = SceneOptimizer;
  83782. })(BABYLON || (BABYLON = {}));
  83783. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83784. var BABYLON;
  83785. (function (BABYLON) {
  83786. var OutlineRenderer = /** @class */ (function () {
  83787. function OutlineRenderer(scene) {
  83788. this.zOffset = 1;
  83789. this._scene = scene;
  83790. }
  83791. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83792. var _this = this;
  83793. if (useOverlay === void 0) { useOverlay = false; }
  83794. var scene = this._scene;
  83795. var engine = this._scene.getEngine();
  83796. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83797. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83798. return;
  83799. }
  83800. var mesh = subMesh.getRenderingMesh();
  83801. var material = subMesh.getMaterial();
  83802. if (!material || !scene.activeCamera) {
  83803. return;
  83804. }
  83805. engine.enableEffect(this._effect);
  83806. // Logarithmic depth
  83807. if (material.useLogarithmicDepth) {
  83808. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83809. }
  83810. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83811. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83812. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83813. // Bones
  83814. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83815. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83816. }
  83817. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83818. // Alpha test
  83819. if (material && material.needAlphaTesting()) {
  83820. var alphaTexture = material.getAlphaTestTexture();
  83821. if (alphaTexture) {
  83822. this._effect.setTexture("diffuseSampler", alphaTexture);
  83823. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83824. }
  83825. }
  83826. engine.setZOffset(-this.zOffset);
  83827. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83828. engine.setZOffset(0);
  83829. };
  83830. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83831. var defines = [];
  83832. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83833. var mesh = subMesh.getMesh();
  83834. var material = subMesh.getMaterial();
  83835. if (material) {
  83836. // Alpha test
  83837. if (material.needAlphaTesting()) {
  83838. defines.push("#define ALPHATEST");
  83839. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83840. attribs.push(BABYLON.VertexBuffer.UVKind);
  83841. defines.push("#define UV1");
  83842. }
  83843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83845. defines.push("#define UV2");
  83846. }
  83847. }
  83848. //Logarithmic depth
  83849. if (material.useLogarithmicDepth) {
  83850. defines.push("#define LOGARITHMICDEPTH");
  83851. }
  83852. }
  83853. // Bones
  83854. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83857. if (mesh.numBoneInfluencers > 4) {
  83858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83860. }
  83861. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83862. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83863. }
  83864. else {
  83865. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83866. }
  83867. // Instances
  83868. if (useInstances) {
  83869. defines.push("#define INSTANCES");
  83870. attribs.push("world0");
  83871. attribs.push("world1");
  83872. attribs.push("world2");
  83873. attribs.push("world3");
  83874. }
  83875. // Get correct effect
  83876. var join = defines.join("\n");
  83877. if (this._cachedDefines !== join) {
  83878. this._cachedDefines = join;
  83879. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83880. }
  83881. return this._effect.isReady();
  83882. };
  83883. return OutlineRenderer;
  83884. }());
  83885. BABYLON.OutlineRenderer = OutlineRenderer;
  83886. })(BABYLON || (BABYLON = {}));
  83887. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83888. var BABYLON;
  83889. (function (BABYLON) {
  83890. var FaceAdjacencies = /** @class */ (function () {
  83891. function FaceAdjacencies() {
  83892. this.edges = new Array();
  83893. this.edgesConnectedCount = 0;
  83894. }
  83895. return FaceAdjacencies;
  83896. }());
  83897. var EdgesRenderer = /** @class */ (function () {
  83898. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83899. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83900. if (epsilon === void 0) { epsilon = 0.95; }
  83901. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83902. this.edgesWidthScalerForOrthographic = 1000.0;
  83903. this.edgesWidthScalerForPerspective = 50.0;
  83904. this._linesPositions = new Array();
  83905. this._linesNormals = new Array();
  83906. this._linesIndices = new Array();
  83907. this._buffers = {};
  83908. this._checkVerticesInsteadOfIndices = false;
  83909. this._source = source;
  83910. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83911. this._epsilon = epsilon;
  83912. this._prepareRessources();
  83913. this._generateEdgesLines();
  83914. }
  83915. EdgesRenderer.prototype._prepareRessources = function () {
  83916. if (this._lineShader) {
  83917. return;
  83918. }
  83919. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83920. attributes: ["position", "normal"],
  83921. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83922. });
  83923. this._lineShader.disableDepthWrite = true;
  83924. this._lineShader.backFaceCulling = false;
  83925. };
  83926. EdgesRenderer.prototype._rebuild = function () {
  83927. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83928. if (buffer) {
  83929. buffer._rebuild();
  83930. }
  83931. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83932. if (buffer) {
  83933. buffer._rebuild();
  83934. }
  83935. var scene = this._source.getScene();
  83936. var engine = scene.getEngine();
  83937. this._ib = engine.createIndexBuffer(this._linesIndices);
  83938. };
  83939. EdgesRenderer.prototype.dispose = function () {
  83940. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83941. if (buffer) {
  83942. buffer.dispose();
  83943. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83944. }
  83945. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83946. if (buffer) {
  83947. buffer.dispose();
  83948. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83949. }
  83950. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83951. this._lineShader.dispose();
  83952. };
  83953. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83954. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83955. return 0;
  83956. }
  83957. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83958. return 1;
  83959. }
  83960. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83961. return 2;
  83962. }
  83963. return -1;
  83964. };
  83965. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83966. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83967. return 0;
  83968. }
  83969. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83970. return 1;
  83971. }
  83972. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83973. return 2;
  83974. }
  83975. return -1;
  83976. };
  83977. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83978. var needToCreateLine;
  83979. if (edge === undefined) {
  83980. needToCreateLine = true;
  83981. }
  83982. else {
  83983. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83984. needToCreateLine = dotProduct < this._epsilon;
  83985. }
  83986. if (needToCreateLine) {
  83987. var offset = this._linesPositions.length / 3;
  83988. var normal = p0.subtract(p1);
  83989. normal.normalize();
  83990. // Positions
  83991. this._linesPositions.push(p0.x);
  83992. this._linesPositions.push(p0.y);
  83993. this._linesPositions.push(p0.z);
  83994. this._linesPositions.push(p0.x);
  83995. this._linesPositions.push(p0.y);
  83996. this._linesPositions.push(p0.z);
  83997. this._linesPositions.push(p1.x);
  83998. this._linesPositions.push(p1.y);
  83999. this._linesPositions.push(p1.z);
  84000. this._linesPositions.push(p1.x);
  84001. this._linesPositions.push(p1.y);
  84002. this._linesPositions.push(p1.z);
  84003. // Normals
  84004. this._linesNormals.push(p1.x);
  84005. this._linesNormals.push(p1.y);
  84006. this._linesNormals.push(p1.z);
  84007. this._linesNormals.push(-1);
  84008. this._linesNormals.push(p1.x);
  84009. this._linesNormals.push(p1.y);
  84010. this._linesNormals.push(p1.z);
  84011. this._linesNormals.push(1);
  84012. this._linesNormals.push(p0.x);
  84013. this._linesNormals.push(p0.y);
  84014. this._linesNormals.push(p0.z);
  84015. this._linesNormals.push(-1);
  84016. this._linesNormals.push(p0.x);
  84017. this._linesNormals.push(p0.y);
  84018. this._linesNormals.push(p0.z);
  84019. this._linesNormals.push(1);
  84020. // Indices
  84021. this._linesIndices.push(offset);
  84022. this._linesIndices.push(offset + 1);
  84023. this._linesIndices.push(offset + 2);
  84024. this._linesIndices.push(offset);
  84025. this._linesIndices.push(offset + 2);
  84026. this._linesIndices.push(offset + 3);
  84027. }
  84028. };
  84029. EdgesRenderer.prototype._generateEdgesLines = function () {
  84030. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84031. var indices = this._source.getIndices();
  84032. if (!indices || !positions) {
  84033. return;
  84034. }
  84035. // First let's find adjacencies
  84036. var adjacencies = new Array();
  84037. var faceNormals = new Array();
  84038. var index;
  84039. var faceAdjacencies;
  84040. // Prepare faces
  84041. for (index = 0; index < indices.length; index += 3) {
  84042. faceAdjacencies = new FaceAdjacencies();
  84043. var p0Index = indices[index];
  84044. var p1Index = indices[index + 1];
  84045. var p2Index = indices[index + 2];
  84046. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84047. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84048. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84049. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84050. faceNormal.normalize();
  84051. faceNormals.push(faceNormal);
  84052. adjacencies.push(faceAdjacencies);
  84053. }
  84054. // Scan
  84055. for (index = 0; index < adjacencies.length; index++) {
  84056. faceAdjacencies = adjacencies[index];
  84057. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84058. var otherFaceAdjacencies = adjacencies[otherIndex];
  84059. if (faceAdjacencies.edgesConnectedCount === 3) {
  84060. break;
  84061. }
  84062. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84063. continue;
  84064. }
  84065. var otherP0 = indices[otherIndex * 3];
  84066. var otherP1 = indices[otherIndex * 3 + 1];
  84067. var otherP2 = indices[otherIndex * 3 + 2];
  84068. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84069. var otherEdgeIndex = 0;
  84070. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84071. continue;
  84072. }
  84073. switch (edgeIndex) {
  84074. case 0:
  84075. if (this._checkVerticesInsteadOfIndices) {
  84076. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84077. }
  84078. else {
  84079. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84080. }
  84081. break;
  84082. case 1:
  84083. if (this._checkVerticesInsteadOfIndices) {
  84084. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84085. }
  84086. else {
  84087. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84088. }
  84089. break;
  84090. case 2:
  84091. if (this._checkVerticesInsteadOfIndices) {
  84092. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84093. }
  84094. else {
  84095. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84096. }
  84097. break;
  84098. }
  84099. if (otherEdgeIndex === -1) {
  84100. continue;
  84101. }
  84102. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84103. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84104. faceAdjacencies.edgesConnectedCount++;
  84105. otherFaceAdjacencies.edgesConnectedCount++;
  84106. if (faceAdjacencies.edgesConnectedCount === 3) {
  84107. break;
  84108. }
  84109. }
  84110. }
  84111. }
  84112. // Create lines
  84113. for (index = 0; index < adjacencies.length; index++) {
  84114. // 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
  84115. var current = adjacencies[index];
  84116. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84117. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84118. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84119. }
  84120. // Merge into a single mesh
  84121. var engine = this._source.getScene().getEngine();
  84122. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84123. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84124. this._ib = engine.createIndexBuffer(this._linesIndices);
  84125. this._indicesCount = this._linesIndices.length;
  84126. };
  84127. EdgesRenderer.prototype.render = function () {
  84128. var scene = this._source.getScene();
  84129. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84130. return;
  84131. }
  84132. var engine = scene.getEngine();
  84133. this._lineShader._preBind();
  84134. // VBOs
  84135. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84136. scene.resetCachedMaterial();
  84137. this._lineShader.setColor4("color", this._source.edgesColor);
  84138. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84139. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84140. }
  84141. else {
  84142. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84143. }
  84144. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84145. this._lineShader.bind(this._source.getWorldMatrix());
  84146. // Draw order
  84147. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84148. this._lineShader.unbind();
  84149. engine.setDepthWrite(true);
  84150. };
  84151. return EdgesRenderer;
  84152. }());
  84153. BABYLON.EdgesRenderer = EdgesRenderer;
  84154. })(BABYLON || (BABYLON = {}));
  84155. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84156. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84157. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84158. s = arguments[i];
  84159. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84160. t[p] = s[p];
  84161. }
  84162. return t;
  84163. };
  84164. var BABYLON;
  84165. (function (BABYLON) {
  84166. /**
  84167. * The effect layer Helps adding post process effect blended with the main pass.
  84168. *
  84169. * This can be for instance use to generate glow or higlight effects on the scene.
  84170. *
  84171. * The effect layer class can not be used directly and is intented to inherited from to be
  84172. * customized per effects.
  84173. */
  84174. var EffectLayer = /** @class */ (function () {
  84175. /**
  84176. * Instantiates a new effect Layer and references it in the scene.
  84177. * @param name The name of the layer
  84178. * @param scene The scene to use the layer in
  84179. */
  84180. function EffectLayer(
  84181. /** The Friendly of the effect in the scene */
  84182. name, scene) {
  84183. this.name = name;
  84184. this._vertexBuffers = {};
  84185. this._maxSize = 0;
  84186. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84187. this._shouldRender = true;
  84188. this._postProcesses = [];
  84189. this._textures = [];
  84190. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84191. /**
  84192. * The clear color of the texture used to generate the glow map.
  84193. */
  84194. this.neutralColor = new BABYLON.Color4();
  84195. /**
  84196. * Specifies wether the highlight layer is enabled or not.
  84197. */
  84198. this.isEnabled = true;
  84199. /**
  84200. * An event triggered when the effect layer has been disposed.
  84201. */
  84202. this.onDisposeObservable = new BABYLON.Observable();
  84203. /**
  84204. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84205. */
  84206. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84207. /**
  84208. * An event triggered when the generated texture is being merged in the scene.
  84209. */
  84210. this.onBeforeComposeObservable = new BABYLON.Observable();
  84211. /**
  84212. * An event triggered when the generated texture has been merged in the scene.
  84213. */
  84214. this.onAfterComposeObservable = new BABYLON.Observable();
  84215. /**
  84216. * An event triggered when the efffect layer changes its size.
  84217. */
  84218. this.onSizeChangedObservable = new BABYLON.Observable();
  84219. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84220. this._engine = scene.getEngine();
  84221. this._maxSize = this._engine.getCaps().maxTextureSize;
  84222. this._scene.effectLayers.push(this);
  84223. // Generate Buffers
  84224. this._generateIndexBuffer();
  84225. this._genrateVertexBuffer();
  84226. }
  84227. Object.defineProperty(EffectLayer.prototype, "camera", {
  84228. /**
  84229. * Gets the camera attached to the layer.
  84230. */
  84231. get: function () {
  84232. return this._effectLayerOptions.camera;
  84233. },
  84234. enumerable: true,
  84235. configurable: true
  84236. });
  84237. /**
  84238. * Initializes the effect layer with the required options.
  84239. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84240. */
  84241. EffectLayer.prototype._init = function (options) {
  84242. // Adapt options
  84243. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84244. this._setMainTextureSize();
  84245. this._createMainTexture();
  84246. this._createTextureAndPostProcesses();
  84247. this._mergeEffect = this._createMergeEffect();
  84248. };
  84249. /**
  84250. * Generates the index buffer of the full screen quad blending to the main canvas.
  84251. */
  84252. EffectLayer.prototype._generateIndexBuffer = function () {
  84253. // Indices
  84254. var indices = [];
  84255. indices.push(0);
  84256. indices.push(1);
  84257. indices.push(2);
  84258. indices.push(0);
  84259. indices.push(2);
  84260. indices.push(3);
  84261. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84262. };
  84263. /**
  84264. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84265. */
  84266. EffectLayer.prototype._genrateVertexBuffer = function () {
  84267. // VBO
  84268. var vertices = [];
  84269. vertices.push(1, 1);
  84270. vertices.push(-1, 1);
  84271. vertices.push(-1, -1);
  84272. vertices.push(1, -1);
  84273. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84275. };
  84276. /**
  84277. * Sets the main texture desired size which is the closest power of two
  84278. * of the engine canvas size.
  84279. */
  84280. EffectLayer.prototype._setMainTextureSize = function () {
  84281. if (this._effectLayerOptions.mainTextureFixedSize) {
  84282. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84283. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84284. }
  84285. else {
  84286. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84287. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84288. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84289. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84290. }
  84291. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84292. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84293. };
  84294. /**
  84295. * Creates the main texture for the effect layer.
  84296. */
  84297. EffectLayer.prototype._createMainTexture = function () {
  84298. var _this = this;
  84299. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84300. width: this._mainTextureDesiredSize.width,
  84301. height: this._mainTextureDesiredSize.height
  84302. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84303. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84304. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84305. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84306. this._mainTexture.anisotropicFilteringLevel = 1;
  84307. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84308. this._mainTexture.renderParticles = false;
  84309. this._mainTexture.renderList = null;
  84310. this._mainTexture.ignoreCameraViewport = true;
  84311. // Custom render function
  84312. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84313. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84314. var index;
  84315. var engine = _this._scene.getEngine();
  84316. if (depthOnlySubMeshes.length) {
  84317. engine.setColorWrite(false);
  84318. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84319. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84320. }
  84321. engine.setColorWrite(true);
  84322. }
  84323. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84324. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84325. }
  84326. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84327. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84328. }
  84329. for (index = 0; index < transparentSubMeshes.length; index++) {
  84330. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84331. }
  84332. };
  84333. this._mainTexture.onClearObservable.add(function (engine) {
  84334. engine.clear(_this.neutralColor, true, true, true);
  84335. });
  84336. };
  84337. /**
  84338. * Checks for the readiness of the element composing the layer.
  84339. * @param subMesh the mesh to check for
  84340. * @param useInstances specify wether or not to use instances to render the mesh
  84341. * @param emissiveTexture the associated emissive texture used to generate the glow
  84342. * @return true if ready otherwise, false
  84343. */
  84344. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84345. var material = subMesh.getMaterial();
  84346. if (!material) {
  84347. return false;
  84348. }
  84349. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84350. return false;
  84351. }
  84352. var defines = [];
  84353. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84354. var mesh = subMesh.getMesh();
  84355. var uv1 = false;
  84356. var uv2 = false;
  84357. // Alpha test
  84358. if (material && material.needAlphaTesting()) {
  84359. var alphaTexture = material.getAlphaTestTexture();
  84360. if (alphaTexture) {
  84361. defines.push("#define ALPHATEST");
  84362. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84363. alphaTexture.coordinatesIndex === 1) {
  84364. defines.push("#define DIFFUSEUV2");
  84365. uv2 = true;
  84366. }
  84367. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84368. defines.push("#define DIFFUSEUV1");
  84369. uv1 = true;
  84370. }
  84371. }
  84372. }
  84373. // Emissive
  84374. if (emissiveTexture) {
  84375. defines.push("#define EMISSIVE");
  84376. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84377. emissiveTexture.coordinatesIndex === 1) {
  84378. defines.push("#define EMISSIVEUV2");
  84379. uv2 = true;
  84380. }
  84381. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84382. defines.push("#define EMISSIVEUV1");
  84383. uv1 = true;
  84384. }
  84385. }
  84386. if (uv1) {
  84387. attribs.push(BABYLON.VertexBuffer.UVKind);
  84388. defines.push("#define UV1");
  84389. }
  84390. if (uv2) {
  84391. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84392. defines.push("#define UV2");
  84393. }
  84394. // Bones
  84395. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84396. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84397. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84398. if (mesh.numBoneInfluencers > 4) {
  84399. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84400. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84401. }
  84402. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84403. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84404. }
  84405. else {
  84406. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84407. }
  84408. // Instances
  84409. if (useInstances) {
  84410. defines.push("#define INSTANCES");
  84411. attribs.push("world0");
  84412. attribs.push("world1");
  84413. attribs.push("world2");
  84414. attribs.push("world3");
  84415. }
  84416. // Get correct effect
  84417. var join = defines.join("\n");
  84418. if (this._cachedDefines !== join) {
  84419. this._cachedDefines = join;
  84420. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84421. }
  84422. return this._effectLayerMapGenerationEffect.isReady();
  84423. };
  84424. /**
  84425. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84426. */
  84427. EffectLayer.prototype.render = function () {
  84428. var currentEffect = this._mergeEffect;
  84429. // Check
  84430. if (!currentEffect.isReady())
  84431. return;
  84432. for (var i = 0; i < this._postProcesses.length; i++) {
  84433. if (!this._postProcesses[i].isReady()) {
  84434. return;
  84435. }
  84436. }
  84437. var engine = this._scene.getEngine();
  84438. this.onBeforeComposeObservable.notifyObservers(this);
  84439. // Render
  84440. engine.enableEffect(currentEffect);
  84441. engine.setState(false);
  84442. // VBOs
  84443. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84444. // Cache
  84445. var previousAlphaMode = engine.getAlphaMode();
  84446. // Go Blend.
  84447. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84448. // Blends the map on the main canvas.
  84449. this._internalRender(currentEffect);
  84450. // Restore Alpha
  84451. engine.setAlphaMode(previousAlphaMode);
  84452. this.onAfterComposeObservable.notifyObservers(this);
  84453. // Handle size changes.
  84454. var size = this._mainTexture.getSize();
  84455. this._setMainTextureSize();
  84456. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84457. // Recreate RTT and post processes on size change.
  84458. this.onSizeChangedObservable.notifyObservers(this);
  84459. this._disposeTextureAndPostProcesses();
  84460. this._createMainTexture();
  84461. this._createTextureAndPostProcesses();
  84462. }
  84463. };
  84464. /**
  84465. * Determine if a given mesh will be used in the current effect.
  84466. * @param mesh mesh to test
  84467. * @returns true if the mesh will be used
  84468. */
  84469. EffectLayer.prototype.hasMesh = function (mesh) {
  84470. return true;
  84471. };
  84472. /**
  84473. * Returns true if the layer contains information to display, otherwise false.
  84474. * @returns true if the glow layer should be rendered
  84475. */
  84476. EffectLayer.prototype.shouldRender = function () {
  84477. return this.isEnabled && this._shouldRender;
  84478. };
  84479. /**
  84480. * Returns true if the mesh should render, otherwise false.
  84481. * @param mesh The mesh to render
  84482. * @returns true if it should render otherwise false
  84483. */
  84484. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84485. return true;
  84486. };
  84487. /**
  84488. * Returns true if the mesh should render, otherwise false.
  84489. * @param mesh The mesh to render
  84490. * @returns true if it should render otherwise false
  84491. */
  84492. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84493. return true;
  84494. };
  84495. /**
  84496. * Renders the submesh passed in parameter to the generation map.
  84497. */
  84498. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84499. var _this = this;
  84500. if (!this.shouldRender()) {
  84501. return;
  84502. }
  84503. var material = subMesh.getMaterial();
  84504. var mesh = subMesh.getRenderingMesh();
  84505. var scene = this._scene;
  84506. var engine = scene.getEngine();
  84507. if (!material) {
  84508. return;
  84509. }
  84510. // Do not block in blend mode.
  84511. if (material.needAlphaBlendingForMesh(mesh)) {
  84512. return;
  84513. }
  84514. // Culling
  84515. engine.setState(material.backFaceCulling);
  84516. // Managing instances
  84517. var batch = mesh._getInstancesRenderList(subMesh._id);
  84518. if (batch.mustReturn) {
  84519. return;
  84520. }
  84521. // Early Exit per mesh
  84522. if (!this._shouldRenderMesh(mesh)) {
  84523. return;
  84524. }
  84525. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84526. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84527. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84528. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84529. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84530. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84531. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84532. // Alpha test
  84533. if (material && material.needAlphaTesting()) {
  84534. var alphaTexture = material.getAlphaTestTexture();
  84535. if (alphaTexture) {
  84536. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84537. var textureMatrix = alphaTexture.getTextureMatrix();
  84538. if (textureMatrix) {
  84539. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84540. }
  84541. }
  84542. }
  84543. // Glow emissive only
  84544. if (this._emissiveTextureAndColor.texture) {
  84545. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84546. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84547. }
  84548. // Bones
  84549. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84550. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84551. }
  84552. // Draw
  84553. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84554. }
  84555. else {
  84556. // Need to reset refresh rate of the shadowMap
  84557. this._mainTexture.resetRefreshCounter();
  84558. }
  84559. };
  84560. /**
  84561. * Rebuild the required buffers.
  84562. * @ignore Internal use only.
  84563. */
  84564. EffectLayer.prototype._rebuild = function () {
  84565. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84566. if (vb) {
  84567. vb._rebuild();
  84568. }
  84569. this._generateIndexBuffer();
  84570. };
  84571. /**
  84572. * Dispose only the render target textures and post process.
  84573. */
  84574. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84575. this._mainTexture.dispose();
  84576. for (var i = 0; i < this._postProcesses.length; i++) {
  84577. if (this._postProcesses[i]) {
  84578. this._postProcesses[i].dispose();
  84579. }
  84580. }
  84581. this._postProcesses = [];
  84582. for (var i = 0; i < this._textures.length; i++) {
  84583. if (this._textures[i]) {
  84584. this._textures[i].dispose();
  84585. }
  84586. }
  84587. this._textures = [];
  84588. };
  84589. /**
  84590. * Dispose the highlight layer and free resources.
  84591. */
  84592. EffectLayer.prototype.dispose = function () {
  84593. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84594. if (vertexBuffer) {
  84595. vertexBuffer.dispose();
  84596. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84597. }
  84598. if (this._indexBuffer) {
  84599. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84600. this._indexBuffer = null;
  84601. }
  84602. // Clean textures and post processes
  84603. this._disposeTextureAndPostProcesses();
  84604. // Remove from scene
  84605. var index = this._scene.effectLayers.indexOf(this, 0);
  84606. if (index > -1) {
  84607. this._scene.effectLayers.splice(index, 1);
  84608. }
  84609. // Callback
  84610. this.onDisposeObservable.notifyObservers(this);
  84611. this.onDisposeObservable.clear();
  84612. this.onBeforeRenderMainTextureObservable.clear();
  84613. this.onBeforeComposeObservable.clear();
  84614. this.onAfterComposeObservable.clear();
  84615. this.onSizeChangedObservable.clear();
  84616. };
  84617. return EffectLayer;
  84618. }());
  84619. BABYLON.EffectLayer = EffectLayer;
  84620. })(BABYLON || (BABYLON = {}));
  84621. //# sourceMappingURL=babylon.effectLayer.js.map
  84622. var BABYLON;
  84623. (function (BABYLON) {
  84624. /**
  84625. * Special Glow Blur post process only blurring the alpha channel
  84626. * It enforces keeping the most luminous color in the color channel.
  84627. */
  84628. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84629. __extends(GlowBlurPostProcess, _super);
  84630. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84632. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84633. _this.direction = direction;
  84634. _this.kernel = kernel;
  84635. _this.onApplyObservable.add(function (effect) {
  84636. effect.setFloat2("screenSize", _this.width, _this.height);
  84637. effect.setVector2("direction", _this.direction);
  84638. effect.setFloat("blurWidth", _this.kernel);
  84639. });
  84640. return _this;
  84641. }
  84642. return GlowBlurPostProcess;
  84643. }(BABYLON.PostProcess));
  84644. /**
  84645. * The highlight layer Helps adding a glow effect around a mesh.
  84646. *
  84647. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84648. * glowy meshes to your scene.
  84649. *
  84650. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84651. */
  84652. var HighlightLayer = /** @class */ (function (_super) {
  84653. __extends(HighlightLayer, _super);
  84654. /**
  84655. * Instantiates a new highlight Layer and references it to the scene..
  84656. * @param name The name of the layer
  84657. * @param scene The scene to use the layer in
  84658. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84659. */
  84660. function HighlightLayer(name, scene, options) {
  84661. var _this = _super.call(this, name, scene) || this;
  84662. _this.name = name;
  84663. /**
  84664. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84665. */
  84666. _this.innerGlow = true;
  84667. /**
  84668. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84669. */
  84670. _this.outerGlow = true;
  84671. /**
  84672. * An event triggered when the highlight layer is being blurred.
  84673. */
  84674. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84675. /**
  84676. * An event triggered when the highlight layer has been blurred.
  84677. */
  84678. _this.onAfterBlurObservable = new BABYLON.Observable();
  84679. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84680. _this._meshes = {};
  84681. _this._excludedMeshes = {};
  84682. _this.neutralColor = HighlightLayer.NeutralColor;
  84683. // Warn on stencil
  84684. if (!_this._engine.isStencilEnable) {
  84685. 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 }");
  84686. }
  84687. // Adapt options
  84688. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84689. // Initialize the layer
  84690. _this._init({
  84691. alphaBlendingMode: _this._options.alphaBlendingMode,
  84692. camera: _this._options.camera,
  84693. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84694. mainTextureRatio: _this._options.mainTextureRatio
  84695. });
  84696. // Do not render as long as no meshes have been added
  84697. _this._shouldRender = false;
  84698. return _this;
  84699. }
  84700. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84701. /**
  84702. * Gets the horizontal size of the blur.
  84703. */
  84704. get: function () {
  84705. return this._horizontalBlurPostprocess.kernel;
  84706. },
  84707. /**
  84708. * Specifies the horizontal size of the blur.
  84709. */
  84710. set: function (value) {
  84711. this._horizontalBlurPostprocess.kernel = value;
  84712. },
  84713. enumerable: true,
  84714. configurable: true
  84715. });
  84716. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84717. /**
  84718. * Gets the vertical size of the blur.
  84719. */
  84720. get: function () {
  84721. return this._verticalBlurPostprocess.kernel;
  84722. },
  84723. /**
  84724. * Specifies the vertical size of the blur.
  84725. */
  84726. set: function (value) {
  84727. this._verticalBlurPostprocess.kernel = value;
  84728. },
  84729. enumerable: true,
  84730. configurable: true
  84731. });
  84732. /**
  84733. * Get the effect name of the layer.
  84734. * @return The effect name
  84735. */
  84736. HighlightLayer.prototype.getEffectName = function () {
  84737. return HighlightLayer.EffectName;
  84738. };
  84739. /**
  84740. * Create the merge effect. This is the shader use to blit the information back
  84741. * to the main canvas at the end of the scene rendering.
  84742. */
  84743. HighlightLayer.prototype._createMergeEffect = function () {
  84744. // Effect
  84745. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84746. };
  84747. /**
  84748. * Creates the render target textures and post processes used in the highlight layer.
  84749. */
  84750. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84751. var _this = this;
  84752. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84753. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84754. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84755. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84756. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84757. width: blurTextureWidth,
  84758. height: blurTextureHeight
  84759. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84760. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84761. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84762. this._blurTexture.anisotropicFilteringLevel = 16;
  84763. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84764. this._blurTexture.renderParticles = false;
  84765. this._blurTexture.ignoreCameraViewport = true;
  84766. this._textures = [this._blurTexture];
  84767. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84768. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84769. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84770. effect.setTexture("textureSampler", _this._mainTexture);
  84771. });
  84772. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84773. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84774. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84775. });
  84776. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84777. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84778. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84779. });
  84780. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84781. }
  84782. else {
  84783. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84784. width: blurTextureWidth,
  84785. height: blurTextureHeight
  84786. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84787. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84788. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84789. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84790. effect.setTexture("textureSampler", _this._mainTexture);
  84791. });
  84792. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84793. width: blurTextureWidth,
  84794. height: blurTextureHeight
  84795. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84796. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84797. }
  84798. this._mainTexture.onAfterUnbindObservable.add(function () {
  84799. _this.onBeforeBlurObservable.notifyObservers(_this);
  84800. var internalTexture = _this._blurTexture.getInternalTexture();
  84801. if (internalTexture) {
  84802. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84803. }
  84804. _this.onAfterBlurObservable.notifyObservers(_this);
  84805. });
  84806. // Prevent autoClear.
  84807. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84808. };
  84809. /**
  84810. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84811. */
  84812. HighlightLayer.prototype.needStencil = function () {
  84813. return true;
  84814. };
  84815. /**
  84816. * Checks for the readiness of the element composing the layer.
  84817. * @param subMesh the mesh to check for
  84818. * @param useInstances specify wether or not to use instances to render the mesh
  84819. * @param emissiveTexture the associated emissive texture used to generate the glow
  84820. * @return true if ready otherwise, false
  84821. */
  84822. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84823. var material = subMesh.getMaterial();
  84824. var mesh = subMesh.getRenderingMesh();
  84825. if (!material || !mesh || !this._meshes) {
  84826. return false;
  84827. }
  84828. var emissiveTexture = null;
  84829. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84830. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84831. emissiveTexture = material.emissiveTexture;
  84832. }
  84833. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84834. };
  84835. /**
  84836. * Implementation specific of rendering the generating effect on the main canvas.
  84837. * @param effect The effect used to render through
  84838. */
  84839. HighlightLayer.prototype._internalRender = function (effect) {
  84840. // Texture
  84841. effect.setTexture("textureSampler", this._blurTexture);
  84842. // Cache
  84843. var engine = this._engine;
  84844. var previousStencilBuffer = engine.getStencilBuffer();
  84845. var previousStencilFunction = engine.getStencilFunction();
  84846. var previousStencilMask = engine.getStencilMask();
  84847. var previousStencilOperationPass = engine.getStencilOperationPass();
  84848. var previousStencilOperationFail = engine.getStencilOperationFail();
  84849. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84850. var previousStencilReference = engine.getStencilFunctionReference();
  84851. // Stencil operations
  84852. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84853. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84854. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84855. // Draw order
  84856. engine.setStencilMask(0x00);
  84857. engine.setStencilBuffer(true);
  84858. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84859. // 2 passes inner outer
  84860. if (this.outerGlow) {
  84861. effect.setFloat("offset", 0);
  84862. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84864. }
  84865. if (this.innerGlow) {
  84866. effect.setFloat("offset", 1);
  84867. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84868. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84869. }
  84870. // Restore Cache
  84871. engine.setStencilFunction(previousStencilFunction);
  84872. engine.setStencilMask(previousStencilMask);
  84873. engine.setStencilBuffer(previousStencilBuffer);
  84874. engine.setStencilOperationPass(previousStencilOperationPass);
  84875. engine.setStencilOperationFail(previousStencilOperationFail);
  84876. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84877. engine.setStencilFunctionReference(previousStencilReference);
  84878. };
  84879. /**
  84880. * Returns true if the layer contains information to display, otherwise false.
  84881. */
  84882. HighlightLayer.prototype.shouldRender = function () {
  84883. if (_super.prototype.shouldRender.call(this)) {
  84884. return this._meshes ? true : false;
  84885. }
  84886. return false;
  84887. };
  84888. /**
  84889. * Returns true if the mesh should render, otherwise false.
  84890. * @param mesh The mesh to render
  84891. * @returns true if it should render otherwise false
  84892. */
  84893. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84894. // Excluded Mesh
  84895. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84896. return false;
  84897. }
  84898. ;
  84899. return true;
  84900. };
  84901. /**
  84902. * Sets the required values for both the emissive texture and and the main color.
  84903. */
  84904. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84905. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84906. if (highlightLayerMesh) {
  84907. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84908. }
  84909. else {
  84910. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84911. }
  84912. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84913. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84914. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84915. }
  84916. else {
  84917. this._emissiveTextureAndColor.texture = null;
  84918. }
  84919. };
  84920. /**
  84921. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84922. * @param mesh The mesh to exclude from the highlight layer
  84923. */
  84924. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84925. if (!this._excludedMeshes) {
  84926. return;
  84927. }
  84928. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84929. if (!meshExcluded) {
  84930. this._excludedMeshes[mesh.uniqueId] = {
  84931. mesh: mesh,
  84932. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84933. mesh.getEngine().setStencilBuffer(false);
  84934. }),
  84935. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84936. mesh.getEngine().setStencilBuffer(true);
  84937. }),
  84938. };
  84939. }
  84940. };
  84941. /**
  84942. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84943. * @param mesh The mesh to highlight
  84944. */
  84945. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84946. if (!this._excludedMeshes) {
  84947. return;
  84948. }
  84949. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84950. if (meshExcluded) {
  84951. if (meshExcluded.beforeRender) {
  84952. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84953. }
  84954. if (meshExcluded.afterRender) {
  84955. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84956. }
  84957. }
  84958. this._excludedMeshes[mesh.uniqueId] = null;
  84959. };
  84960. /**
  84961. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84962. * @param mesh mesh to test
  84963. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84964. */
  84965. HighlightLayer.prototype.hasMesh = function (mesh) {
  84966. if (!this._meshes) {
  84967. return false;
  84968. }
  84969. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84970. };
  84971. /**
  84972. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84973. * @param mesh The mesh to highlight
  84974. * @param color The color of the highlight
  84975. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84976. */
  84977. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84978. var _this = this;
  84979. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84980. if (!this._meshes) {
  84981. return;
  84982. }
  84983. var meshHighlight = this._meshes[mesh.uniqueId];
  84984. if (meshHighlight) {
  84985. meshHighlight.color = color;
  84986. }
  84987. else {
  84988. this._meshes[mesh.uniqueId] = {
  84989. mesh: mesh,
  84990. color: color,
  84991. // Lambda required for capture due to Observable this context
  84992. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84993. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84994. _this._defaultStencilReference(mesh);
  84995. }
  84996. else {
  84997. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84998. }
  84999. }),
  85000. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85001. glowEmissiveOnly: glowEmissiveOnly
  85002. };
  85003. }
  85004. this._shouldRender = true;
  85005. };
  85006. /**
  85007. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85008. * @param mesh The mesh to highlight
  85009. */
  85010. HighlightLayer.prototype.removeMesh = function (mesh) {
  85011. if (!this._meshes) {
  85012. return;
  85013. }
  85014. var meshHighlight = this._meshes[mesh.uniqueId];
  85015. if (meshHighlight) {
  85016. if (meshHighlight.observerHighlight) {
  85017. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85018. }
  85019. if (meshHighlight.observerDefault) {
  85020. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85021. }
  85022. delete this._meshes[mesh.uniqueId];
  85023. }
  85024. this._shouldRender = false;
  85025. for (var meshHighlightToCheck in this._meshes) {
  85026. if (this._meshes[meshHighlightToCheck]) {
  85027. this._shouldRender = true;
  85028. break;
  85029. }
  85030. }
  85031. };
  85032. /**
  85033. * Force the stencil to the normal expected value for none glowing parts
  85034. */
  85035. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85036. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85037. };
  85038. /**
  85039. * Free any resources and references associated to a mesh.
  85040. * Internal use
  85041. * @param mesh The mesh to free.
  85042. */
  85043. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85044. this.removeMesh(mesh);
  85045. this.removeExcludedMesh(mesh);
  85046. };
  85047. /**
  85048. * Dispose the highlight layer and free resources.
  85049. */
  85050. HighlightLayer.prototype.dispose = function () {
  85051. if (this._meshes) {
  85052. // Clean mesh references
  85053. for (var id in this._meshes) {
  85054. var meshHighlight = this._meshes[id];
  85055. if (meshHighlight && meshHighlight.mesh) {
  85056. if (meshHighlight.observerHighlight) {
  85057. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85058. }
  85059. if (meshHighlight.observerDefault) {
  85060. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85061. }
  85062. }
  85063. }
  85064. this._meshes = null;
  85065. }
  85066. if (this._excludedMeshes) {
  85067. for (var id in this._excludedMeshes) {
  85068. var meshHighlight = this._excludedMeshes[id];
  85069. if (meshHighlight) {
  85070. if (meshHighlight.beforeRender) {
  85071. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85072. }
  85073. if (meshHighlight.afterRender) {
  85074. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85075. }
  85076. }
  85077. }
  85078. this._excludedMeshes = null;
  85079. }
  85080. _super.prototype.dispose.call(this);
  85081. };
  85082. /**
  85083. * Effect Name of the highlight layer.
  85084. */
  85085. HighlightLayer.EffectName = "HighlightLayer";
  85086. /**
  85087. * The neutral color used during the preparation of the glow effect.
  85088. * This is black by default as the blend operation is a blend operation.
  85089. */
  85090. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85091. /**
  85092. * Stencil value used for glowing meshes.
  85093. */
  85094. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85095. /**
  85096. * Stencil value used for the other meshes in the scene.
  85097. */
  85098. HighlightLayer.NormalMeshStencilReference = 0x01;
  85099. return HighlightLayer;
  85100. }(BABYLON.EffectLayer));
  85101. BABYLON.HighlightLayer = HighlightLayer;
  85102. })(BABYLON || (BABYLON = {}));
  85103. //# sourceMappingURL=babylon.highlightLayer.js.map
  85104. var BABYLON;
  85105. (function (BABYLON) {
  85106. /**
  85107. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85108. *
  85109. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85110. * glowy meshes to your scene.
  85111. *
  85112. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85113. */
  85114. var GlowLayer = /** @class */ (function (_super) {
  85115. __extends(GlowLayer, _super);
  85116. /**
  85117. * Instantiates a new glow Layer and references it to the scene.
  85118. * @param name The name of the layer
  85119. * @param scene The scene to use the layer in
  85120. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85121. */
  85122. function GlowLayer(name, scene, options) {
  85123. var _this = _super.call(this, name, scene) || this;
  85124. _this.name = name;
  85125. _this._intensity = 1.0;
  85126. _this._includedOnlyMeshes = [];
  85127. _this._excludedMeshes = [];
  85128. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85129. // Adapt options
  85130. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85131. // Initialize the layer
  85132. _this._init({
  85133. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85134. camera: _this._options.camera,
  85135. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85136. mainTextureRatio: _this._options.mainTextureRatio
  85137. });
  85138. return _this;
  85139. }
  85140. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85141. /**
  85142. * Gets the kernel size of the blur.
  85143. */
  85144. get: function () {
  85145. return this._horizontalBlurPostprocess1.kernel;
  85146. },
  85147. /**
  85148. * Sets the kernel size of the blur.
  85149. */
  85150. set: function (value) {
  85151. this._horizontalBlurPostprocess1.kernel = value;
  85152. this._verticalBlurPostprocess1.kernel = value;
  85153. this._horizontalBlurPostprocess2.kernel = value;
  85154. this._verticalBlurPostprocess2.kernel = value;
  85155. },
  85156. enumerable: true,
  85157. configurable: true
  85158. });
  85159. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85160. /**
  85161. * Gets the glow intensity.
  85162. */
  85163. get: function () {
  85164. return this._intensity;
  85165. },
  85166. /**
  85167. * Sets the glow intensity.
  85168. */
  85169. set: function (value) {
  85170. this._intensity = value;
  85171. },
  85172. enumerable: true,
  85173. configurable: true
  85174. });
  85175. /**
  85176. * Get the effect name of the layer.
  85177. * @return The effect name
  85178. */
  85179. GlowLayer.prototype.getEffectName = function () {
  85180. return GlowLayer.EffectName;
  85181. };
  85182. /**
  85183. * Create the merge effect. This is the shader use to blit the information back
  85184. * to the main canvas at the end of the scene rendering.
  85185. */
  85186. GlowLayer.prototype._createMergeEffect = function () {
  85187. // Effect
  85188. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85189. };
  85190. /**
  85191. * Creates the render target textures and post processes used in the glow layer.
  85192. */
  85193. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85194. var _this = this;
  85195. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85196. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85197. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85198. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85199. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85200. width: blurTextureWidth,
  85201. height: blurTextureHeight
  85202. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85203. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85204. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85205. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85206. this._blurTexture1.renderParticles = false;
  85207. this._blurTexture1.ignoreCameraViewport = true;
  85208. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85209. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85210. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85211. width: blurTextureWidth2,
  85212. height: blurTextureHeight2
  85213. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85214. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85215. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85216. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85217. this._blurTexture2.renderParticles = false;
  85218. this._blurTexture2.ignoreCameraViewport = true;
  85219. this._textures = [this._blurTexture1, this._blurTexture2];
  85220. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85221. width: blurTextureWidth,
  85222. height: blurTextureHeight
  85223. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85224. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85225. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85226. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85227. effect.setTexture("textureSampler", _this._mainTexture);
  85228. });
  85229. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85230. width: blurTextureWidth,
  85231. height: blurTextureHeight
  85232. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85233. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85234. width: blurTextureWidth2,
  85235. height: blurTextureHeight2
  85236. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85237. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85238. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85239. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85240. effect.setTexture("textureSampler", _this._blurTexture1);
  85241. });
  85242. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85243. width: blurTextureWidth2,
  85244. height: blurTextureHeight2
  85245. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85246. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85247. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85248. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85249. this._mainTexture.samples = this._options.mainTextureSamples;
  85250. this._mainTexture.onAfterUnbindObservable.add(function () {
  85251. var internalTexture = _this._blurTexture1.getInternalTexture();
  85252. if (internalTexture) {
  85253. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85254. internalTexture = _this._blurTexture2.getInternalTexture();
  85255. if (internalTexture) {
  85256. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85257. }
  85258. }
  85259. });
  85260. // Prevent autoClear.
  85261. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85262. };
  85263. /**
  85264. * Checks for the readiness of the element composing the layer.
  85265. * @param subMesh the mesh to check for
  85266. * @param useInstances specify wether or not to use instances to render the mesh
  85267. * @param emissiveTexture the associated emissive texture used to generate the glow
  85268. * @return true if ready otherwise, false
  85269. */
  85270. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85271. var material = subMesh.getMaterial();
  85272. var mesh = subMesh.getRenderingMesh();
  85273. if (!material || !mesh) {
  85274. return false;
  85275. }
  85276. var emissiveTexture = material.emissiveTexture;
  85277. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85278. };
  85279. /**
  85280. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85281. */
  85282. GlowLayer.prototype.needStencil = function () {
  85283. return false;
  85284. };
  85285. /**
  85286. * Implementation specific of rendering the generating effect on the main canvas.
  85287. * @param effect The effect used to render through
  85288. */
  85289. GlowLayer.prototype._internalRender = function (effect) {
  85290. // Texture
  85291. effect.setTexture("textureSampler", this._blurTexture1);
  85292. effect.setTexture("textureSampler2", this._blurTexture2);
  85293. effect.setFloat("offset", this._intensity);
  85294. // Cache
  85295. var engine = this._engine;
  85296. var previousStencilBuffer = engine.getStencilBuffer();
  85297. // Draw order
  85298. engine.setStencilBuffer(false);
  85299. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85300. // Draw order
  85301. engine.setStencilBuffer(previousStencilBuffer);
  85302. };
  85303. /**
  85304. * Sets the required values for both the emissive texture and and the main color.
  85305. */
  85306. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85307. var textureLevel = 1.0;
  85308. if (this.customEmissiveTextureSelector) {
  85309. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85310. }
  85311. else {
  85312. if (material) {
  85313. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85314. if (this._emissiveTextureAndColor.texture) {
  85315. textureLevel = this._emissiveTextureAndColor.texture.level;
  85316. }
  85317. }
  85318. else {
  85319. this._emissiveTextureAndColor.texture = null;
  85320. }
  85321. }
  85322. if (this.customEmissiveColorSelector) {
  85323. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85324. }
  85325. else {
  85326. if (material.emissiveColor) {
  85327. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85328. }
  85329. else {
  85330. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85331. }
  85332. }
  85333. };
  85334. /**
  85335. * Returns true if the mesh should render, otherwise false.
  85336. * @param mesh The mesh to render
  85337. * @returns true if it should render otherwise false
  85338. */
  85339. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85340. return this.hasMesh(mesh);
  85341. };
  85342. /**
  85343. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85344. * @param mesh The mesh to exclude from the glow layer
  85345. */
  85346. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85347. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85348. this._excludedMeshes.push(mesh.uniqueId);
  85349. }
  85350. };
  85351. /**
  85352. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85353. * @param mesh The mesh to remove
  85354. */
  85355. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85356. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85357. if (index !== -1) {
  85358. this._excludedMeshes.splice(index, 1);
  85359. }
  85360. };
  85361. /**
  85362. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85363. * @param mesh The mesh to include in the glow layer
  85364. */
  85365. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85366. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85367. this._includedOnlyMeshes.push(mesh.uniqueId);
  85368. }
  85369. };
  85370. /**
  85371. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85372. * @param mesh The mesh to remove
  85373. */
  85374. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85375. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85376. if (index !== -1) {
  85377. this._includedOnlyMeshes.splice(index, 1);
  85378. }
  85379. };
  85380. /**
  85381. * Determine if a given mesh will be used in the glow layer
  85382. * @param mesh The mesh to test
  85383. * @returns true if the mesh will be highlighted by the current glow layer
  85384. */
  85385. GlowLayer.prototype.hasMesh = function (mesh) {
  85386. // Included Mesh
  85387. if (this._includedOnlyMeshes.length) {
  85388. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85389. }
  85390. ;
  85391. // Excluded Mesh
  85392. if (this._excludedMeshes.length) {
  85393. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85394. }
  85395. ;
  85396. return true;
  85397. };
  85398. /**
  85399. * Free any resources and references associated to a mesh.
  85400. * Internal use
  85401. * @param mesh The mesh to free.
  85402. */
  85403. GlowLayer.prototype._disposeMesh = function (mesh) {
  85404. this.removeIncludedOnlyMesh(mesh);
  85405. this.removeExcludedMesh(mesh);
  85406. };
  85407. /**
  85408. * Effect Name of the layer.
  85409. */
  85410. GlowLayer.EffectName = "GlowLayer";
  85411. /**
  85412. * The default blur kernel size used for the glow.
  85413. */
  85414. GlowLayer.DefaultBlurKernelSize = 32;
  85415. /**
  85416. * The default texture size ratio used for the glow.
  85417. */
  85418. GlowLayer.DefaultTextureRatio = 0.5;
  85419. return GlowLayer;
  85420. }(BABYLON.EffectLayer));
  85421. BABYLON.GlowLayer = GlowLayer;
  85422. })(BABYLON || (BABYLON = {}));
  85423. //# sourceMappingURL=babylon.glowLayer.js.map
  85424. var BABYLON;
  85425. (function (BABYLON) {
  85426. /**
  85427. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85428. */
  85429. var AssetTaskState;
  85430. (function (AssetTaskState) {
  85431. /**
  85432. * Initialization
  85433. */
  85434. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85435. /**
  85436. * Running
  85437. */
  85438. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85439. /**
  85440. * Done
  85441. */
  85442. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85443. /**
  85444. * Error
  85445. */
  85446. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85447. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85448. /**
  85449. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85450. */
  85451. var AbstractAssetTask = /** @class */ (function () {
  85452. /**
  85453. * Creates a new {BABYLON.AssetsManager}
  85454. * @param name defines the name of the task
  85455. */
  85456. function AbstractAssetTask(
  85457. /**
  85458. * Task name
  85459. */ name) {
  85460. this.name = name;
  85461. this._isCompleted = false;
  85462. this._taskState = AssetTaskState.INIT;
  85463. }
  85464. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85465. /**
  85466. * Get if the task is completed
  85467. */
  85468. get: function () {
  85469. return this._isCompleted;
  85470. },
  85471. enumerable: true,
  85472. configurable: true
  85473. });
  85474. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85475. /**
  85476. * Gets the current state of the task
  85477. */
  85478. get: function () {
  85479. return this._taskState;
  85480. },
  85481. enumerable: true,
  85482. configurable: true
  85483. });
  85484. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85485. /**
  85486. * Gets the current error object (if task is in error)
  85487. */
  85488. get: function () {
  85489. return this._errorObject;
  85490. },
  85491. enumerable: true,
  85492. configurable: true
  85493. });
  85494. /**
  85495. * Internal only
  85496. * @ignore
  85497. */
  85498. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85499. if (this._errorObject) {
  85500. return;
  85501. }
  85502. this._errorObject = {
  85503. message: message,
  85504. exception: exception
  85505. };
  85506. };
  85507. /**
  85508. * Execute the current task
  85509. * @param scene defines the scene where you want your assets to be loaded
  85510. * @param onSuccess is a callback called when the task is successfully executed
  85511. * @param onError is a callback called if an error occurs
  85512. */
  85513. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85514. var _this = this;
  85515. this._taskState = AssetTaskState.RUNNING;
  85516. this.runTask(scene, function () {
  85517. _this.onDoneCallback(onSuccess, onError);
  85518. }, function (msg, exception) {
  85519. _this.onErrorCallback(onError, msg, exception);
  85520. });
  85521. };
  85522. /**
  85523. * Execute the current task
  85524. * @param scene defines the scene where you want your assets to be loaded
  85525. * @param onSuccess is a callback called when the task is successfully executed
  85526. * @param onError is a callback called if an error occurs
  85527. */
  85528. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85529. throw new Error("runTask is not implemented");
  85530. };
  85531. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85532. this._taskState = AssetTaskState.ERROR;
  85533. this._errorObject = {
  85534. message: message,
  85535. exception: exception
  85536. };
  85537. if (this.onError) {
  85538. this.onError(this, message, exception);
  85539. }
  85540. onError();
  85541. };
  85542. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85543. try {
  85544. this._taskState = AssetTaskState.DONE;
  85545. this._isCompleted = true;
  85546. if (this.onSuccess) {
  85547. this.onSuccess(this);
  85548. }
  85549. onSuccess();
  85550. }
  85551. catch (e) {
  85552. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85553. }
  85554. };
  85555. return AbstractAssetTask;
  85556. }());
  85557. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85558. /**
  85559. * Class used to share progress information about assets loading
  85560. */
  85561. var AssetsProgressEvent = /** @class */ (function () {
  85562. /**
  85563. * Creates a {BABYLON.AssetsProgressEvent}
  85564. * @param remainingCount defines the number of remaining tasks to process
  85565. * @param totalCount defines the total number of tasks
  85566. * @param task defines the task that was just processed
  85567. */
  85568. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85569. this.remainingCount = remainingCount;
  85570. this.totalCount = totalCount;
  85571. this.task = task;
  85572. }
  85573. return AssetsProgressEvent;
  85574. }());
  85575. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85576. /**
  85577. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85578. */
  85579. var MeshAssetTask = /** @class */ (function (_super) {
  85580. __extends(MeshAssetTask, _super);
  85581. /**
  85582. * Creates a new {BABYLON.MeshAssetTask}
  85583. * @param name defines the name of the task
  85584. * @param meshesNames defines the list of mesh's names you want to load
  85585. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85586. * @param sceneFilename defines the filename of the scene to load from
  85587. */
  85588. function MeshAssetTask(
  85589. /**
  85590. * Defines the name of the task
  85591. */
  85592. name,
  85593. /**
  85594. * Defines the list of mesh's names you want to load
  85595. */
  85596. meshesNames,
  85597. /**
  85598. * Defines the root url to use as a base to load your meshes and associated resources
  85599. */
  85600. rootUrl,
  85601. /**
  85602. * Defines the filename of the scene to load from
  85603. */
  85604. sceneFilename) {
  85605. var _this = _super.call(this, name) || this;
  85606. _this.name = name;
  85607. _this.meshesNames = meshesNames;
  85608. _this.rootUrl = rootUrl;
  85609. _this.sceneFilename = sceneFilename;
  85610. return _this;
  85611. }
  85612. /**
  85613. * Execute the current task
  85614. * @param scene defines the scene where you want your assets to be loaded
  85615. * @param onSuccess is a callback called when the task is successfully executed
  85616. * @param onError is a callback called if an error occurs
  85617. */
  85618. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85619. var _this = this;
  85620. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85621. _this.loadedMeshes = meshes;
  85622. _this.loadedParticleSystems = particleSystems;
  85623. _this.loadedSkeletons = skeletons;
  85624. onSuccess();
  85625. }, null, function (scene, message, exception) {
  85626. onError(message, exception);
  85627. });
  85628. };
  85629. return MeshAssetTask;
  85630. }(AbstractAssetTask));
  85631. BABYLON.MeshAssetTask = MeshAssetTask;
  85632. /**
  85633. * Define a task used by {BABYLON.AssetsManager} to load text content
  85634. */
  85635. var TextFileAssetTask = /** @class */ (function (_super) {
  85636. __extends(TextFileAssetTask, _super);
  85637. /**
  85638. * Creates a new TextFileAssetTask object
  85639. * @param name defines the name of the task
  85640. * @param url defines the location of the file to load
  85641. */
  85642. function TextFileAssetTask(
  85643. /**
  85644. * Defines the name of the task
  85645. */
  85646. name,
  85647. /**
  85648. * Defines the location of the file to load
  85649. */
  85650. url) {
  85651. var _this = _super.call(this, name) || this;
  85652. _this.name = name;
  85653. _this.url = url;
  85654. return _this;
  85655. }
  85656. /**
  85657. * Execute the current task
  85658. * @param scene defines the scene where you want your assets to be loaded
  85659. * @param onSuccess is a callback called when the task is successfully executed
  85660. * @param onError is a callback called if an error occurs
  85661. */
  85662. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85663. var _this = this;
  85664. scene._loadFile(this.url, function (data) {
  85665. _this.text = data;
  85666. onSuccess();
  85667. }, undefined, false, false, function (request, exception) {
  85668. if (request) {
  85669. onError(request.status + " " + request.statusText, exception);
  85670. }
  85671. });
  85672. };
  85673. return TextFileAssetTask;
  85674. }(AbstractAssetTask));
  85675. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85676. /**
  85677. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85678. */
  85679. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85680. __extends(BinaryFileAssetTask, _super);
  85681. /**
  85682. * Creates a new BinaryFileAssetTask object
  85683. * @param name defines the name of the new task
  85684. * @param url defines the location of the file to load
  85685. */
  85686. function BinaryFileAssetTask(
  85687. /**
  85688. * Defines the name of the task
  85689. */
  85690. name,
  85691. /**
  85692. * Defines the location of the file to load
  85693. */
  85694. url) {
  85695. var _this = _super.call(this, name) || this;
  85696. _this.name = name;
  85697. _this.url = url;
  85698. return _this;
  85699. }
  85700. /**
  85701. * Execute the current task
  85702. * @param scene defines the scene where you want your assets to be loaded
  85703. * @param onSuccess is a callback called when the task is successfully executed
  85704. * @param onError is a callback called if an error occurs
  85705. */
  85706. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85707. var _this = this;
  85708. scene._loadFile(this.url, function (data) {
  85709. _this.data = data;
  85710. onSuccess();
  85711. }, undefined, true, true, function (request, exception) {
  85712. if (request) {
  85713. onError(request.status + " " + request.statusText, exception);
  85714. }
  85715. });
  85716. };
  85717. return BinaryFileAssetTask;
  85718. }(AbstractAssetTask));
  85719. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85720. /**
  85721. * Define a task used by {BABYLON.AssetsManager} to load images
  85722. */
  85723. var ImageAssetTask = /** @class */ (function (_super) {
  85724. __extends(ImageAssetTask, _super);
  85725. /**
  85726. * Creates a new ImageAssetTask
  85727. * @param name defines the name of the task
  85728. * @param url defines the location of the image to load
  85729. */
  85730. function ImageAssetTask(
  85731. /**
  85732. * Defines the name of the task
  85733. */
  85734. name,
  85735. /**
  85736. * Defines the location of the image to load
  85737. */
  85738. url) {
  85739. var _this = _super.call(this, name) || this;
  85740. _this.name = name;
  85741. _this.url = url;
  85742. return _this;
  85743. }
  85744. /**
  85745. * Execute the current task
  85746. * @param scene defines the scene where you want your assets to be loaded
  85747. * @param onSuccess is a callback called when the task is successfully executed
  85748. * @param onError is a callback called if an error occurs
  85749. */
  85750. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85751. var _this = this;
  85752. var img = new Image();
  85753. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85754. img.onload = function () {
  85755. _this.image = img;
  85756. onSuccess();
  85757. };
  85758. img.onerror = function (err) {
  85759. onError("Error loading image", err);
  85760. };
  85761. img.src = this.url;
  85762. };
  85763. return ImageAssetTask;
  85764. }(AbstractAssetTask));
  85765. BABYLON.ImageAssetTask = ImageAssetTask;
  85766. /**
  85767. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85768. */
  85769. var TextureAssetTask = /** @class */ (function (_super) {
  85770. __extends(TextureAssetTask, _super);
  85771. /**
  85772. * Creates a new TextureAssetTask object
  85773. * @param name defines the name of the task
  85774. * @param url defines the location of the file to load
  85775. * @param noMipmap defines if mipmap should not be generated (default is false)
  85776. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85777. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85778. */
  85779. function TextureAssetTask(
  85780. /**
  85781. * Defines the name of the task
  85782. */
  85783. name,
  85784. /**
  85785. * Defines the location of the file to load
  85786. */
  85787. url,
  85788. /**
  85789. * Defines if mipmap should not be generated (default is false)
  85790. */
  85791. noMipmap,
  85792. /**
  85793. * Defines if texture must be inverted on Y axis (default is false)
  85794. */
  85795. invertY,
  85796. /**
  85797. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85798. */
  85799. samplingMode) {
  85800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85801. var _this = _super.call(this, name) || this;
  85802. _this.name = name;
  85803. _this.url = url;
  85804. _this.noMipmap = noMipmap;
  85805. _this.invertY = invertY;
  85806. _this.samplingMode = samplingMode;
  85807. return _this;
  85808. }
  85809. /**
  85810. * Execute the current task
  85811. * @param scene defines the scene where you want your assets to be loaded
  85812. * @param onSuccess is a callback called when the task is successfully executed
  85813. * @param onError is a callback called if an error occurs
  85814. */
  85815. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85816. var onload = function () {
  85817. onSuccess();
  85818. };
  85819. var onerror = function (message, exception) {
  85820. onError(message, exception);
  85821. };
  85822. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85823. };
  85824. return TextureAssetTask;
  85825. }(AbstractAssetTask));
  85826. BABYLON.TextureAssetTask = TextureAssetTask;
  85827. /**
  85828. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85829. */
  85830. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85831. __extends(CubeTextureAssetTask, _super);
  85832. /**
  85833. * Creates a new CubeTextureAssetTask
  85834. * @param name defines the name of the task
  85835. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85836. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85837. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85838. * @param files defines the explicit list of files (undefined by default)
  85839. */
  85840. function CubeTextureAssetTask(
  85841. /**
  85842. * Defines the name of the task
  85843. */
  85844. name,
  85845. /**
  85846. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85847. */
  85848. url,
  85849. /**
  85850. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85851. */
  85852. extensions,
  85853. /**
  85854. * Defines if mipmaps should not be generated (default is false)
  85855. */
  85856. noMipmap,
  85857. /**
  85858. * Defines the explicit list of files (undefined by default)
  85859. */
  85860. files) {
  85861. var _this = _super.call(this, name) || this;
  85862. _this.name = name;
  85863. _this.url = url;
  85864. _this.extensions = extensions;
  85865. _this.noMipmap = noMipmap;
  85866. _this.files = files;
  85867. return _this;
  85868. }
  85869. /**
  85870. * Execute the current task
  85871. * @param scene defines the scene where you want your assets to be loaded
  85872. * @param onSuccess is a callback called when the task is successfully executed
  85873. * @param onError is a callback called if an error occurs
  85874. */
  85875. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85876. var onload = function () {
  85877. onSuccess();
  85878. };
  85879. var onerror = function (message, exception) {
  85880. onError(message, exception);
  85881. };
  85882. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85883. };
  85884. return CubeTextureAssetTask;
  85885. }(AbstractAssetTask));
  85886. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85887. /**
  85888. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85889. */
  85890. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85891. __extends(HDRCubeTextureAssetTask, _super);
  85892. /**
  85893. * Creates a new HDRCubeTextureAssetTask object
  85894. * @param name defines the name of the task
  85895. * @param url defines the location of the file to load
  85896. * @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.
  85897. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85898. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85899. * @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)
  85900. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85901. */
  85902. function HDRCubeTextureAssetTask(
  85903. /**
  85904. * Defines the name of the task
  85905. */
  85906. name,
  85907. /**
  85908. * Defines the location of the file to load
  85909. */
  85910. url,
  85911. /**
  85912. * 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.
  85913. */
  85914. size,
  85915. /**
  85916. * Defines if mipmaps should not be generated (default is false)
  85917. */
  85918. noMipmap,
  85919. /**
  85920. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85921. */
  85922. generateHarmonics,
  85923. /**
  85924. * 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)
  85925. */
  85926. useInGammaSpace,
  85927. /**
  85928. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85929. */
  85930. usePMREMGenerator) {
  85931. if (noMipmap === void 0) { noMipmap = false; }
  85932. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85933. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85934. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85935. var _this = _super.call(this, name) || this;
  85936. _this.name = name;
  85937. _this.url = url;
  85938. _this.size = size;
  85939. _this.noMipmap = noMipmap;
  85940. _this.generateHarmonics = generateHarmonics;
  85941. _this.useInGammaSpace = useInGammaSpace;
  85942. _this.usePMREMGenerator = usePMREMGenerator;
  85943. return _this;
  85944. }
  85945. /**
  85946. * Execute the current task
  85947. * @param scene defines the scene where you want your assets to be loaded
  85948. * @param onSuccess is a callback called when the task is successfully executed
  85949. * @param onError is a callback called if an error occurs
  85950. */
  85951. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85952. var onload = function () {
  85953. onSuccess();
  85954. };
  85955. var onerror = function (message, exception) {
  85956. onError(message, exception);
  85957. };
  85958. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85959. };
  85960. return HDRCubeTextureAssetTask;
  85961. }(AbstractAssetTask));
  85962. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85963. /**
  85964. * This class can be used to easily import assets into a scene
  85965. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85966. */
  85967. var AssetsManager = /** @class */ (function () {
  85968. /**
  85969. * Creates a new AssetsManager
  85970. * @param scene defines the scene to work on
  85971. */
  85972. function AssetsManager(scene) {
  85973. this._isLoading = false;
  85974. this._tasks = new Array();
  85975. this._waitingTasksCount = 0;
  85976. this._totalTasksCount = 0;
  85977. /**
  85978. * Observable called when all tasks are processed
  85979. */
  85980. this.onTaskSuccessObservable = new BABYLON.Observable();
  85981. /**
  85982. * Observable called when a task had an error
  85983. */
  85984. this.onTaskErrorObservable = new BABYLON.Observable();
  85985. /**
  85986. * Observable called when a task is successful
  85987. */
  85988. this.onTasksDoneObservable = new BABYLON.Observable();
  85989. /**
  85990. * Observable called when a task is done (whatever the result is)
  85991. */
  85992. this.onProgressObservable = new BABYLON.Observable();
  85993. /**
  85994. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85995. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85996. */
  85997. this.useDefaultLoadingScreen = true;
  85998. this._scene = scene;
  85999. }
  86000. /**
  86001. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86002. * @param taskName defines the name of the new task
  86003. * @param meshesNames defines the name of meshes to load
  86004. * @param rootUrl defines the root url to use to locate files
  86005. * @param sceneFilename defines the filename of the scene file
  86006. * @returns a new {BABYLON.MeshAssetTask} object
  86007. */
  86008. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86009. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86010. this._tasks.push(task);
  86011. return task;
  86012. };
  86013. /**
  86014. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86015. * @param taskName defines the name of the new task
  86016. * @param url defines the url of the file to load
  86017. * @returns a new {BABYLON.TextFileAssetTask} object
  86018. */
  86019. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86020. var task = new TextFileAssetTask(taskName, url);
  86021. this._tasks.push(task);
  86022. return task;
  86023. };
  86024. /**
  86025. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86026. * @param taskName defines the name of the new task
  86027. * @param url defines the url of the file to load
  86028. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86029. */
  86030. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86031. var task = new BinaryFileAssetTask(taskName, url);
  86032. this._tasks.push(task);
  86033. return task;
  86034. };
  86035. /**
  86036. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86037. * @param taskName defines the name of the new task
  86038. * @param url defines the url of the file to load
  86039. * @returns a new {BABYLON.ImageAssetTask} object
  86040. */
  86041. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86042. var task = new ImageAssetTask(taskName, url);
  86043. this._tasks.push(task);
  86044. return task;
  86045. };
  86046. /**
  86047. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86048. * @param taskName defines the name of the new task
  86049. * @param url defines the url of the file to load
  86050. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86051. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86052. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86053. * @returns a new {BABYLON.TextureAssetTask} object
  86054. */
  86055. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86057. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86058. this._tasks.push(task);
  86059. return task;
  86060. };
  86061. /**
  86062. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86063. * @param taskName defines the name of the new task
  86064. * @param url defines the url of the file to load
  86065. * @param extensions defines the extension to use to load the cube map (can be null)
  86066. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86067. * @param files defines the list of files to load (can be null)
  86068. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86069. */
  86070. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86071. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86072. this._tasks.push(task);
  86073. return task;
  86074. };
  86075. /**
  86076. *
  86077. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86078. * @param taskName defines the name of the new task
  86079. * @param url defines the url of the file to load
  86080. * @param size defines the size you want for the cubemap (can be null)
  86081. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86082. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86083. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86084. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86085. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86086. */
  86087. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86088. if (noMipmap === void 0) { noMipmap = false; }
  86089. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86090. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86091. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86092. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86093. this._tasks.push(task);
  86094. return task;
  86095. };
  86096. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86097. var _this = this;
  86098. this._waitingTasksCount--;
  86099. try {
  86100. if (task.taskState === AssetTaskState.DONE) {
  86101. // Let's remove successfull tasks
  86102. BABYLON.Tools.SetImmediate(function () {
  86103. var index = _this._tasks.indexOf(task);
  86104. if (index > -1) {
  86105. _this._tasks.splice(index, 1);
  86106. }
  86107. });
  86108. }
  86109. if (this.onProgress) {
  86110. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86111. }
  86112. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86113. }
  86114. catch (e) {
  86115. BABYLON.Tools.Error("Error running progress callbacks.");
  86116. console.log(e);
  86117. }
  86118. if (this._waitingTasksCount === 0) {
  86119. try {
  86120. if (this.onFinish) {
  86121. this.onFinish(this._tasks);
  86122. }
  86123. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86124. }
  86125. catch (e) {
  86126. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86127. console.log(e);
  86128. }
  86129. this._isLoading = false;
  86130. this._scene.getEngine().hideLoadingUI();
  86131. }
  86132. };
  86133. AssetsManager.prototype._runTask = function (task) {
  86134. var _this = this;
  86135. var done = function () {
  86136. try {
  86137. if (_this.onTaskSuccess) {
  86138. _this.onTaskSuccess(task);
  86139. }
  86140. _this.onTaskSuccessObservable.notifyObservers(task);
  86141. _this._decreaseWaitingTasksCount(task);
  86142. }
  86143. catch (e) {
  86144. error("Error executing task success callbacks", e);
  86145. }
  86146. };
  86147. var error = function (message, exception) {
  86148. task._setErrorObject(message, exception);
  86149. if (_this.onTaskError) {
  86150. _this.onTaskError(task);
  86151. }
  86152. _this.onTaskErrorObservable.notifyObservers(task);
  86153. _this._decreaseWaitingTasksCount(task);
  86154. };
  86155. task.run(this._scene, done, error);
  86156. };
  86157. /**
  86158. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86159. * @return the current instance of the {BABYLON.AssetsManager}
  86160. */
  86161. AssetsManager.prototype.reset = function () {
  86162. this._isLoading = false;
  86163. this._tasks = new Array();
  86164. return this;
  86165. };
  86166. /**
  86167. * Start the loading process
  86168. * @return the current instance of the {BABYLON.AssetsManager}
  86169. */
  86170. AssetsManager.prototype.load = function () {
  86171. if (this._isLoading) {
  86172. return this;
  86173. }
  86174. this._isLoading = true;
  86175. this._waitingTasksCount = this._tasks.length;
  86176. this._totalTasksCount = this._tasks.length;
  86177. if (this._waitingTasksCount === 0) {
  86178. this._isLoading = false;
  86179. if (this.onFinish) {
  86180. this.onFinish(this._tasks);
  86181. }
  86182. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86183. return this;
  86184. }
  86185. if (this.useDefaultLoadingScreen) {
  86186. this._scene.getEngine().displayLoadingUI();
  86187. }
  86188. for (var index = 0; index < this._tasks.length; index++) {
  86189. var task = this._tasks[index];
  86190. this._runTask(task);
  86191. }
  86192. return this;
  86193. };
  86194. return AssetsManager;
  86195. }());
  86196. BABYLON.AssetsManager = AssetsManager;
  86197. })(BABYLON || (BABYLON = {}));
  86198. //# sourceMappingURL=babylon.assetsManager.js.map
  86199. var BABYLON;
  86200. (function (BABYLON) {
  86201. var serializedGeometries = [];
  86202. var serializeGeometry = function (geometry, serializationGeometries) {
  86203. if (serializedGeometries[geometry.id]) {
  86204. return;
  86205. }
  86206. if (geometry.doNotSerialize) {
  86207. return;
  86208. }
  86209. if (geometry instanceof BABYLON.BoxGeometry) {
  86210. serializationGeometries.boxes.push(geometry.serialize());
  86211. }
  86212. else if (geometry instanceof BABYLON.SphereGeometry) {
  86213. serializationGeometries.spheres.push(geometry.serialize());
  86214. }
  86215. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86216. serializationGeometries.cylinders.push(geometry.serialize());
  86217. }
  86218. else if (geometry instanceof BABYLON.TorusGeometry) {
  86219. serializationGeometries.toruses.push(geometry.serialize());
  86220. }
  86221. else if (geometry instanceof BABYLON.GroundGeometry) {
  86222. serializationGeometries.grounds.push(geometry.serialize());
  86223. }
  86224. else if (geometry instanceof BABYLON.Plane) {
  86225. serializationGeometries.planes.push(geometry.serialize());
  86226. }
  86227. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86228. serializationGeometries.torusKnots.push(geometry.serialize());
  86229. }
  86230. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86231. throw new Error("Unknown primitive type");
  86232. }
  86233. else {
  86234. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86235. }
  86236. serializedGeometries[geometry.id] = true;
  86237. };
  86238. var serializeMesh = function (mesh, serializationScene) {
  86239. var serializationObject = {};
  86240. // Geometry
  86241. var geometry = mesh._geometry;
  86242. if (geometry) {
  86243. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86244. // 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
  86245. serializeGeometry(geometry, serializationScene.geometries);
  86246. }
  86247. }
  86248. // Custom
  86249. if (mesh.serialize) {
  86250. mesh.serialize(serializationObject);
  86251. }
  86252. return serializationObject;
  86253. };
  86254. var finalizeSingleMesh = function (mesh, serializationObject) {
  86255. //only works if the mesh is already loaded
  86256. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86257. //serialize material
  86258. if (mesh.material) {
  86259. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86260. serializationObject.materials = serializationObject.materials || [];
  86261. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86262. serializationObject.materials.push(mesh.material.serialize());
  86263. }
  86264. }
  86265. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86266. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86267. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86268. serializationObject.multiMaterials.push(mesh.material.serialize());
  86269. }
  86270. }
  86271. }
  86272. //serialize geometry
  86273. var geometry = mesh._geometry;
  86274. if (geometry) {
  86275. if (!serializationObject.geometries) {
  86276. serializationObject.geometries = {};
  86277. serializationObject.geometries.boxes = [];
  86278. serializationObject.geometries.spheres = [];
  86279. serializationObject.geometries.cylinders = [];
  86280. serializationObject.geometries.toruses = [];
  86281. serializationObject.geometries.grounds = [];
  86282. serializationObject.geometries.planes = [];
  86283. serializationObject.geometries.torusKnots = [];
  86284. serializationObject.geometries.vertexData = [];
  86285. }
  86286. serializeGeometry(geometry, serializationObject.geometries);
  86287. }
  86288. // Skeletons
  86289. if (mesh.skeleton) {
  86290. serializationObject.skeletons = serializationObject.skeletons || [];
  86291. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86292. }
  86293. //serialize the actual mesh
  86294. serializationObject.meshes = serializationObject.meshes || [];
  86295. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86296. }
  86297. };
  86298. var SceneSerializer = /** @class */ (function () {
  86299. function SceneSerializer() {
  86300. }
  86301. SceneSerializer.ClearCache = function () {
  86302. serializedGeometries = [];
  86303. };
  86304. SceneSerializer.Serialize = function (scene) {
  86305. var serializationObject = {};
  86306. SceneSerializer.ClearCache();
  86307. // Scene
  86308. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86309. serializationObject.autoClear = scene.autoClear;
  86310. serializationObject.clearColor = scene.clearColor.asArray();
  86311. serializationObject.ambientColor = scene.ambientColor.asArray();
  86312. serializationObject.gravity = scene.gravity.asArray();
  86313. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86314. serializationObject.workerCollisions = scene.workerCollisions;
  86315. // Fog
  86316. if (scene.fogMode && scene.fogMode !== 0) {
  86317. serializationObject.fogMode = scene.fogMode;
  86318. serializationObject.fogColor = scene.fogColor.asArray();
  86319. serializationObject.fogStart = scene.fogStart;
  86320. serializationObject.fogEnd = scene.fogEnd;
  86321. serializationObject.fogDensity = scene.fogDensity;
  86322. }
  86323. //Physics
  86324. if (scene.isPhysicsEnabled()) {
  86325. var physicEngine = scene.getPhysicsEngine();
  86326. if (physicEngine) {
  86327. serializationObject.physicsEnabled = true;
  86328. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86329. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86330. }
  86331. }
  86332. // Metadata
  86333. if (scene.metadata) {
  86334. serializationObject.metadata = scene.metadata;
  86335. }
  86336. // Morph targets
  86337. serializationObject.morphTargetManagers = [];
  86338. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86339. var abstractMesh = _a[_i];
  86340. var manager = abstractMesh.morphTargetManager;
  86341. if (manager) {
  86342. serializationObject.morphTargetManagers.push(manager.serialize());
  86343. }
  86344. }
  86345. // Lights
  86346. serializationObject.lights = [];
  86347. var index;
  86348. var light;
  86349. for (index = 0; index < scene.lights.length; index++) {
  86350. light = scene.lights[index];
  86351. if (!light.doNotSerialize) {
  86352. serializationObject.lights.push(light.serialize());
  86353. }
  86354. }
  86355. // Cameras
  86356. serializationObject.cameras = [];
  86357. for (index = 0; index < scene.cameras.length; index++) {
  86358. var camera = scene.cameras[index];
  86359. if (!camera.doNotSerialize) {
  86360. serializationObject.cameras.push(camera.serialize());
  86361. }
  86362. }
  86363. if (scene.activeCamera) {
  86364. serializationObject.activeCameraID = scene.activeCamera.id;
  86365. }
  86366. // Animations
  86367. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86368. // Materials
  86369. serializationObject.materials = [];
  86370. serializationObject.multiMaterials = [];
  86371. var material;
  86372. for (index = 0; index < scene.materials.length; index++) {
  86373. material = scene.materials[index];
  86374. if (!material.doNotSerialize) {
  86375. serializationObject.materials.push(material.serialize());
  86376. }
  86377. }
  86378. // MultiMaterials
  86379. serializationObject.multiMaterials = [];
  86380. for (index = 0; index < scene.multiMaterials.length; index++) {
  86381. var multiMaterial = scene.multiMaterials[index];
  86382. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86383. }
  86384. // Environment texture
  86385. if (scene.environmentTexture) {
  86386. serializationObject.environmentTexture = scene.environmentTexture.name;
  86387. }
  86388. // Skeletons
  86389. serializationObject.skeletons = [];
  86390. for (index = 0; index < scene.skeletons.length; index++) {
  86391. var skeleton = scene.skeletons[index];
  86392. if (!skeleton.doNotSerialize) {
  86393. serializationObject.skeletons.push(skeleton.serialize());
  86394. }
  86395. }
  86396. // Transform nodes
  86397. serializationObject.transformNodes = [];
  86398. for (index = 0; index < scene.transformNodes.length; index++) {
  86399. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86400. }
  86401. // Geometries
  86402. serializationObject.geometries = {};
  86403. serializationObject.geometries.boxes = [];
  86404. serializationObject.geometries.spheres = [];
  86405. serializationObject.geometries.cylinders = [];
  86406. serializationObject.geometries.toruses = [];
  86407. serializationObject.geometries.grounds = [];
  86408. serializationObject.geometries.planes = [];
  86409. serializationObject.geometries.torusKnots = [];
  86410. serializationObject.geometries.vertexData = [];
  86411. serializedGeometries = [];
  86412. var geometries = scene.getGeometries();
  86413. for (index = 0; index < geometries.length; index++) {
  86414. var geometry = geometries[index];
  86415. if (geometry.isReady()) {
  86416. serializeGeometry(geometry, serializationObject.geometries);
  86417. }
  86418. }
  86419. // Meshes
  86420. serializationObject.meshes = [];
  86421. for (index = 0; index < scene.meshes.length; index++) {
  86422. var abstractMesh = scene.meshes[index];
  86423. if (abstractMesh instanceof BABYLON.Mesh) {
  86424. var mesh = abstractMesh;
  86425. if (!mesh.doNotSerialize) {
  86426. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86427. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86428. }
  86429. }
  86430. }
  86431. }
  86432. // Particles Systems
  86433. serializationObject.particleSystems = [];
  86434. for (index = 0; index < scene.particleSystems.length; index++) {
  86435. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86436. }
  86437. // Lens flares
  86438. serializationObject.lensFlareSystems = [];
  86439. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86440. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86441. }
  86442. // Shadows
  86443. serializationObject.shadowGenerators = [];
  86444. for (index = 0; index < scene.lights.length; index++) {
  86445. light = scene.lights[index];
  86446. var shadowGenerator = light.getShadowGenerator();
  86447. if (shadowGenerator) {
  86448. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86449. }
  86450. }
  86451. // Action Manager
  86452. if (scene.actionManager) {
  86453. serializationObject.actions = scene.actionManager.serialize("scene");
  86454. }
  86455. // Audio
  86456. serializationObject.sounds = [];
  86457. for (index = 0; index < scene.soundTracks.length; index++) {
  86458. var soundtrack = scene.soundTracks[index];
  86459. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86460. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86461. }
  86462. }
  86463. return serializationObject;
  86464. };
  86465. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86466. if (withParents === void 0) { withParents = false; }
  86467. if (withChildren === void 0) { withChildren = false; }
  86468. var serializationObject = {};
  86469. SceneSerializer.ClearCache();
  86470. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86471. if (withParents || withChildren) {
  86472. //deliberate for loop! not for each, appended should be processed as well.
  86473. for (var i = 0; i < toSerialize.length; ++i) {
  86474. if (withChildren) {
  86475. toSerialize[i].getDescendants().forEach(function (node) {
  86476. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86477. toSerialize.push(node);
  86478. }
  86479. });
  86480. }
  86481. //make sure the array doesn't contain the object already
  86482. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86483. toSerialize.push(toSerialize[i].parent);
  86484. }
  86485. }
  86486. }
  86487. toSerialize.forEach(function (mesh) {
  86488. finalizeSingleMesh(mesh, serializationObject);
  86489. });
  86490. return serializationObject;
  86491. };
  86492. return SceneSerializer;
  86493. }());
  86494. BABYLON.SceneSerializer = SceneSerializer;
  86495. })(BABYLON || (BABYLON = {}));
  86496. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86497. var BABYLON;
  86498. (function (BABYLON) {
  86499. var ReflectionProbe = /** @class */ (function () {
  86500. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86502. var _this = this;
  86503. this.name = name;
  86504. this._viewMatrix = BABYLON.Matrix.Identity();
  86505. this._target = BABYLON.Vector3.Zero();
  86506. this._add = BABYLON.Vector3.Zero();
  86507. this._invertYAxis = false;
  86508. this.position = BABYLON.Vector3.Zero();
  86509. this._scene = scene;
  86510. this._scene.reflectionProbes.push(this);
  86511. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86512. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86513. switch (faceIndex) {
  86514. case 0:
  86515. _this._add.copyFromFloats(1, 0, 0);
  86516. break;
  86517. case 1:
  86518. _this._add.copyFromFloats(-1, 0, 0);
  86519. break;
  86520. case 2:
  86521. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86522. break;
  86523. case 3:
  86524. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86525. break;
  86526. case 4:
  86527. _this._add.copyFromFloats(0, 0, 1);
  86528. break;
  86529. case 5:
  86530. _this._add.copyFromFloats(0, 0, -1);
  86531. break;
  86532. }
  86533. if (_this._attachedMesh) {
  86534. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86535. }
  86536. _this.position.addToRef(_this._add, _this._target);
  86537. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86538. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86539. scene._forcedViewPosition = _this.position;
  86540. });
  86541. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86542. scene._forcedViewPosition = null;
  86543. scene.updateTransformMatrix(true);
  86544. });
  86545. if (scene.activeCamera) {
  86546. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86547. }
  86548. }
  86549. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86550. get: function () {
  86551. return this._renderTargetTexture.samples;
  86552. },
  86553. set: function (value) {
  86554. this._renderTargetTexture.samples = value;
  86555. },
  86556. enumerable: true,
  86557. configurable: true
  86558. });
  86559. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86560. get: function () {
  86561. return this._renderTargetTexture.refreshRate;
  86562. },
  86563. set: function (value) {
  86564. this._renderTargetTexture.refreshRate = value;
  86565. },
  86566. enumerable: true,
  86567. configurable: true
  86568. });
  86569. ReflectionProbe.prototype.getScene = function () {
  86570. return this._scene;
  86571. };
  86572. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86573. get: function () {
  86574. return this._renderTargetTexture;
  86575. },
  86576. enumerable: true,
  86577. configurable: true
  86578. });
  86579. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86580. get: function () {
  86581. return this._renderTargetTexture.renderList;
  86582. },
  86583. enumerable: true,
  86584. configurable: true
  86585. });
  86586. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86587. this._attachedMesh = mesh;
  86588. };
  86589. /**
  86590. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86591. *
  86592. * @param renderingGroupId The rendering group id corresponding to its index
  86593. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86594. */
  86595. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86596. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86597. };
  86598. ReflectionProbe.prototype.dispose = function () {
  86599. var index = this._scene.reflectionProbes.indexOf(this);
  86600. if (index !== -1) {
  86601. // Remove from the scene if found
  86602. this._scene.reflectionProbes.splice(index, 1);
  86603. }
  86604. if (this._renderTargetTexture) {
  86605. this._renderTargetTexture.dispose();
  86606. this._renderTargetTexture = null;
  86607. }
  86608. };
  86609. return ReflectionProbe;
  86610. }());
  86611. BABYLON.ReflectionProbe = ReflectionProbe;
  86612. })(BABYLON || (BABYLON = {}));
  86613. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86614. var BABYLON;
  86615. (function (BABYLON) {
  86616. var Layer = /** @class */ (function () {
  86617. function Layer(name, imgUrl, scene, isBackground, color) {
  86618. this.name = name;
  86619. this.scale = new BABYLON.Vector2(1, 1);
  86620. this.offset = new BABYLON.Vector2(0, 0);
  86621. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86622. this.layerMask = 0x0FFFFFFF;
  86623. this._vertexBuffers = {};
  86624. // Events
  86625. /**
  86626. * An event triggered when the layer is disposed.
  86627. * @type {BABYLON.Observable}
  86628. */
  86629. this.onDisposeObservable = new BABYLON.Observable();
  86630. /**
  86631. * An event triggered before rendering the scene
  86632. * @type {BABYLON.Observable}
  86633. */
  86634. this.onBeforeRenderObservable = new BABYLON.Observable();
  86635. /**
  86636. * An event triggered after rendering the scene
  86637. * @type {BABYLON.Observable}
  86638. */
  86639. this.onAfterRenderObservable = new BABYLON.Observable();
  86640. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86641. this.isBackground = isBackground === undefined ? true : isBackground;
  86642. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86643. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86644. this._scene.layers.push(this);
  86645. var engine = this._scene.getEngine();
  86646. // VBO
  86647. var vertices = [];
  86648. vertices.push(1, 1);
  86649. vertices.push(-1, 1);
  86650. vertices.push(-1, -1);
  86651. vertices.push(1, -1);
  86652. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86653. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86654. this._createIndexBuffer();
  86655. // Effects
  86656. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86657. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86658. }
  86659. Object.defineProperty(Layer.prototype, "onDispose", {
  86660. set: function (callback) {
  86661. if (this._onDisposeObserver) {
  86662. this.onDisposeObservable.remove(this._onDisposeObserver);
  86663. }
  86664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86665. },
  86666. enumerable: true,
  86667. configurable: true
  86668. });
  86669. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86670. set: function (callback) {
  86671. if (this._onBeforeRenderObserver) {
  86672. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86673. }
  86674. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86675. },
  86676. enumerable: true,
  86677. configurable: true
  86678. });
  86679. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86680. set: function (callback) {
  86681. if (this._onAfterRenderObserver) {
  86682. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86683. }
  86684. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86685. },
  86686. enumerable: true,
  86687. configurable: true
  86688. });
  86689. Layer.prototype._createIndexBuffer = function () {
  86690. var engine = this._scene.getEngine();
  86691. // Indices
  86692. var indices = [];
  86693. indices.push(0);
  86694. indices.push(1);
  86695. indices.push(2);
  86696. indices.push(0);
  86697. indices.push(2);
  86698. indices.push(3);
  86699. this._indexBuffer = engine.createIndexBuffer(indices);
  86700. };
  86701. Layer.prototype._rebuild = function () {
  86702. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86703. if (vb) {
  86704. vb._rebuild();
  86705. }
  86706. this._createIndexBuffer();
  86707. };
  86708. Layer.prototype.render = function () {
  86709. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86710. // Check
  86711. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86712. return;
  86713. var engine = this._scene.getEngine();
  86714. this.onBeforeRenderObservable.notifyObservers(this);
  86715. // Render
  86716. engine.enableEffect(currentEffect);
  86717. engine.setState(false);
  86718. // Texture
  86719. currentEffect.setTexture("textureSampler", this.texture);
  86720. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86721. // Color
  86722. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86723. // Scale / offset
  86724. currentEffect.setVector2("offset", this.offset);
  86725. currentEffect.setVector2("scale", this.scale);
  86726. // VBOs
  86727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86728. // Draw order
  86729. if (!this.alphaTest) {
  86730. engine.setAlphaMode(this.alphaBlendingMode);
  86731. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86732. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86733. }
  86734. else {
  86735. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86736. }
  86737. this.onAfterRenderObservable.notifyObservers(this);
  86738. };
  86739. Layer.prototype.dispose = function () {
  86740. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86741. if (vertexBuffer) {
  86742. vertexBuffer.dispose();
  86743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86744. }
  86745. if (this._indexBuffer) {
  86746. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86747. this._indexBuffer = null;
  86748. }
  86749. if (this.texture) {
  86750. this.texture.dispose();
  86751. this.texture = null;
  86752. }
  86753. // Remove from scene
  86754. var index = this._scene.layers.indexOf(this);
  86755. this._scene.layers.splice(index, 1);
  86756. // Callback
  86757. this.onDisposeObservable.notifyObservers(this);
  86758. this.onDisposeObservable.clear();
  86759. this.onAfterRenderObservable.clear();
  86760. this.onBeforeRenderObservable.clear();
  86761. };
  86762. return Layer;
  86763. }());
  86764. BABYLON.Layer = Layer;
  86765. })(BABYLON || (BABYLON = {}));
  86766. //# sourceMappingURL=babylon.layer.js.map
  86767. var BABYLON;
  86768. (function (BABYLON) {
  86769. var TextureTools = /** @class */ (function () {
  86770. function TextureTools() {
  86771. }
  86772. /**
  86773. * Uses the GPU to create a copy texture rescaled at a given size
  86774. * @param texture Texture to copy from
  86775. * @param width Desired width
  86776. * @param height Desired height
  86777. * @return Generated texture
  86778. */
  86779. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86780. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86781. var scene = texture.getScene();
  86782. var engine = scene.getEngine();
  86783. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86784. rtt.wrapU = texture.wrapU;
  86785. rtt.wrapV = texture.wrapV;
  86786. rtt.uOffset = texture.uOffset;
  86787. rtt.vOffset = texture.vOffset;
  86788. rtt.uScale = texture.uScale;
  86789. rtt.vScale = texture.vScale;
  86790. rtt.uAng = texture.uAng;
  86791. rtt.vAng = texture.vAng;
  86792. rtt.wAng = texture.wAng;
  86793. rtt.coordinatesIndex = texture.coordinatesIndex;
  86794. rtt.level = texture.level;
  86795. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86796. rtt._texture.isReady = false;
  86797. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86798. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86799. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86800. passPostProcess.getEffect().executeWhenCompiled(function () {
  86801. passPostProcess.onApply = function (effect) {
  86802. effect.setTexture("textureSampler", texture);
  86803. };
  86804. var internalTexture = rtt.getInternalTexture();
  86805. if (internalTexture) {
  86806. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86807. engine.unBindFramebuffer(internalTexture);
  86808. rtt.disposeFramebufferObjects();
  86809. passPostProcess.dispose();
  86810. internalTexture.isReady = true;
  86811. }
  86812. });
  86813. return rtt;
  86814. };
  86815. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86816. if (!scene._environmentBRDFTexture) {
  86817. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86818. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86819. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86820. scene._environmentBRDFTexture = texture;
  86821. }
  86822. return scene._environmentBRDFTexture;
  86823. };
  86824. 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=";
  86825. return TextureTools;
  86826. }());
  86827. BABYLON.TextureTools = TextureTools;
  86828. })(BABYLON || (BABYLON = {}));
  86829. //# sourceMappingURL=babylon.textureTools.js.map
  86830. var BABYLON;
  86831. (function (BABYLON) {
  86832. var FramingBehavior = /** @class */ (function () {
  86833. function FramingBehavior() {
  86834. this._mode = FramingBehavior.FitFrustumSidesMode;
  86835. this._radiusScale = 1.0;
  86836. this._positionScale = 0.5;
  86837. this._defaultElevation = 0.3;
  86838. this._elevationReturnTime = 1500;
  86839. this._elevationReturnWaitTime = 1000;
  86840. this._zoomStopsAnimation = false;
  86841. this._framingTime = 1500;
  86842. this._isPointerDown = false;
  86843. this._lastInteractionTime = -Infinity;
  86844. // Framing control
  86845. this._animatables = new Array();
  86846. this._betaIsAnimating = false;
  86847. }
  86848. Object.defineProperty(FramingBehavior.prototype, "name", {
  86849. get: function () {
  86850. return "Framing";
  86851. },
  86852. enumerable: true,
  86853. configurable: true
  86854. });
  86855. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86856. /**
  86857. * Gets current mode used by the behavior.
  86858. */
  86859. get: function () {
  86860. return this._mode;
  86861. },
  86862. /**
  86863. * Sets the current mode used by the behavior
  86864. */
  86865. set: function (mode) {
  86866. this._mode = mode;
  86867. },
  86868. enumerable: true,
  86869. configurable: true
  86870. });
  86871. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86872. /**
  86873. * Gets the scale applied to the radius
  86874. */
  86875. get: function () {
  86876. return this._radiusScale;
  86877. },
  86878. /**
  86879. * Sets the scale applied to the radius (1 by default)
  86880. */
  86881. set: function (radius) {
  86882. this._radiusScale = radius;
  86883. },
  86884. enumerable: true,
  86885. configurable: true
  86886. });
  86887. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86888. /**
  86889. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86890. */
  86891. get: function () {
  86892. return this._positionScale;
  86893. },
  86894. /**
  86895. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86896. */
  86897. set: function (scale) {
  86898. this._positionScale = scale;
  86899. },
  86900. enumerable: true,
  86901. configurable: true
  86902. });
  86903. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86904. /**
  86905. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86906. * behaviour is triggered, in radians.
  86907. */
  86908. get: function () {
  86909. return this._defaultElevation;
  86910. },
  86911. /**
  86912. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86913. * behaviour is triggered, in radians.
  86914. */
  86915. set: function (elevation) {
  86916. this._defaultElevation = elevation;
  86917. },
  86918. enumerable: true,
  86919. configurable: true
  86920. });
  86921. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86922. /**
  86923. * Gets the time (in milliseconds) taken to return to the default beta position.
  86924. * Negative value indicates camera should not return to default.
  86925. */
  86926. get: function () {
  86927. return this._elevationReturnTime;
  86928. },
  86929. /**
  86930. * Sets the time (in milliseconds) taken to return to the default beta position.
  86931. * Negative value indicates camera should not return to default.
  86932. */
  86933. set: function (speed) {
  86934. this._elevationReturnTime = speed;
  86935. },
  86936. enumerable: true,
  86937. configurable: true
  86938. });
  86939. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86940. /**
  86941. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86942. */
  86943. get: function () {
  86944. return this._elevationReturnWaitTime;
  86945. },
  86946. /**
  86947. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86948. */
  86949. set: function (time) {
  86950. this._elevationReturnWaitTime = time;
  86951. },
  86952. enumerable: true,
  86953. configurable: true
  86954. });
  86955. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86956. /**
  86957. * Gets the flag that indicates if user zooming should stop animation.
  86958. */
  86959. get: function () {
  86960. return this._zoomStopsAnimation;
  86961. },
  86962. /**
  86963. * Sets the flag that indicates if user zooming should stop animation.
  86964. */
  86965. set: function (flag) {
  86966. this._zoomStopsAnimation = flag;
  86967. },
  86968. enumerable: true,
  86969. configurable: true
  86970. });
  86971. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86972. /**
  86973. * Gets the transition time when framing the mesh, in milliseconds
  86974. */
  86975. get: function () {
  86976. return this._framingTime;
  86977. },
  86978. /**
  86979. * Sets the transition time when framing the mesh, in milliseconds
  86980. */
  86981. set: function (time) {
  86982. this._framingTime = time;
  86983. },
  86984. enumerable: true,
  86985. configurable: true
  86986. });
  86987. FramingBehavior.prototype.init = function () {
  86988. // Do notihng
  86989. };
  86990. FramingBehavior.prototype.attach = function (camera) {
  86991. var _this = this;
  86992. this._attachedCamera = camera;
  86993. var scene = this._attachedCamera.getScene();
  86994. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86995. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86996. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86997. _this._isPointerDown = true;
  86998. return;
  86999. }
  87000. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87001. _this._isPointerDown = false;
  87002. }
  87003. });
  87004. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87005. if (mesh) {
  87006. _this.zoomOnMesh(mesh);
  87007. }
  87008. });
  87009. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87010. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87011. _this._applyUserInteraction();
  87012. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87013. // back to the default position after a given timeout
  87014. _this._maintainCameraAboveGround();
  87015. });
  87016. };
  87017. FramingBehavior.prototype.detach = function () {
  87018. if (!this._attachedCamera) {
  87019. return;
  87020. }
  87021. var scene = this._attachedCamera.getScene();
  87022. if (this._onPrePointerObservableObserver) {
  87023. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87024. }
  87025. if (this._onAfterCheckInputsObserver) {
  87026. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87027. }
  87028. if (this._onMeshTargetChangedObserver) {
  87029. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87030. }
  87031. this._attachedCamera = null;
  87032. };
  87033. /**
  87034. * Targets the given mesh and updates zoom level accordingly.
  87035. * @param mesh The mesh to target.
  87036. * @param radius Optional. If a cached radius position already exists, overrides default.
  87037. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87038. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87039. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87040. */
  87041. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87042. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87043. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87044. mesh.computeWorldMatrix(true);
  87045. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87046. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87047. };
  87048. /**
  87049. * Targets the given mesh with its children and updates zoom level accordingly.
  87050. * @param mesh The mesh to target.
  87051. * @param radius Optional. If a cached radius position already exists, overrides default.
  87052. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87053. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87054. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87055. */
  87056. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87057. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87058. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87059. mesh.computeWorldMatrix(true);
  87060. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87061. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87062. };
  87063. /**
  87064. * Targets the given meshes with their children and updates zoom level accordingly.
  87065. * @param meshes The mesh to target.
  87066. * @param radius Optional. If a cached radius position already exists, overrides default.
  87067. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87068. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87069. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87070. */
  87071. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87072. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87073. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87074. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87075. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87076. for (var i = 0; i < meshes.length; i++) {
  87077. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87078. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87079. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87080. }
  87081. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87082. };
  87083. /**
  87084. * Targets the given mesh and updates zoom level accordingly.
  87085. * @param mesh The mesh to target.
  87086. * @param radius Optional. If a cached radius position already exists, overrides default.
  87087. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87088. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87089. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87090. */
  87091. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87092. var _this = this;
  87093. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87094. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87095. var zoomTarget;
  87096. if (!this._attachedCamera) {
  87097. return;
  87098. }
  87099. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87100. var bottom = minimumWorld.y;
  87101. var top = maximumWorld.y;
  87102. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87103. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87104. if (focusOnOriginXZ) {
  87105. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87106. }
  87107. else {
  87108. var centerWorld = minimumWorld.add(radiusWorld);
  87109. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87110. }
  87111. if (!this._vectorTransition) {
  87112. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87113. }
  87114. this._betaIsAnimating = true;
  87115. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87116. if (animatable) {
  87117. this._animatables.push(animatable);
  87118. }
  87119. // sets the radius and lower radius bounds
  87120. // Small delta ensures camera is not always at lower zoom limit.
  87121. var radius = 0;
  87122. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87123. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87124. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87125. radius = position;
  87126. }
  87127. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87128. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87129. if (this._attachedCamera.lowerRadiusLimit === null) {
  87130. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87131. }
  87132. }
  87133. // Set sensibilities
  87134. var extend = maximumWorld.subtract(minimumWorld).length();
  87135. this._attachedCamera.panningSensibility = 5000 / extend;
  87136. this._attachedCamera.wheelPrecision = 100 / radius;
  87137. // transition to new radius
  87138. if (!this._radiusTransition) {
  87139. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87140. }
  87141. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87142. _this.stopAllAnimations();
  87143. if (onAnimationEnd) {
  87144. onAnimationEnd();
  87145. }
  87146. if (_this._attachedCamera) {
  87147. _this._attachedCamera.storeState();
  87148. }
  87149. });
  87150. if (animatable) {
  87151. this._animatables.push(animatable);
  87152. }
  87153. };
  87154. /**
  87155. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87156. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87157. * frustum width.
  87158. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87159. * to fully enclose the mesh in the viewing frustum.
  87160. */
  87161. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87162. var size = maximumWorld.subtract(minimumWorld);
  87163. var boxVectorGlobalDiagonal = size.length();
  87164. var frustumSlope = this._getFrustumSlope();
  87165. // Formula for setting distance
  87166. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87167. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87168. // Horizon distance
  87169. var radius = radiusWithoutFraming * this._radiusScale;
  87170. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87171. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87172. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87173. var camera = this._attachedCamera;
  87174. if (!camera) {
  87175. return 0;
  87176. }
  87177. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87178. // Don't exceed the requested limit
  87179. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87180. }
  87181. // Don't exceed the upper radius limit
  87182. if (camera.upperRadiusLimit) {
  87183. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87184. }
  87185. return distance;
  87186. };
  87187. /**
  87188. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87189. * is automatically returned to its default position (expected to be above ground plane).
  87190. */
  87191. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87192. var _this = this;
  87193. if (this._elevationReturnTime < 0) {
  87194. return;
  87195. }
  87196. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87197. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87198. var limitBeta = Math.PI * 0.5;
  87199. // Bring the camera back up if below the ground plane
  87200. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87201. this._betaIsAnimating = true;
  87202. //Transition to new position
  87203. this.stopAllAnimations();
  87204. if (!this._betaTransition) {
  87205. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87206. }
  87207. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87208. _this._clearAnimationLocks();
  87209. _this.stopAllAnimations();
  87210. });
  87211. if (animatabe) {
  87212. this._animatables.push(animatabe);
  87213. }
  87214. }
  87215. };
  87216. /**
  87217. * Returns the frustum slope based on the canvas ratio and camera FOV
  87218. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87219. */
  87220. FramingBehavior.prototype._getFrustumSlope = function () {
  87221. // Calculate the viewport ratio
  87222. // Aspect Ratio is Height/Width.
  87223. var camera = this._attachedCamera;
  87224. if (!camera) {
  87225. return BABYLON.Vector2.Zero();
  87226. }
  87227. var engine = camera.getScene().getEngine();
  87228. var aspectRatio = engine.getAspectRatio(camera);
  87229. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87230. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87231. var frustumSlopeY = Math.tan(camera.fov / 2);
  87232. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87233. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87234. // along the forward vector.
  87235. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87236. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87237. };
  87238. /**
  87239. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87240. */
  87241. FramingBehavior.prototype._clearAnimationLocks = function () {
  87242. this._betaIsAnimating = false;
  87243. };
  87244. /**
  87245. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87246. */
  87247. FramingBehavior.prototype._applyUserInteraction = function () {
  87248. if (this.isUserIsMoving) {
  87249. this._lastInteractionTime = BABYLON.Tools.Now;
  87250. this.stopAllAnimations();
  87251. this._clearAnimationLocks();
  87252. }
  87253. };
  87254. /**
  87255. * Stops and removes all animations that have been applied to the camera
  87256. */
  87257. FramingBehavior.prototype.stopAllAnimations = function () {
  87258. if (this._attachedCamera) {
  87259. this._attachedCamera.animations = [];
  87260. }
  87261. while (this._animatables.length) {
  87262. if (this._animatables[0]) {
  87263. this._animatables[0].onAnimationEnd = null;
  87264. this._animatables[0].stop();
  87265. }
  87266. this._animatables.shift();
  87267. }
  87268. };
  87269. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87270. /**
  87271. * Gets a value indicating if the user is moving the camera
  87272. */
  87273. get: function () {
  87274. if (!this._attachedCamera) {
  87275. return false;
  87276. }
  87277. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87278. this._attachedCamera.inertialBetaOffset !== 0 ||
  87279. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87280. this._attachedCamera.inertialPanningX !== 0 ||
  87281. this._attachedCamera.inertialPanningY !== 0 ||
  87282. this._isPointerDown;
  87283. },
  87284. enumerable: true,
  87285. configurable: true
  87286. });
  87287. /**
  87288. * The easing function used by animations
  87289. */
  87290. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87291. /**
  87292. * The easing mode used by animations
  87293. */
  87294. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87295. // Statics
  87296. /**
  87297. * The camera can move all the way towards the mesh.
  87298. */
  87299. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87300. /**
  87301. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87302. */
  87303. FramingBehavior.FitFrustumSidesMode = 1;
  87304. return FramingBehavior;
  87305. }());
  87306. BABYLON.FramingBehavior = FramingBehavior;
  87307. })(BABYLON || (BABYLON = {}));
  87308. //# sourceMappingURL=babylon.framingBehavior.js.map
  87309. var BABYLON;
  87310. (function (BABYLON) {
  87311. /**
  87312. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87313. */
  87314. var BouncingBehavior = /** @class */ (function () {
  87315. function BouncingBehavior() {
  87316. /**
  87317. * The duration of the animation, in milliseconds
  87318. */
  87319. this.transitionDuration = 450;
  87320. /**
  87321. * Length of the distance animated by the transition when lower radius is reached
  87322. */
  87323. this.lowerRadiusTransitionRange = 2;
  87324. /**
  87325. * Length of the distance animated by the transition when upper radius is reached
  87326. */
  87327. this.upperRadiusTransitionRange = -2;
  87328. this._autoTransitionRange = false;
  87329. // Animations
  87330. this._radiusIsAnimating = false;
  87331. this._radiusBounceTransition = null;
  87332. this._animatables = new Array();
  87333. }
  87334. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87335. get: function () {
  87336. return "Bouncing";
  87337. },
  87338. enumerable: true,
  87339. configurable: true
  87340. });
  87341. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87342. /**
  87343. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87344. */
  87345. get: function () {
  87346. return this._autoTransitionRange;
  87347. },
  87348. /**
  87349. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87350. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87351. */
  87352. set: function (value) {
  87353. var _this = this;
  87354. if (this._autoTransitionRange === value) {
  87355. return;
  87356. }
  87357. this._autoTransitionRange = value;
  87358. var camera = this._attachedCamera;
  87359. if (!camera) {
  87360. return;
  87361. }
  87362. if (value) {
  87363. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87364. if (!mesh) {
  87365. return;
  87366. }
  87367. mesh.computeWorldMatrix(true);
  87368. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87369. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87370. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87371. });
  87372. }
  87373. else if (this._onMeshTargetChangedObserver) {
  87374. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87375. }
  87376. },
  87377. enumerable: true,
  87378. configurable: true
  87379. });
  87380. BouncingBehavior.prototype.init = function () {
  87381. // Do notihng
  87382. };
  87383. BouncingBehavior.prototype.attach = function (camera) {
  87384. var _this = this;
  87385. this._attachedCamera = camera;
  87386. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87387. if (!_this._attachedCamera) {
  87388. return;
  87389. }
  87390. // Add the bounce animation to the lower radius limit
  87391. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87392. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87393. }
  87394. // Add the bounce animation to the upper radius limit
  87395. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87396. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87397. }
  87398. });
  87399. };
  87400. BouncingBehavior.prototype.detach = function () {
  87401. if (!this._attachedCamera) {
  87402. return;
  87403. }
  87404. if (this._onAfterCheckInputsObserver) {
  87405. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87406. }
  87407. if (this._onMeshTargetChangedObserver) {
  87408. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87409. }
  87410. this._attachedCamera = null;
  87411. };
  87412. /**
  87413. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87414. * @param radiusLimit The limit to check against.
  87415. * @return Bool to indicate if at limit.
  87416. */
  87417. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87418. if (!this._attachedCamera) {
  87419. return false;
  87420. }
  87421. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87422. return true;
  87423. }
  87424. return false;
  87425. };
  87426. /**
  87427. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87428. * @param radiusDelta The delta by which to animate to. Can be negative.
  87429. */
  87430. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87431. var _this = this;
  87432. if (!this._attachedCamera) {
  87433. return;
  87434. }
  87435. if (!this._radiusBounceTransition) {
  87436. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87437. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87438. }
  87439. // Prevent zoom until bounce has completed
  87440. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87441. this._attachedCamera.wheelPrecision = Infinity;
  87442. this._attachedCamera.inertialRadiusOffset = 0;
  87443. // Animate to the radius limit
  87444. this.stopAllAnimations();
  87445. this._radiusIsAnimating = true;
  87446. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87447. if (animatable) {
  87448. this._animatables.push(animatable);
  87449. }
  87450. };
  87451. /**
  87452. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87453. */
  87454. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87455. this._radiusIsAnimating = false;
  87456. if (this._attachedCamera) {
  87457. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87458. }
  87459. };
  87460. /**
  87461. * Stops and removes all animations that have been applied to the camera
  87462. */
  87463. BouncingBehavior.prototype.stopAllAnimations = function () {
  87464. if (this._attachedCamera) {
  87465. this._attachedCamera.animations = [];
  87466. }
  87467. while (this._animatables.length) {
  87468. this._animatables[0].onAnimationEnd = null;
  87469. this._animatables[0].stop();
  87470. this._animatables.shift();
  87471. }
  87472. };
  87473. /**
  87474. * The easing function used by animations
  87475. */
  87476. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87477. /**
  87478. * The easing mode used by animations
  87479. */
  87480. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87481. return BouncingBehavior;
  87482. }());
  87483. BABYLON.BouncingBehavior = BouncingBehavior;
  87484. })(BABYLON || (BABYLON = {}));
  87485. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87486. var BABYLON;
  87487. (function (BABYLON) {
  87488. var AutoRotationBehavior = /** @class */ (function () {
  87489. function AutoRotationBehavior() {
  87490. this._zoomStopsAnimation = false;
  87491. this._idleRotationSpeed = 0.05;
  87492. this._idleRotationWaitTime = 2000;
  87493. this._idleRotationSpinupTime = 2000;
  87494. this._isPointerDown = false;
  87495. this._lastFrameTime = null;
  87496. this._lastInteractionTime = -Infinity;
  87497. this._cameraRotationSpeed = 0;
  87498. this._lastFrameRadius = 0;
  87499. }
  87500. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87501. get: function () {
  87502. return "AutoRotation";
  87503. },
  87504. enumerable: true,
  87505. configurable: true
  87506. });
  87507. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87508. /**
  87509. * Gets the flag that indicates if user zooming should stop animation.
  87510. */
  87511. get: function () {
  87512. return this._zoomStopsAnimation;
  87513. },
  87514. /**
  87515. * Sets the flag that indicates if user zooming should stop animation.
  87516. */
  87517. set: function (flag) {
  87518. this._zoomStopsAnimation = flag;
  87519. },
  87520. enumerable: true,
  87521. configurable: true
  87522. });
  87523. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87524. /**
  87525. * Gets the default speed at which the camera rotates around the model.
  87526. */
  87527. get: function () {
  87528. return this._idleRotationSpeed;
  87529. },
  87530. /**
  87531. * Sets the default speed at which the camera rotates around the model.
  87532. */
  87533. set: function (speed) {
  87534. this._idleRotationSpeed = speed;
  87535. },
  87536. enumerable: true,
  87537. configurable: true
  87538. });
  87539. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87540. /**
  87541. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87542. */
  87543. get: function () {
  87544. return this._idleRotationWaitTime;
  87545. },
  87546. /**
  87547. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87548. */
  87549. set: function (time) {
  87550. this._idleRotationWaitTime = time;
  87551. },
  87552. enumerable: true,
  87553. configurable: true
  87554. });
  87555. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87556. /**
  87557. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87558. */
  87559. get: function () {
  87560. return this._idleRotationSpinupTime;
  87561. },
  87562. /**
  87563. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87564. */
  87565. set: function (time) {
  87566. this._idleRotationSpinupTime = time;
  87567. },
  87568. enumerable: true,
  87569. configurable: true
  87570. });
  87571. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87572. /**
  87573. * Gets a value indicating if the camera is currently rotating because of this behavior
  87574. */
  87575. get: function () {
  87576. return Math.abs(this._cameraRotationSpeed) > 0;
  87577. },
  87578. enumerable: true,
  87579. configurable: true
  87580. });
  87581. AutoRotationBehavior.prototype.init = function () {
  87582. // Do notihng
  87583. };
  87584. AutoRotationBehavior.prototype.attach = function (camera) {
  87585. var _this = this;
  87586. this._attachedCamera = camera;
  87587. var scene = this._attachedCamera.getScene();
  87588. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87589. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87590. _this._isPointerDown = true;
  87591. return;
  87592. }
  87593. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87594. _this._isPointerDown = false;
  87595. }
  87596. });
  87597. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87598. var now = BABYLON.Tools.Now;
  87599. var dt = 0;
  87600. if (_this._lastFrameTime != null) {
  87601. dt = now - _this._lastFrameTime;
  87602. }
  87603. _this._lastFrameTime = now;
  87604. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87605. _this._applyUserInteraction();
  87606. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87607. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87608. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87609. // Step camera rotation by rotation speed
  87610. if (_this._attachedCamera) {
  87611. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87612. }
  87613. });
  87614. };
  87615. AutoRotationBehavior.prototype.detach = function () {
  87616. if (!this._attachedCamera) {
  87617. return;
  87618. }
  87619. var scene = this._attachedCamera.getScene();
  87620. if (this._onPrePointerObservableObserver) {
  87621. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87622. }
  87623. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87624. this._attachedCamera = null;
  87625. };
  87626. /**
  87627. * Returns true if user is scrolling.
  87628. * @return true if user is scrolling.
  87629. */
  87630. AutoRotationBehavior.prototype._userIsZooming = function () {
  87631. if (!this._attachedCamera) {
  87632. return false;
  87633. }
  87634. return this._attachedCamera.inertialRadiusOffset !== 0;
  87635. };
  87636. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87637. if (!this._attachedCamera) {
  87638. return false;
  87639. }
  87640. var zoomHasHitLimit = false;
  87641. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87642. zoomHasHitLimit = true;
  87643. }
  87644. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87645. this._lastFrameRadius = this._attachedCamera.radius;
  87646. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87647. };
  87648. /**
  87649. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87650. */
  87651. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87652. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87653. this._lastInteractionTime = BABYLON.Tools.Now;
  87654. }
  87655. };
  87656. // Tools
  87657. AutoRotationBehavior.prototype._userIsMoving = function () {
  87658. if (!this._attachedCamera) {
  87659. return false;
  87660. }
  87661. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87662. this._attachedCamera.inertialBetaOffset !== 0 ||
  87663. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87664. this._attachedCamera.inertialPanningX !== 0 ||
  87665. this._attachedCamera.inertialPanningY !== 0 ||
  87666. this._isPointerDown;
  87667. };
  87668. return AutoRotationBehavior;
  87669. }());
  87670. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87671. })(BABYLON || (BABYLON = {}));
  87672. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87673. var BABYLON;
  87674. (function (BABYLON) {
  87675. /**
  87676. * This class can be used to get instrumentation data from a Babylon engine
  87677. */
  87678. var EngineInstrumentation = /** @class */ (function () {
  87679. function EngineInstrumentation(engine) {
  87680. this.engine = engine;
  87681. this._captureGPUFrameTime = false;
  87682. this._gpuFrameTime = new BABYLON.PerfCounter();
  87683. this._captureShaderCompilationTime = false;
  87684. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87685. // Observers
  87686. this._onBeginFrameObserver = null;
  87687. this._onEndFrameObserver = null;
  87688. this._onBeforeShaderCompilationObserver = null;
  87689. this._onAfterShaderCompilationObserver = null;
  87690. }
  87691. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87692. // Properties
  87693. /**
  87694. * Gets the perf counter used for GPU frame time
  87695. */
  87696. get: function () {
  87697. return this._gpuFrameTime;
  87698. },
  87699. enumerable: true,
  87700. configurable: true
  87701. });
  87702. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87703. /**
  87704. * Gets the GPU frame time capture status
  87705. */
  87706. get: function () {
  87707. return this._captureGPUFrameTime;
  87708. },
  87709. /**
  87710. * Enable or disable the GPU frame time capture
  87711. */
  87712. set: function (value) {
  87713. var _this = this;
  87714. if (value === this._captureGPUFrameTime) {
  87715. return;
  87716. }
  87717. this._captureGPUFrameTime = value;
  87718. if (value) {
  87719. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87720. if (!_this._gpuFrameTimeToken) {
  87721. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87722. }
  87723. });
  87724. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87725. if (!_this._gpuFrameTimeToken) {
  87726. return;
  87727. }
  87728. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87729. if (time > -1) {
  87730. _this._gpuFrameTimeToken = null;
  87731. _this._gpuFrameTime.fetchNewFrame();
  87732. _this._gpuFrameTime.addCount(time, true);
  87733. }
  87734. });
  87735. }
  87736. else {
  87737. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87738. this._onBeginFrameObserver = null;
  87739. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87740. this._onEndFrameObserver = null;
  87741. }
  87742. },
  87743. enumerable: true,
  87744. configurable: true
  87745. });
  87746. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87747. /**
  87748. * Gets the perf counter used for shader compilation time
  87749. */
  87750. get: function () {
  87751. return this._shaderCompilationTime;
  87752. },
  87753. enumerable: true,
  87754. configurable: true
  87755. });
  87756. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87757. /**
  87758. * Gets the shader compilation time capture status
  87759. */
  87760. get: function () {
  87761. return this._captureShaderCompilationTime;
  87762. },
  87763. /**
  87764. * Enable or disable the shader compilation time capture
  87765. */
  87766. set: function (value) {
  87767. var _this = this;
  87768. if (value === this._captureShaderCompilationTime) {
  87769. return;
  87770. }
  87771. this._captureShaderCompilationTime = value;
  87772. if (value) {
  87773. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87774. _this._shaderCompilationTime.fetchNewFrame();
  87775. _this._shaderCompilationTime.beginMonitoring();
  87776. });
  87777. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87778. _this._shaderCompilationTime.endMonitoring();
  87779. });
  87780. }
  87781. else {
  87782. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87783. this._onBeforeShaderCompilationObserver = null;
  87784. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87785. this._onAfterShaderCompilationObserver = null;
  87786. }
  87787. },
  87788. enumerable: true,
  87789. configurable: true
  87790. });
  87791. EngineInstrumentation.prototype.dispose = function () {
  87792. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87793. this._onBeginFrameObserver = null;
  87794. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87795. this._onEndFrameObserver = null;
  87796. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87797. this._onBeforeShaderCompilationObserver = null;
  87798. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87799. this._onAfterShaderCompilationObserver = null;
  87800. this.engine = null;
  87801. };
  87802. return EngineInstrumentation;
  87803. }());
  87804. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87805. })(BABYLON || (BABYLON = {}));
  87806. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87807. var BABYLON;
  87808. (function (BABYLON) {
  87809. /**
  87810. * This class can be used to get instrumentation data from a Babylon engine
  87811. */
  87812. var SceneInstrumentation = /** @class */ (function () {
  87813. function SceneInstrumentation(scene) {
  87814. var _this = this;
  87815. this.scene = scene;
  87816. this._captureActiveMeshesEvaluationTime = false;
  87817. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87818. this._captureRenderTargetsRenderTime = false;
  87819. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87820. this._captureFrameTime = false;
  87821. this._frameTime = new BABYLON.PerfCounter();
  87822. this._captureRenderTime = false;
  87823. this._renderTime = new BABYLON.PerfCounter();
  87824. this._captureInterFrameTime = false;
  87825. this._interFrameTime = new BABYLON.PerfCounter();
  87826. this._captureParticlesRenderTime = false;
  87827. this._particlesRenderTime = new BABYLON.PerfCounter();
  87828. this._captureSpritesRenderTime = false;
  87829. this._spritesRenderTime = new BABYLON.PerfCounter();
  87830. this._capturePhysicsTime = false;
  87831. this._physicsTime = new BABYLON.PerfCounter();
  87832. this._captureAnimationsTime = false;
  87833. this._animationsTime = new BABYLON.PerfCounter();
  87834. // Observers
  87835. this._onBeforeActiveMeshesEvaluationObserver = null;
  87836. this._onAfterActiveMeshesEvaluationObserver = null;
  87837. this._onBeforeRenderTargetsRenderObserver = null;
  87838. this._onAfterRenderTargetsRenderObserver = null;
  87839. this._onAfterRenderObserver = null;
  87840. this._onBeforeDrawPhaseObserver = null;
  87841. this._onAfterDrawPhaseObserver = null;
  87842. this._onBeforeAnimationsObserver = null;
  87843. this._onBeforeParticlesRenderingObserver = null;
  87844. this._onAfterParticlesRenderingObserver = null;
  87845. this._onBeforeSpritesRenderingObserver = null;
  87846. this._onAfterSpritesRenderingObserver = null;
  87847. this._onBeforePhysicsObserver = null;
  87848. this._onAfterPhysicsObserver = null;
  87849. this._onAfterAnimationsObserver = null;
  87850. // Before render
  87851. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87852. if (_this._captureActiveMeshesEvaluationTime) {
  87853. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87854. }
  87855. if (_this._captureRenderTargetsRenderTime) {
  87856. _this._renderTargetsRenderTime.fetchNewFrame();
  87857. }
  87858. if (_this._captureFrameTime) {
  87859. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87860. _this._frameTime.beginMonitoring();
  87861. }
  87862. if (_this._captureInterFrameTime) {
  87863. _this._interFrameTime.endMonitoring();
  87864. }
  87865. if (_this._captureParticlesRenderTime) {
  87866. _this._particlesRenderTime.fetchNewFrame();
  87867. }
  87868. if (_this._captureSpritesRenderTime) {
  87869. _this._spritesRenderTime.fetchNewFrame();
  87870. }
  87871. if (_this._captureAnimationsTime) {
  87872. _this._animationsTime.beginMonitoring();
  87873. }
  87874. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87875. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87876. });
  87877. // After render
  87878. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87879. if (_this._captureFrameTime) {
  87880. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87881. _this._frameTime.endMonitoring();
  87882. }
  87883. if (_this._captureRenderTime) {
  87884. _this._renderTime.endMonitoring(false);
  87885. }
  87886. if (_this._captureInterFrameTime) {
  87887. _this._interFrameTime.beginMonitoring();
  87888. }
  87889. });
  87890. }
  87891. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87892. // Properties
  87893. /**
  87894. * Gets the perf counter used for active meshes evaluation time
  87895. */
  87896. get: function () {
  87897. return this._activeMeshesEvaluationTime;
  87898. },
  87899. enumerable: true,
  87900. configurable: true
  87901. });
  87902. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87903. /**
  87904. * Gets the active meshes evaluation time capture status
  87905. */
  87906. get: function () {
  87907. return this._captureActiveMeshesEvaluationTime;
  87908. },
  87909. /**
  87910. * Enable or disable the active meshes evaluation time capture
  87911. */
  87912. set: function (value) {
  87913. var _this = this;
  87914. if (value === this._captureActiveMeshesEvaluationTime) {
  87915. return;
  87916. }
  87917. this._captureActiveMeshesEvaluationTime = value;
  87918. if (value) {
  87919. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87920. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87921. _this._activeMeshesEvaluationTime.beginMonitoring();
  87922. });
  87923. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87924. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87925. _this._activeMeshesEvaluationTime.endMonitoring();
  87926. });
  87927. }
  87928. else {
  87929. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87930. this._onBeforeActiveMeshesEvaluationObserver = null;
  87931. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87932. this._onAfterActiveMeshesEvaluationObserver = null;
  87933. }
  87934. },
  87935. enumerable: true,
  87936. configurable: true
  87937. });
  87938. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87939. /**
  87940. * Gets the perf counter used for render targets render time
  87941. */
  87942. get: function () {
  87943. return this._renderTargetsRenderTime;
  87944. },
  87945. enumerable: true,
  87946. configurable: true
  87947. });
  87948. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87949. /**
  87950. * Gets the render targets render time capture status
  87951. */
  87952. get: function () {
  87953. return this._captureRenderTargetsRenderTime;
  87954. },
  87955. /**
  87956. * Enable or disable the render targets render time capture
  87957. */
  87958. set: function (value) {
  87959. var _this = this;
  87960. if (value === this._captureRenderTargetsRenderTime) {
  87961. return;
  87962. }
  87963. this._captureRenderTargetsRenderTime = value;
  87964. if (value) {
  87965. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87966. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87967. _this._renderTargetsRenderTime.beginMonitoring();
  87968. });
  87969. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87970. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87971. _this._renderTargetsRenderTime.endMonitoring(false);
  87972. });
  87973. }
  87974. else {
  87975. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87976. this._onBeforeRenderTargetsRenderObserver = null;
  87977. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87978. this._onAfterRenderTargetsRenderObserver = null;
  87979. }
  87980. },
  87981. enumerable: true,
  87982. configurable: true
  87983. });
  87984. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87985. /**
  87986. * Gets the perf counter used for particles render time
  87987. */
  87988. get: function () {
  87989. return this._particlesRenderTime;
  87990. },
  87991. enumerable: true,
  87992. configurable: true
  87993. });
  87994. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87995. /**
  87996. * Gets the particles render time capture status
  87997. */
  87998. get: function () {
  87999. return this._captureParticlesRenderTime;
  88000. },
  88001. /**
  88002. * Enable or disable the particles render time capture
  88003. */
  88004. set: function (value) {
  88005. var _this = this;
  88006. if (value === this._captureParticlesRenderTime) {
  88007. return;
  88008. }
  88009. this._captureParticlesRenderTime = value;
  88010. if (value) {
  88011. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88012. BABYLON.Tools.StartPerformanceCounter("Particles");
  88013. _this._particlesRenderTime.beginMonitoring();
  88014. });
  88015. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88016. BABYLON.Tools.EndPerformanceCounter("Particles");
  88017. _this._particlesRenderTime.endMonitoring(false);
  88018. });
  88019. }
  88020. else {
  88021. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88022. this._onBeforeParticlesRenderingObserver = null;
  88023. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88024. this._onAfterParticlesRenderingObserver = null;
  88025. }
  88026. },
  88027. enumerable: true,
  88028. configurable: true
  88029. });
  88030. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88031. /**
  88032. * Gets the perf counter used for sprites render time
  88033. */
  88034. get: function () {
  88035. return this._spritesRenderTime;
  88036. },
  88037. enumerable: true,
  88038. configurable: true
  88039. });
  88040. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88041. /**
  88042. * Gets the sprites render time capture status
  88043. */
  88044. get: function () {
  88045. return this._captureSpritesRenderTime;
  88046. },
  88047. /**
  88048. * Enable or disable the sprites render time capture
  88049. */
  88050. set: function (value) {
  88051. var _this = this;
  88052. if (value === this._captureSpritesRenderTime) {
  88053. return;
  88054. }
  88055. this._captureSpritesRenderTime = value;
  88056. if (value) {
  88057. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88058. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88059. _this._spritesRenderTime.beginMonitoring();
  88060. });
  88061. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88062. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88063. _this._spritesRenderTime.endMonitoring(false);
  88064. });
  88065. }
  88066. else {
  88067. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88068. this._onBeforeSpritesRenderingObserver = null;
  88069. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88070. this._onAfterSpritesRenderingObserver = null;
  88071. }
  88072. },
  88073. enumerable: true,
  88074. configurable: true
  88075. });
  88076. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88077. /**
  88078. * Gets the perf counter used for physics time
  88079. */
  88080. get: function () {
  88081. return this._physicsTime;
  88082. },
  88083. enumerable: true,
  88084. configurable: true
  88085. });
  88086. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88087. /**
  88088. * Gets the physics time capture status
  88089. */
  88090. get: function () {
  88091. return this._capturePhysicsTime;
  88092. },
  88093. /**
  88094. * Enable or disable the physics time capture
  88095. */
  88096. set: function (value) {
  88097. var _this = this;
  88098. if (value === this._capturePhysicsTime) {
  88099. return;
  88100. }
  88101. this._capturePhysicsTime = value;
  88102. if (value) {
  88103. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88104. BABYLON.Tools.StartPerformanceCounter("Physics");
  88105. _this._physicsTime.beginMonitoring();
  88106. });
  88107. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88108. BABYLON.Tools.EndPerformanceCounter("Physics");
  88109. _this._physicsTime.endMonitoring();
  88110. });
  88111. }
  88112. else {
  88113. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88114. this._onBeforePhysicsObserver = null;
  88115. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88116. this._onAfterPhysicsObserver = null;
  88117. }
  88118. },
  88119. enumerable: true,
  88120. configurable: true
  88121. });
  88122. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88123. /**
  88124. * Gets the perf counter used for animations time
  88125. */
  88126. get: function () {
  88127. return this._animationsTime;
  88128. },
  88129. enumerable: true,
  88130. configurable: true
  88131. });
  88132. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88133. /**
  88134. * Gets the animations time capture status
  88135. */
  88136. get: function () {
  88137. return this._captureAnimationsTime;
  88138. },
  88139. /**
  88140. * Enable or disable the animations time capture
  88141. */
  88142. set: function (value) {
  88143. var _this = this;
  88144. if (value === this._captureAnimationsTime) {
  88145. return;
  88146. }
  88147. this._captureAnimationsTime = value;
  88148. if (value) {
  88149. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88150. _this._animationsTime.endMonitoring();
  88151. });
  88152. }
  88153. else {
  88154. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88155. this._onAfterAnimationsObserver = null;
  88156. }
  88157. },
  88158. enumerable: true,
  88159. configurable: true
  88160. });
  88161. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88162. /**
  88163. * Gets the perf counter used for frame time capture
  88164. */
  88165. get: function () {
  88166. return this._frameTime;
  88167. },
  88168. enumerable: true,
  88169. configurable: true
  88170. });
  88171. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88172. /**
  88173. * Gets the frame time capture status
  88174. */
  88175. get: function () {
  88176. return this._captureFrameTime;
  88177. },
  88178. /**
  88179. * Enable or disable the frame time capture
  88180. */
  88181. set: function (value) {
  88182. this._captureFrameTime = value;
  88183. },
  88184. enumerable: true,
  88185. configurable: true
  88186. });
  88187. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88188. /**
  88189. * Gets the perf counter used for inter-frames time capture
  88190. */
  88191. get: function () {
  88192. return this._interFrameTime;
  88193. },
  88194. enumerable: true,
  88195. configurable: true
  88196. });
  88197. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88198. /**
  88199. * Gets the inter-frames time capture status
  88200. */
  88201. get: function () {
  88202. return this._captureInterFrameTime;
  88203. },
  88204. /**
  88205. * Enable or disable the inter-frames time capture
  88206. */
  88207. set: function (value) {
  88208. this._captureInterFrameTime = value;
  88209. },
  88210. enumerable: true,
  88211. configurable: true
  88212. });
  88213. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88214. /**
  88215. * Gets the perf counter used for render time capture
  88216. */
  88217. get: function () {
  88218. return this._renderTime;
  88219. },
  88220. enumerable: true,
  88221. configurable: true
  88222. });
  88223. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88224. /**
  88225. * Gets the render time capture status
  88226. */
  88227. get: function () {
  88228. return this._captureRenderTime;
  88229. },
  88230. /**
  88231. * Enable or disable the render time capture
  88232. */
  88233. set: function (value) {
  88234. var _this = this;
  88235. if (value === this._captureRenderTime) {
  88236. return;
  88237. }
  88238. this._captureRenderTime = value;
  88239. if (value) {
  88240. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88241. _this._renderTime.beginMonitoring();
  88242. BABYLON.Tools.StartPerformanceCounter("Main render");
  88243. });
  88244. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88245. _this._renderTime.endMonitoring(false);
  88246. BABYLON.Tools.EndPerformanceCounter("Main render");
  88247. });
  88248. }
  88249. else {
  88250. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88251. this._onBeforeDrawPhaseObserver = null;
  88252. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88253. this._onAfterDrawPhaseObserver = null;
  88254. }
  88255. },
  88256. enumerable: true,
  88257. configurable: true
  88258. });
  88259. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88260. /**
  88261. * Gets the perf counter used for draw calls
  88262. */
  88263. get: function () {
  88264. return this.scene.getEngine()._drawCalls;
  88265. },
  88266. enumerable: true,
  88267. configurable: true
  88268. });
  88269. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88270. /**
  88271. * Gets the perf counter used for texture collisions
  88272. */
  88273. get: function () {
  88274. return this.scene.getEngine()._textureCollisions;
  88275. },
  88276. enumerable: true,
  88277. configurable: true
  88278. });
  88279. SceneInstrumentation.prototype.dispose = function () {
  88280. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88281. this._onAfterRenderObserver = null;
  88282. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88283. this._onBeforeActiveMeshesEvaluationObserver = null;
  88284. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88285. this._onAfterActiveMeshesEvaluationObserver = null;
  88286. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88287. this._onBeforeRenderTargetsRenderObserver = null;
  88288. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88289. this._onAfterRenderTargetsRenderObserver = null;
  88290. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88291. this._onBeforeAnimationsObserver = null;
  88292. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88293. this._onBeforeParticlesRenderingObserver = null;
  88294. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88295. this._onAfterParticlesRenderingObserver = null;
  88296. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88297. this._onBeforeSpritesRenderingObserver = null;
  88298. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88299. this._onAfterSpritesRenderingObserver = null;
  88300. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88301. this._onBeforeDrawPhaseObserver = null;
  88302. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88303. this._onAfterDrawPhaseObserver = null;
  88304. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88305. this._onBeforePhysicsObserver = null;
  88306. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88307. this._onAfterPhysicsObserver = null;
  88308. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88309. this._onAfterAnimationsObserver = null;
  88310. this.scene = null;
  88311. };
  88312. return SceneInstrumentation;
  88313. }());
  88314. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88315. })(BABYLON || (BABYLON = {}));
  88316. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88317. var BABYLON;
  88318. (function (BABYLON) {
  88319. var _TimeToken = /** @class */ (function () {
  88320. function _TimeToken() {
  88321. this._timeElapsedQueryEnded = false;
  88322. }
  88323. return _TimeToken;
  88324. }());
  88325. BABYLON._TimeToken = _TimeToken;
  88326. })(BABYLON || (BABYLON = {}));
  88327. //# sourceMappingURL=babylon.timeToken.js.map
  88328. var BABYLON;
  88329. (function (BABYLON) {
  88330. /**
  88331. * Background material defines definition.
  88332. * @ignore Mainly internal Use
  88333. */
  88334. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88335. __extends(BackgroundMaterialDefines, _super);
  88336. /**
  88337. * Constructor of the defines.
  88338. */
  88339. function BackgroundMaterialDefines() {
  88340. var _this = _super.call(this) || this;
  88341. /**
  88342. * True if the diffuse texture is in use.
  88343. */
  88344. _this.DIFFUSE = false;
  88345. /**
  88346. * The direct UV channel to use.
  88347. */
  88348. _this.DIFFUSEDIRECTUV = 0;
  88349. /**
  88350. * True if the diffuse texture is in gamma space.
  88351. */
  88352. _this.GAMMADIFFUSE = false;
  88353. /**
  88354. * True if the diffuse texture has opacity in the alpha channel.
  88355. */
  88356. _this.DIFFUSEHASALPHA = false;
  88357. /**
  88358. * True if you want the material to fade to transparent at grazing angle.
  88359. */
  88360. _this.OPACITYFRESNEL = false;
  88361. /**
  88362. * True if an extra blur needs to be added in the reflection.
  88363. */
  88364. _this.REFLECTIONBLUR = false;
  88365. /**
  88366. * True if you want the material to fade to reflection at grazing angle.
  88367. */
  88368. _this.REFLECTIONFRESNEL = false;
  88369. /**
  88370. * True if you want the material to falloff as far as you move away from the scene center.
  88371. */
  88372. _this.REFLECTIONFALLOFF = false;
  88373. /**
  88374. * False if the current Webgl implementation does not support the texture lod extension.
  88375. */
  88376. _this.TEXTURELODSUPPORT = false;
  88377. /**
  88378. * True to ensure the data are premultiplied.
  88379. */
  88380. _this.PREMULTIPLYALPHA = false;
  88381. /**
  88382. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88383. */
  88384. _this.USERGBCOLOR = false;
  88385. /**
  88386. * True to add noise in order to reduce the banding effect.
  88387. */
  88388. _this.NOISE = false;
  88389. /**
  88390. * is the reflection texture in BGR color scheme?
  88391. * Mainly used to solve a bug in ios10 video tag
  88392. */
  88393. _this.REFLECTIONBGR = false;
  88394. _this.IMAGEPROCESSING = false;
  88395. _this.VIGNETTE = false;
  88396. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88397. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88398. _this.TONEMAPPING = false;
  88399. _this.CONTRAST = false;
  88400. _this.COLORCURVES = false;
  88401. _this.COLORGRADING = false;
  88402. _this.COLORGRADING3D = false;
  88403. _this.SAMPLER3DGREENDEPTH = false;
  88404. _this.SAMPLER3DBGRMAP = false;
  88405. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88406. _this.EXPOSURE = false;
  88407. _this.GRAIN = false;
  88408. // Reflection.
  88409. _this.REFLECTION = false;
  88410. _this.REFLECTIONMAP_3D = false;
  88411. _this.REFLECTIONMAP_SPHERICAL = false;
  88412. _this.REFLECTIONMAP_PLANAR = false;
  88413. _this.REFLECTIONMAP_CUBIC = false;
  88414. _this.REFLECTIONMAP_PROJECTION = false;
  88415. _this.REFLECTIONMAP_SKYBOX = false;
  88416. _this.REFLECTIONMAP_EXPLICIT = false;
  88417. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88418. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88419. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88420. _this.INVERTCUBICMAP = false;
  88421. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88422. _this.LODINREFLECTIONALPHA = false;
  88423. _this.GAMMAREFLECTION = false;
  88424. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88425. // Default BJS.
  88426. _this.MAINUV1 = false;
  88427. _this.MAINUV2 = false;
  88428. _this.UV1 = false;
  88429. _this.UV2 = false;
  88430. _this.CLIPPLANE = false;
  88431. _this.POINTSIZE = false;
  88432. _this.FOG = false;
  88433. _this.NORMAL = false;
  88434. _this.NUM_BONE_INFLUENCERS = 0;
  88435. _this.BonesPerMesh = 0;
  88436. _this.INSTANCES = false;
  88437. _this.SHADOWFLOAT = false;
  88438. _this.rebuild();
  88439. return _this;
  88440. }
  88441. return BackgroundMaterialDefines;
  88442. }(BABYLON.MaterialDefines));
  88443. /**
  88444. * Background material used to create an efficient environement around your scene.
  88445. */
  88446. var BackgroundMaterial = /** @class */ (function (_super) {
  88447. __extends(BackgroundMaterial, _super);
  88448. /**
  88449. * Instantiates a Background Material in the given scene
  88450. * @param name The friendly name of the material
  88451. * @param scene The scene to add the material to
  88452. */
  88453. function BackgroundMaterial(name, scene) {
  88454. var _this = _super.call(this, name, scene) || this;
  88455. /**
  88456. * Key light Color (multiply against the R channel of the environement texture)
  88457. */
  88458. _this.primaryColor = BABYLON.Color3.White();
  88459. /**
  88460. * Key light Level (allowing HDR output of the background)
  88461. */
  88462. _this.primaryLevel = 1;
  88463. /**
  88464. * Secondary light Color (multiply against the G channel of the environement texture)
  88465. */
  88466. _this.secondaryColor = BABYLON.Color3.Gray();
  88467. /**
  88468. * Secondary light Level (allowing HDR output of the background)
  88469. */
  88470. _this.secondaryLevel = 1;
  88471. /**
  88472. * Tertiary light Color (multiply against the B channel of the environement texture)
  88473. */
  88474. _this.tertiaryColor = BABYLON.Color3.Black();
  88475. /**
  88476. * Tertiary light Level (allowing HDR output of the background)
  88477. */
  88478. _this.tertiaryLevel = 1;
  88479. /**
  88480. * Reflection Texture used in the material.
  88481. * Should be author in a specific way for the best result (refer to the documentation).
  88482. */
  88483. _this.reflectionTexture = null;
  88484. /**
  88485. * Reflection Texture level of blur.
  88486. *
  88487. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88488. * texture twice.
  88489. */
  88490. _this.reflectionBlur = 0;
  88491. /**
  88492. * Diffuse Texture used in the material.
  88493. * Should be author in a specific way for the best result (refer to the documentation).
  88494. */
  88495. _this.diffuseTexture = null;
  88496. _this._shadowLights = null;
  88497. /**
  88498. * Specify the list of lights casting shadow on the material.
  88499. * All scene shadow lights will be included if null.
  88500. */
  88501. _this.shadowLights = null;
  88502. /**
  88503. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88504. * soft lighting on the background.
  88505. */
  88506. _this.shadowBlurScale = 1;
  88507. /**
  88508. * Helps adjusting the shadow to a softer level if required.
  88509. * 0 means black shadows and 1 means no shadows.
  88510. */
  88511. _this.shadowLevel = 0;
  88512. /**
  88513. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88514. * It is usually zero but might be interesting to modify according to your setup.
  88515. */
  88516. _this.sceneCenter = BABYLON.Vector3.Zero();
  88517. /**
  88518. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88519. * This helps ensuring a nice transition when the camera goes under the ground.
  88520. */
  88521. _this.opacityFresnel = true;
  88522. /**
  88523. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88524. * This helps adding a mirror texture on the ground.
  88525. */
  88526. _this.reflectionFresnel = false;
  88527. /**
  88528. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88529. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88530. */
  88531. _this.reflectionFalloffDistance = 0.0;
  88532. /**
  88533. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88534. */
  88535. _this.reflectionAmount = 1.0;
  88536. /**
  88537. * This specifies the weight of the reflection at grazing angle.
  88538. */
  88539. _this.reflectionReflectance0 = 0.05;
  88540. /**
  88541. * This specifies the weight of the reflection at a perpendicular point of view.
  88542. */
  88543. _this.reflectionReflectance90 = 0.5;
  88544. /**
  88545. * Helps to directly use the maps channels instead of their level.
  88546. */
  88547. _this.useRGBColor = true;
  88548. /**
  88549. * This helps reducing the banding effect that could occur on the background.
  88550. */
  88551. _this.enableNoise = false;
  88552. _this._fovMultiplier = 1.0;
  88553. /**
  88554. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88555. * @type {boolean}
  88556. */
  88557. _this.useEquirectangularFOV = false;
  88558. _this._maxSimultaneousLights = 4;
  88559. /**
  88560. * Number of Simultaneous lights allowed on the material.
  88561. */
  88562. _this.maxSimultaneousLights = 4;
  88563. /**
  88564. * Keep track of the image processing observer to allow dispose and replace.
  88565. */
  88566. _this._imageProcessingObserver = null;
  88567. /**
  88568. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88569. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88570. */
  88571. _this.switchToBGR = false;
  88572. // Temp values kept as cache in the material.
  88573. _this._renderTargets = new BABYLON.SmartArray(16);
  88574. _this._reflectionControls = BABYLON.Vector4.Zero();
  88575. // Setup the default processing configuration to the scene.
  88576. _this._attachImageProcessingConfiguration(null);
  88577. _this.getRenderTargetTextures = function () {
  88578. _this._renderTargets.reset();
  88579. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88580. _this._renderTargets.push(_this._diffuseTexture);
  88581. }
  88582. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88583. _this._renderTargets.push(_this._reflectionTexture);
  88584. }
  88585. return _this._renderTargets;
  88586. };
  88587. return _this;
  88588. }
  88589. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88590. /**
  88591. * Sets the reflection reflectance fresnel values according to the default standard
  88592. * empirically know to work well :-)
  88593. */
  88594. set: function (value) {
  88595. var reflectionWeight = value;
  88596. if (reflectionWeight < 0.5) {
  88597. reflectionWeight = reflectionWeight * 2.0;
  88598. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88599. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88600. }
  88601. else {
  88602. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88603. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88604. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88605. }
  88606. },
  88607. enumerable: true,
  88608. configurable: true
  88609. });
  88610. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88611. /**
  88612. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88613. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88614. * Recommended to be keep at 1.0 except for special cases.
  88615. */
  88616. get: function () {
  88617. return this._fovMultiplier;
  88618. },
  88619. set: function (value) {
  88620. if (isNaN(value)) {
  88621. value = 1.0;
  88622. }
  88623. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88624. },
  88625. enumerable: true,
  88626. configurable: true
  88627. });
  88628. /**
  88629. * Attaches a new image processing configuration to the PBR Material.
  88630. * @param configuration (if null the scene configuration will be use)
  88631. */
  88632. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88633. var _this = this;
  88634. if (configuration === this._imageProcessingConfiguration) {
  88635. return;
  88636. }
  88637. // Detaches observer.
  88638. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88639. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88640. }
  88641. // Pick the scene configuration if needed.
  88642. if (!configuration) {
  88643. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88644. }
  88645. else {
  88646. this._imageProcessingConfiguration = configuration;
  88647. }
  88648. // Attaches observer.
  88649. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88650. _this._markAllSubMeshesAsImageProcessingDirty();
  88651. });
  88652. };
  88653. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88654. /**
  88655. * Gets the image processing configuration used either in this material.
  88656. */
  88657. get: function () {
  88658. return this._imageProcessingConfiguration;
  88659. },
  88660. /**
  88661. * Sets the Default image processing configuration used either in the this material.
  88662. *
  88663. * If sets to null, the scene one is in use.
  88664. */
  88665. set: function (value) {
  88666. this._attachImageProcessingConfiguration(value);
  88667. // Ensure the effect will be rebuilt.
  88668. this._markAllSubMeshesAsTexturesDirty();
  88669. },
  88670. enumerable: true,
  88671. configurable: true
  88672. });
  88673. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88674. /**
  88675. * Gets wether the color curves effect is enabled.
  88676. */
  88677. get: function () {
  88678. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88679. },
  88680. /**
  88681. * Sets wether the color curves effect is enabled.
  88682. */
  88683. set: function (value) {
  88684. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88685. },
  88686. enumerable: true,
  88687. configurable: true
  88688. });
  88689. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88690. /**
  88691. * Gets wether the color grading effect is enabled.
  88692. */
  88693. get: function () {
  88694. return this.imageProcessingConfiguration.colorGradingEnabled;
  88695. },
  88696. /**
  88697. * Gets wether the color grading effect is enabled.
  88698. */
  88699. set: function (value) {
  88700. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88701. },
  88702. enumerable: true,
  88703. configurable: true
  88704. });
  88705. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88706. /**
  88707. * Gets wether tonemapping is enabled or not.
  88708. */
  88709. get: function () {
  88710. return this._imageProcessingConfiguration.toneMappingEnabled;
  88711. },
  88712. /**
  88713. * Sets wether tonemapping is enabled or not
  88714. */
  88715. set: function (value) {
  88716. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88717. },
  88718. enumerable: true,
  88719. configurable: true
  88720. });
  88721. ;
  88722. ;
  88723. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88724. /**
  88725. * The camera exposure used on this material.
  88726. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88727. * This corresponds to a photographic exposure.
  88728. */
  88729. get: function () {
  88730. return this._imageProcessingConfiguration.exposure;
  88731. },
  88732. /**
  88733. * The camera exposure used on this material.
  88734. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88735. * This corresponds to a photographic exposure.
  88736. */
  88737. set: function (value) {
  88738. this._imageProcessingConfiguration.exposure = value;
  88739. },
  88740. enumerable: true,
  88741. configurable: true
  88742. });
  88743. ;
  88744. ;
  88745. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88746. /**
  88747. * Gets The camera contrast used on this material.
  88748. */
  88749. get: function () {
  88750. return this._imageProcessingConfiguration.contrast;
  88751. },
  88752. /**
  88753. * Sets The camera contrast used on this material.
  88754. */
  88755. set: function (value) {
  88756. this._imageProcessingConfiguration.contrast = value;
  88757. },
  88758. enumerable: true,
  88759. configurable: true
  88760. });
  88761. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88762. /**
  88763. * Gets the Color Grading 2D Lookup Texture.
  88764. */
  88765. get: function () {
  88766. return this._imageProcessingConfiguration.colorGradingTexture;
  88767. },
  88768. /**
  88769. * Sets the Color Grading 2D Lookup Texture.
  88770. */
  88771. set: function (value) {
  88772. this.imageProcessingConfiguration.colorGradingTexture = value;
  88773. },
  88774. enumerable: true,
  88775. configurable: true
  88776. });
  88777. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88778. /**
  88779. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88780. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88781. * 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;
  88782. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88783. */
  88784. get: function () {
  88785. return this.imageProcessingConfiguration.colorCurves;
  88786. },
  88787. /**
  88788. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88789. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88790. * 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;
  88791. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88792. */
  88793. set: function (value) {
  88794. this.imageProcessingConfiguration.colorCurves = value;
  88795. },
  88796. enumerable: true,
  88797. configurable: true
  88798. });
  88799. /**
  88800. * The entire material has been created in order to prevent overdraw.
  88801. * @returns false
  88802. */
  88803. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88804. return true;
  88805. };
  88806. /**
  88807. * The entire material has been created in order to prevent overdraw.
  88808. * @returns true if blending is enable
  88809. */
  88810. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88811. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88812. };
  88813. /**
  88814. * Checks wether the material is ready to be rendered for a given mesh.
  88815. * @param mesh The mesh to render
  88816. * @param subMesh The submesh to check against
  88817. * @param useInstances Specify wether or not the material is used with instances
  88818. * @returns true if all the dependencies are ready (Textures, Effects...)
  88819. */
  88820. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88821. var _this = this;
  88822. if (useInstances === void 0) { useInstances = false; }
  88823. if (subMesh.effect && this.isFrozen) {
  88824. if (this._wasPreviouslyReady) {
  88825. return true;
  88826. }
  88827. }
  88828. if (!subMesh._materialDefines) {
  88829. subMesh._materialDefines = new BackgroundMaterialDefines();
  88830. }
  88831. var scene = this.getScene();
  88832. var defines = subMesh._materialDefines;
  88833. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88834. if (defines._renderId === scene.getRenderId()) {
  88835. return true;
  88836. }
  88837. }
  88838. var engine = scene.getEngine();
  88839. // Lights
  88840. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88841. defines._needNormals = true;
  88842. // Textures
  88843. if (defines._areTexturesDirty) {
  88844. defines._needUVs = false;
  88845. if (scene.texturesEnabled) {
  88846. if (scene.getEngine().getCaps().textureLOD) {
  88847. defines.TEXTURELODSUPPORT = true;
  88848. }
  88849. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88850. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88851. return false;
  88852. }
  88853. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88854. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88855. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88856. defines.OPACITYFRESNEL = this._opacityFresnel;
  88857. }
  88858. else {
  88859. defines.DIFFUSE = false;
  88860. defines.DIFFUSEHASALPHA = false;
  88861. defines.GAMMADIFFUSE = false;
  88862. defines.OPACITYFRESNEL = false;
  88863. }
  88864. var reflectionTexture = this._reflectionTexture;
  88865. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88866. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88867. return false;
  88868. }
  88869. defines.REFLECTION = true;
  88870. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88871. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88872. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88873. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88874. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88875. defines.REFLECTIONBGR = this.switchToBGR;
  88876. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88877. defines.INVERTCUBICMAP = true;
  88878. }
  88879. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88880. switch (reflectionTexture.coordinatesMode) {
  88881. case BABYLON.Texture.CUBIC_MODE:
  88882. case BABYLON.Texture.INVCUBIC_MODE:
  88883. defines.REFLECTIONMAP_CUBIC = true;
  88884. break;
  88885. case BABYLON.Texture.EXPLICIT_MODE:
  88886. defines.REFLECTIONMAP_EXPLICIT = true;
  88887. break;
  88888. case BABYLON.Texture.PLANAR_MODE:
  88889. defines.REFLECTIONMAP_PLANAR = true;
  88890. break;
  88891. case BABYLON.Texture.PROJECTION_MODE:
  88892. defines.REFLECTIONMAP_PROJECTION = true;
  88893. break;
  88894. case BABYLON.Texture.SKYBOX_MODE:
  88895. defines.REFLECTIONMAP_SKYBOX = true;
  88896. break;
  88897. case BABYLON.Texture.SPHERICAL_MODE:
  88898. defines.REFLECTIONMAP_SPHERICAL = true;
  88899. break;
  88900. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88901. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88902. break;
  88903. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88904. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88905. break;
  88906. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88907. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88908. break;
  88909. }
  88910. if (this.reflectionFresnel) {
  88911. defines.REFLECTIONFRESNEL = true;
  88912. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88913. this._reflectionControls.x = this.reflectionAmount;
  88914. this._reflectionControls.y = this.reflectionReflectance0;
  88915. this._reflectionControls.z = this.reflectionReflectance90;
  88916. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88917. }
  88918. else {
  88919. defines.REFLECTIONFRESNEL = false;
  88920. defines.REFLECTIONFALLOFF = false;
  88921. }
  88922. }
  88923. else {
  88924. defines.REFLECTION = false;
  88925. defines.REFLECTIONFALLOFF = false;
  88926. defines.REFLECTIONBLUR = false;
  88927. defines.REFLECTIONMAP_3D = false;
  88928. defines.REFLECTIONMAP_SPHERICAL = false;
  88929. defines.REFLECTIONMAP_PLANAR = false;
  88930. defines.REFLECTIONMAP_CUBIC = false;
  88931. defines.REFLECTIONMAP_PROJECTION = false;
  88932. defines.REFLECTIONMAP_SKYBOX = false;
  88933. defines.REFLECTIONMAP_EXPLICIT = false;
  88934. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88935. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88936. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88937. defines.INVERTCUBICMAP = false;
  88938. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88939. defines.LODINREFLECTIONALPHA = false;
  88940. defines.GAMMAREFLECTION = false;
  88941. }
  88942. }
  88943. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88944. defines.USERGBCOLOR = this._useRGBColor;
  88945. defines.NOISE = this._enableNoise;
  88946. }
  88947. if (defines._areImageProcessingDirty) {
  88948. if (!this._imageProcessingConfiguration.isReady()) {
  88949. return false;
  88950. }
  88951. this._imageProcessingConfiguration.prepareDefines(defines);
  88952. }
  88953. // Misc.
  88954. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88955. // Values that need to be evaluated on every frame
  88956. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88957. // Attribs
  88958. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88959. if (mesh) {
  88960. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88961. mesh.createNormals(true);
  88962. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88963. }
  88964. }
  88965. }
  88966. // Get correct effect
  88967. if (defines.isDirty) {
  88968. defines.markAsProcessed();
  88969. scene.resetCachedMaterial();
  88970. // Fallbacks
  88971. var fallbacks = new BABYLON.EffectFallbacks();
  88972. if (defines.FOG) {
  88973. fallbacks.addFallback(0, "FOG");
  88974. }
  88975. if (defines.POINTSIZE) {
  88976. fallbacks.addFallback(1, "POINTSIZE");
  88977. }
  88978. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88979. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88980. fallbacks.addCPUSkinningFallback(0, mesh);
  88981. }
  88982. //Attributes
  88983. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88984. if (defines.NORMAL) {
  88985. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88986. }
  88987. if (defines.UV1) {
  88988. attribs.push(BABYLON.VertexBuffer.UVKind);
  88989. }
  88990. if (defines.UV2) {
  88991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88992. }
  88993. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88994. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88995. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88996. "vFogInfos", "vFogColor", "pointSize",
  88997. "vClipPlane", "mBones",
  88998. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88999. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89000. "shadowLevel", "alpha",
  89001. "vBackgroundCenter", "vReflectionControl",
  89002. "vDiffuseInfos", "diffuseMatrix",
  89003. ];
  89004. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89005. var uniformBuffers = ["Material", "Scene"];
  89006. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89007. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89008. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89009. uniformsNames: uniforms,
  89010. uniformBuffersNames: uniformBuffers,
  89011. samplers: samplers,
  89012. defines: defines,
  89013. maxSimultaneousLights: this._maxSimultaneousLights
  89014. });
  89015. var onCompiled = function (effect) {
  89016. if (_this.onCompiled) {
  89017. _this.onCompiled(effect);
  89018. }
  89019. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89020. };
  89021. var join = defines.toString();
  89022. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89023. attributes: attribs,
  89024. uniformsNames: uniforms,
  89025. uniformBuffersNames: uniformBuffers,
  89026. samplers: samplers,
  89027. defines: join,
  89028. fallbacks: fallbacks,
  89029. onCompiled: onCompiled,
  89030. onError: this.onError,
  89031. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89032. }, engine), defines);
  89033. this.buildUniformLayout();
  89034. }
  89035. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89036. return false;
  89037. }
  89038. defines._renderId = scene.getRenderId();
  89039. this._wasPreviouslyReady = true;
  89040. return true;
  89041. };
  89042. /**
  89043. * Build the uniform buffer used in the material.
  89044. */
  89045. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89046. // Order is important !
  89047. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89048. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89049. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89050. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89051. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89052. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89053. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89054. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89055. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89056. this._uniformBuffer.addUniform("pointSize", 1);
  89057. this._uniformBuffer.addUniform("shadowLevel", 1);
  89058. this._uniformBuffer.addUniform("alpha", 1);
  89059. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89060. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89061. this._uniformBuffer.create();
  89062. };
  89063. /**
  89064. * Unbind the material.
  89065. */
  89066. BackgroundMaterial.prototype.unbind = function () {
  89067. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89068. this._uniformBuffer.setTexture("diffuseSampler", null);
  89069. }
  89070. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89071. this._uniformBuffer.setTexture("reflectionSampler", null);
  89072. }
  89073. _super.prototype.unbind.call(this);
  89074. };
  89075. /**
  89076. * Bind only the world matrix to the material.
  89077. * @param world The world matrix to bind.
  89078. */
  89079. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89080. this._activeEffect.setMatrix("world", world);
  89081. };
  89082. /**
  89083. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89084. * @param world The world matrix to bind.
  89085. * @param subMesh The submesh to bind for.
  89086. */
  89087. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89088. var scene = this.getScene();
  89089. var defines = subMesh._materialDefines;
  89090. if (!defines) {
  89091. return;
  89092. }
  89093. var effect = subMesh.effect;
  89094. if (!effect) {
  89095. return;
  89096. }
  89097. this._activeEffect = effect;
  89098. // Matrices
  89099. this.bindOnlyWorldMatrix(world);
  89100. // Bones
  89101. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89102. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89103. if (mustRebind) {
  89104. this._uniformBuffer.bindToEffect(effect, "Material");
  89105. this.bindViewProjection(effect);
  89106. var reflectionTexture = this._reflectionTexture;
  89107. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89108. // Texture uniforms
  89109. if (scene.texturesEnabled) {
  89110. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89111. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89112. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89113. }
  89114. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89115. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89116. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89117. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89118. }
  89119. }
  89120. if (this.shadowLevel > 0) {
  89121. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89122. }
  89123. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89124. // Point size
  89125. if (this.pointsCloud) {
  89126. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89127. }
  89128. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89129. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89130. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89131. }
  89132. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89133. // Textures
  89134. if (scene.texturesEnabled) {
  89135. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89136. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89137. }
  89138. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89139. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89140. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89141. }
  89142. else if (!defines.REFLECTIONBLUR) {
  89143. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89144. }
  89145. else {
  89146. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89147. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89148. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89149. }
  89150. if (defines.REFLECTIONFRESNEL) {
  89151. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89152. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89153. }
  89154. }
  89155. }
  89156. // Clip plane
  89157. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89158. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89159. }
  89160. if (mustRebind || !this.isFrozen) {
  89161. if (scene.lightsEnabled) {
  89162. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89163. }
  89164. // View
  89165. this.bindView(effect);
  89166. // Fog
  89167. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89168. // image processing
  89169. this._imageProcessingConfiguration.bind(this._activeEffect);
  89170. }
  89171. this._uniformBuffer.update();
  89172. this._afterBind(mesh);
  89173. };
  89174. /**
  89175. * Dispose the material.
  89176. * @param forceDisposeEffect Force disposal of the associated effect.
  89177. * @param forceDisposeTextures Force disposal of the associated textures.
  89178. */
  89179. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89180. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89181. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89182. if (forceDisposeTextures) {
  89183. if (this.diffuseTexture) {
  89184. this.diffuseTexture.dispose();
  89185. }
  89186. if (this.reflectionTexture) {
  89187. this.reflectionTexture.dispose();
  89188. }
  89189. }
  89190. this._renderTargets.dispose();
  89191. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89192. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89193. }
  89194. _super.prototype.dispose.call(this, forceDisposeEffect);
  89195. };
  89196. /**
  89197. * Clones the material.
  89198. * @param name The cloned name.
  89199. * @returns The cloned material.
  89200. */
  89201. BackgroundMaterial.prototype.clone = function (name) {
  89202. var _this = this;
  89203. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89204. };
  89205. /**
  89206. * Serializes the current material to its JSON representation.
  89207. * @returns The JSON representation.
  89208. */
  89209. BackgroundMaterial.prototype.serialize = function () {
  89210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89211. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89212. return serializationObject;
  89213. };
  89214. /**
  89215. * Gets the class name of the material
  89216. * @returns "BackgroundMaterial"
  89217. */
  89218. BackgroundMaterial.prototype.getClassName = function () {
  89219. return "BackgroundMaterial";
  89220. };
  89221. /**
  89222. * Parse a JSON input to create back a background material.
  89223. * @param source The JSON data to parse
  89224. * @param scene The scene to create the parsed material in
  89225. * @param rootUrl The root url of the assets the material depends upon
  89226. * @returns the instantiated BackgroundMaterial.
  89227. */
  89228. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89229. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89230. };
  89231. /**
  89232. * Standard reflectance value at parallel view angle.
  89233. */
  89234. BackgroundMaterial.StandardReflectance0 = 0.05;
  89235. /**
  89236. * Standard reflectance value at grazing angle.
  89237. */
  89238. BackgroundMaterial.StandardReflectance90 = 0.5;
  89239. __decorate([
  89240. BABYLON.serializeAsColor3()
  89241. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89242. __decorate([
  89243. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89244. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89245. __decorate([
  89246. BABYLON.serialize()
  89247. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89248. __decorate([
  89249. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89250. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89251. __decorate([
  89252. BABYLON.serializeAsColor3()
  89253. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89254. __decorate([
  89255. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89256. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89257. __decorate([
  89258. BABYLON.serialize()
  89259. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89260. __decorate([
  89261. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89262. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89263. __decorate([
  89264. BABYLON.serializeAsColor3()
  89265. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89266. __decorate([
  89267. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89268. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89269. __decorate([
  89270. BABYLON.serialize()
  89271. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89272. __decorate([
  89273. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89274. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89275. __decorate([
  89276. BABYLON.serializeAsTexture()
  89277. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89278. __decorate([
  89279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89280. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89281. __decorate([
  89282. BABYLON.serialize()
  89283. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89284. __decorate([
  89285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89286. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89287. __decorate([
  89288. BABYLON.serializeAsTexture()
  89289. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89290. __decorate([
  89291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89292. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89293. __decorate([
  89294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89295. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89296. __decorate([
  89297. BABYLON.serialize()
  89298. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89299. __decorate([
  89300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89301. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89302. __decorate([
  89303. BABYLON.serialize()
  89304. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89305. __decorate([
  89306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89307. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89308. __decorate([
  89309. BABYLON.serializeAsVector3()
  89310. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89311. __decorate([
  89312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89313. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89314. __decorate([
  89315. BABYLON.serialize()
  89316. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89317. __decorate([
  89318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89319. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89320. __decorate([
  89321. BABYLON.serialize()
  89322. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89323. __decorate([
  89324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89325. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89326. __decorate([
  89327. BABYLON.serialize()
  89328. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89329. __decorate([
  89330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89331. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89332. __decorate([
  89333. BABYLON.serialize()
  89334. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89335. __decorate([
  89336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89337. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89338. __decorate([
  89339. BABYLON.serialize()
  89340. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89341. __decorate([
  89342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89343. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89344. __decorate([
  89345. BABYLON.serialize()
  89346. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89347. __decorate([
  89348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89349. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89350. __decorate([
  89351. BABYLON.serialize()
  89352. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89353. __decorate([
  89354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89355. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89356. __decorate([
  89357. BABYLON.serialize()
  89358. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89359. __decorate([
  89360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89361. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89362. __decorate([
  89363. BABYLON.serialize()
  89364. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89365. __decorate([
  89366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89367. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89368. __decorate([
  89369. BABYLON.serializeAsImageProcessingConfiguration()
  89370. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89371. return BackgroundMaterial;
  89372. }(BABYLON.PushMaterial));
  89373. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89374. })(BABYLON || (BABYLON = {}));
  89375. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89376. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89377. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89378. s = arguments[i];
  89379. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89380. t[p] = s[p];
  89381. }
  89382. return t;
  89383. };
  89384. var BABYLON;
  89385. (function (BABYLON) {
  89386. /**
  89387. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89388. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89389. * It also helps with the default setup of your imageProcessing configuration.
  89390. */
  89391. var EnvironmentHelper = /** @class */ (function () {
  89392. /**
  89393. * constructor
  89394. * @param options
  89395. * @param scene The scene to add the material to
  89396. */
  89397. function EnvironmentHelper(options, scene) {
  89398. var _this = this;
  89399. this._errorHandler = function (message, exception) {
  89400. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89401. };
  89402. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89403. this._scene = scene;
  89404. this.onErrorObservable = new BABYLON.Observable();
  89405. this._setupBackground();
  89406. this._setupImageProcessing();
  89407. }
  89408. /**
  89409. * Creates the default options for the helper.
  89410. */
  89411. EnvironmentHelper._getDefaultOptions = function () {
  89412. return {
  89413. createGround: true,
  89414. groundSize: 15,
  89415. groundTexture: this._groundTextureCDNUrl,
  89416. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89417. groundOpacity: 0.9,
  89418. enableGroundShadow: true,
  89419. groundShadowLevel: 0.5,
  89420. enableGroundMirror: false,
  89421. groundMirrorSizeRatio: 0.3,
  89422. groundMirrorBlurKernel: 64,
  89423. groundMirrorAmount: 1,
  89424. groundMirrorFresnelWeight: 1,
  89425. groundMirrorFallOffDistance: 0,
  89426. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89427. groundYBias: 0.00001,
  89428. createSkybox: true,
  89429. skyboxSize: 20,
  89430. skyboxTexture: this._skyboxTextureCDNUrl,
  89431. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89432. backgroundYRotation: 0,
  89433. sizeAuto: true,
  89434. rootPosition: BABYLON.Vector3.Zero(),
  89435. setupImageProcessing: true,
  89436. environmentTexture: this._environmentTextureCDNUrl,
  89437. cameraExposure: 0.8,
  89438. cameraContrast: 1.2,
  89439. toneMappingEnabled: true,
  89440. };
  89441. };
  89442. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89443. /**
  89444. * Gets the root mesh created by the helper.
  89445. */
  89446. get: function () {
  89447. return this._rootMesh;
  89448. },
  89449. enumerable: true,
  89450. configurable: true
  89451. });
  89452. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89453. /**
  89454. * Gets the skybox created by the helper.
  89455. */
  89456. get: function () {
  89457. return this._skybox;
  89458. },
  89459. enumerable: true,
  89460. configurable: true
  89461. });
  89462. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89463. /**
  89464. * Gets the skybox texture created by the helper.
  89465. */
  89466. get: function () {
  89467. return this._skyboxTexture;
  89468. },
  89469. enumerable: true,
  89470. configurable: true
  89471. });
  89472. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89473. /**
  89474. * Gets the skybox material created by the helper.
  89475. */
  89476. get: function () {
  89477. return this._skyboxMaterial;
  89478. },
  89479. enumerable: true,
  89480. configurable: true
  89481. });
  89482. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89483. /**
  89484. * Gets the ground mesh created by the helper.
  89485. */
  89486. get: function () {
  89487. return this._ground;
  89488. },
  89489. enumerable: true,
  89490. configurable: true
  89491. });
  89492. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89493. /**
  89494. * Gets the ground texture created by the helper.
  89495. */
  89496. get: function () {
  89497. return this._groundTexture;
  89498. },
  89499. enumerable: true,
  89500. configurable: true
  89501. });
  89502. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89503. /**
  89504. * Gets the ground mirror created by the helper.
  89505. */
  89506. get: function () {
  89507. return this._groundMirror;
  89508. },
  89509. enumerable: true,
  89510. configurable: true
  89511. });
  89512. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89513. /**
  89514. * Gets the ground mirror render list to helps pushing the meshes
  89515. * you wish in the ground reflection.
  89516. */
  89517. get: function () {
  89518. if (this._groundMirror) {
  89519. return this._groundMirror.renderList;
  89520. }
  89521. return null;
  89522. },
  89523. enumerable: true,
  89524. configurable: true
  89525. });
  89526. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89527. /**
  89528. * Gets the ground material created by the helper.
  89529. */
  89530. get: function () {
  89531. return this._groundMaterial;
  89532. },
  89533. enumerable: true,
  89534. configurable: true
  89535. });
  89536. /**
  89537. * Updates the background according to the new options
  89538. * @param options
  89539. */
  89540. EnvironmentHelper.prototype.updateOptions = function (options) {
  89541. var newOptions = __assign({}, this._options, options);
  89542. if (this._ground && !newOptions.createGround) {
  89543. this._ground.dispose();
  89544. this._ground = null;
  89545. }
  89546. if (this._groundMaterial && !newOptions.createGround) {
  89547. this._groundMaterial.dispose();
  89548. this._groundMaterial = null;
  89549. }
  89550. if (this._groundTexture) {
  89551. if (this._options.groundTexture != newOptions.groundTexture) {
  89552. this._groundTexture.dispose();
  89553. this._groundTexture = null;
  89554. }
  89555. }
  89556. if (this._skybox && !newOptions.createSkybox) {
  89557. this._skybox.dispose();
  89558. this._skybox = null;
  89559. }
  89560. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89561. this._skyboxMaterial.dispose();
  89562. this._skyboxMaterial = null;
  89563. }
  89564. if (this._skyboxTexture) {
  89565. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89566. this._skyboxTexture.dispose();
  89567. this._skyboxTexture = null;
  89568. }
  89569. }
  89570. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89571. this._groundMirror.dispose();
  89572. this._groundMirror = null;
  89573. }
  89574. if (this._scene.environmentTexture) {
  89575. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89576. this._scene.environmentTexture.dispose();
  89577. }
  89578. }
  89579. this._options = newOptions;
  89580. this._setupBackground();
  89581. this._setupImageProcessing();
  89582. };
  89583. /**
  89584. * Sets the primary color of all the available elements.
  89585. * @param color
  89586. */
  89587. EnvironmentHelper.prototype.setMainColor = function (color) {
  89588. if (this.groundMaterial) {
  89589. this.groundMaterial.primaryColor = color;
  89590. }
  89591. if (this.skyboxMaterial) {
  89592. this.skyboxMaterial.primaryColor = color;
  89593. }
  89594. if (this.groundMirror) {
  89595. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89596. }
  89597. };
  89598. /**
  89599. * Setup the image processing according to the specified options.
  89600. */
  89601. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89602. if (this._options.setupImageProcessing) {
  89603. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89604. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89605. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89606. this._setupEnvironmentTexture();
  89607. }
  89608. };
  89609. /**
  89610. * Setup the environment texture according to the specified options.
  89611. */
  89612. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89613. if (this._scene.environmentTexture) {
  89614. return;
  89615. }
  89616. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89617. this._scene.environmentTexture = this._options.environmentTexture;
  89618. return;
  89619. }
  89620. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89621. this._scene.environmentTexture = environmentTexture;
  89622. };
  89623. /**
  89624. * Setup the background according to the specified options.
  89625. */
  89626. EnvironmentHelper.prototype._setupBackground = function () {
  89627. if (!this._rootMesh) {
  89628. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89629. }
  89630. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89631. var sceneSize = this._getSceneSize();
  89632. if (this._options.createGround) {
  89633. this._setupGround(sceneSize);
  89634. this._setupGroundMaterial();
  89635. this._setupGroundDiffuseTexture();
  89636. if (this._options.enableGroundMirror) {
  89637. this._setupGroundMirrorTexture(sceneSize);
  89638. }
  89639. this._setupMirrorInGroundMaterial();
  89640. }
  89641. if (this._options.createSkybox) {
  89642. this._setupSkybox(sceneSize);
  89643. this._setupSkyboxMaterial();
  89644. this._setupSkyboxReflectionTexture();
  89645. }
  89646. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89647. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89648. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89649. };
  89650. /**
  89651. * Get the scene sizes according to the setup.
  89652. */
  89653. EnvironmentHelper.prototype._getSceneSize = function () {
  89654. var _this = this;
  89655. var groundSize = this._options.groundSize;
  89656. var skyboxSize = this._options.skyboxSize;
  89657. var rootPosition = this._options.rootPosition;
  89658. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89659. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89660. }
  89661. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89662. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89663. });
  89664. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89665. if (this._options.sizeAuto) {
  89666. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89667. this._scene.activeCamera.upperRadiusLimit) {
  89668. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89669. skyboxSize = groundSize;
  89670. }
  89671. var sceneDiagonalLenght = sceneDiagonal.length();
  89672. if (sceneDiagonalLenght > groundSize) {
  89673. groundSize = sceneDiagonalLenght * 2;
  89674. skyboxSize = groundSize;
  89675. }
  89676. // 10 % bigger.
  89677. groundSize *= 1.1;
  89678. skyboxSize *= 1.5;
  89679. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89680. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89681. }
  89682. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89683. };
  89684. /**
  89685. * Setup the ground according to the specified options.
  89686. */
  89687. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89688. var _this = this;
  89689. if (!this._ground) {
  89690. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89691. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89692. this._ground.parent = this._rootMesh;
  89693. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89694. }
  89695. this._ground.receiveShadows = this._options.enableGroundShadow;
  89696. };
  89697. /**
  89698. * Setup the ground material according to the specified options.
  89699. */
  89700. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89701. if (!this._groundMaterial) {
  89702. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89703. }
  89704. this._groundMaterial.alpha = this._options.groundOpacity;
  89705. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89706. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89707. this._groundMaterial.primaryLevel = 1;
  89708. this._groundMaterial.primaryColor = this._options.groundColor;
  89709. this._groundMaterial.secondaryLevel = 0;
  89710. this._groundMaterial.tertiaryLevel = 0;
  89711. this._groundMaterial.useRGBColor = false;
  89712. this._groundMaterial.enableNoise = true;
  89713. if (this._ground) {
  89714. this._ground.material = this._groundMaterial;
  89715. }
  89716. };
  89717. /**
  89718. * Setup the ground diffuse texture according to the specified options.
  89719. */
  89720. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89721. if (!this._groundMaterial) {
  89722. return;
  89723. }
  89724. if (this._groundTexture) {
  89725. return;
  89726. }
  89727. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89728. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89729. return;
  89730. }
  89731. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89732. diffuseTexture.gammaSpace = false;
  89733. diffuseTexture.hasAlpha = true;
  89734. this._groundMaterial.diffuseTexture = diffuseTexture;
  89735. };
  89736. /**
  89737. * Setup the ground mirror texture according to the specified options.
  89738. */
  89739. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89740. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89741. if (!this._groundMirror) {
  89742. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89743. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89744. this._groundMirror.anisotropicFilteringLevel = 1;
  89745. this._groundMirror.wrapU = wrapping;
  89746. this._groundMirror.wrapV = wrapping;
  89747. this._groundMirror.gammaSpace = false;
  89748. if (this._groundMirror.renderList) {
  89749. for (var i = 0; i < this._scene.meshes.length; i++) {
  89750. var mesh = this._scene.meshes[i];
  89751. if (mesh !== this._ground &&
  89752. mesh !== this._skybox &&
  89753. mesh !== this._rootMesh) {
  89754. this._groundMirror.renderList.push(mesh);
  89755. }
  89756. }
  89757. }
  89758. }
  89759. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89760. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89761. };
  89762. /**
  89763. * Setup the ground to receive the mirror texture.
  89764. */
  89765. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89766. if (this._groundMaterial) {
  89767. this._groundMaterial.reflectionTexture = this._groundMirror;
  89768. this._groundMaterial.reflectionFresnel = true;
  89769. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89770. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89771. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89772. }
  89773. };
  89774. /**
  89775. * Setup the skybox according to the specified options.
  89776. */
  89777. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89778. var _this = this;
  89779. if (!this._skybox) {
  89780. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89781. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89782. }
  89783. this._skybox.parent = this._rootMesh;
  89784. };
  89785. /**
  89786. * Setup the skybox material according to the specified options.
  89787. */
  89788. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89789. if (!this._skybox) {
  89790. return;
  89791. }
  89792. if (!this._skyboxMaterial) {
  89793. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89794. }
  89795. this._skyboxMaterial.useRGBColor = false;
  89796. this._skyboxMaterial.primaryLevel = 1;
  89797. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89798. this._skyboxMaterial.secondaryLevel = 0;
  89799. this._skyboxMaterial.tertiaryLevel = 0;
  89800. this._skyboxMaterial.enableNoise = true;
  89801. this._skybox.material = this._skyboxMaterial;
  89802. };
  89803. /**
  89804. * Setup the skybox reflection texture according to the specified options.
  89805. */
  89806. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89807. if (!this._skyboxMaterial) {
  89808. return;
  89809. }
  89810. if (this._skyboxTexture) {
  89811. return;
  89812. }
  89813. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89814. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89815. return;
  89816. }
  89817. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89818. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89819. this._skyboxTexture.gammaSpace = false;
  89820. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89821. };
  89822. /**
  89823. * Dispose all the elements created by the Helper.
  89824. */
  89825. EnvironmentHelper.prototype.dispose = function () {
  89826. if (this._groundMaterial) {
  89827. this._groundMaterial.dispose(true, true);
  89828. }
  89829. if (this._skyboxMaterial) {
  89830. this._skyboxMaterial.dispose(true, true);
  89831. }
  89832. this._rootMesh.dispose(false);
  89833. };
  89834. /**
  89835. * Default ground texture URL.
  89836. */
  89837. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89838. /**
  89839. * Default skybox texture URL.
  89840. */
  89841. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89842. /**
  89843. * Default environment texture URL.
  89844. */
  89845. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89846. return EnvironmentHelper;
  89847. }());
  89848. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89849. })(BABYLON || (BABYLON = {}));
  89850. //# sourceMappingURL=babylon.environmentHelper.js.map
  89851. 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"};
  89852. 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};"};
  89853. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89854. var BABYLON;
  89855. (function (BABYLON) {
  89856. var GridMaterialDefines = /** @class */ (function (_super) {
  89857. __extends(GridMaterialDefines, _super);
  89858. function GridMaterialDefines() {
  89859. var _this = _super.call(this) || this;
  89860. _this.TRANSPARENT = false;
  89861. _this.FOG = false;
  89862. _this.PREMULTIPLYALPHA = false;
  89863. _this.rebuild();
  89864. return _this;
  89865. }
  89866. return GridMaterialDefines;
  89867. }(BABYLON.MaterialDefines));
  89868. /**
  89869. * The grid materials allows you to wrap any shape with a grid.
  89870. * Colors are customizable.
  89871. */
  89872. var GridMaterial = /** @class */ (function (_super) {
  89873. __extends(GridMaterial, _super);
  89874. /**
  89875. * constructor
  89876. * @param name The name given to the material in order to identify it afterwards.
  89877. * @param scene The scene the material is used in.
  89878. */
  89879. function GridMaterial(name, scene) {
  89880. var _this = _super.call(this, name, scene) || this;
  89881. /**
  89882. * Main color of the grid (e.g. between lines)
  89883. */
  89884. _this.mainColor = BABYLON.Color3.Black();
  89885. /**
  89886. * Color of the grid lines.
  89887. */
  89888. _this.lineColor = BABYLON.Color3.Teal();
  89889. /**
  89890. * The scale of the grid compared to unit.
  89891. */
  89892. _this.gridRatio = 1.0;
  89893. /**
  89894. * Allows setting an offset for the grid lines.
  89895. */
  89896. _this.gridOffset = BABYLON.Vector3.Zero();
  89897. /**
  89898. * The frequency of thicker lines.
  89899. */
  89900. _this.majorUnitFrequency = 10;
  89901. /**
  89902. * The visibility of minor units in the grid.
  89903. */
  89904. _this.minorUnitVisibility = 0.33;
  89905. /**
  89906. * The grid opacity outside of the lines.
  89907. */
  89908. _this.opacity = 1.0;
  89909. /**
  89910. * Determine RBG output is premultiplied by alpha value.
  89911. */
  89912. _this.preMultiplyAlpha = false;
  89913. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89914. return _this;
  89915. }
  89916. /**
  89917. * Returns wehter or not the grid requires alpha blending.
  89918. */
  89919. GridMaterial.prototype.needAlphaBlending = function () {
  89920. return this.opacity < 1.0;
  89921. };
  89922. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89923. return this.needAlphaBlending();
  89924. };
  89925. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89926. if (this.isFrozen) {
  89927. if (this._wasPreviouslyReady && subMesh.effect) {
  89928. return true;
  89929. }
  89930. }
  89931. if (!subMesh._materialDefines) {
  89932. subMesh._materialDefines = new GridMaterialDefines();
  89933. }
  89934. var defines = subMesh._materialDefines;
  89935. var scene = this.getScene();
  89936. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89937. if (this._renderId === scene.getRenderId()) {
  89938. return true;
  89939. }
  89940. }
  89941. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89942. defines.TRANSPARENT = !defines.TRANSPARENT;
  89943. defines.markAsUnprocessed();
  89944. }
  89945. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89946. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89947. defines.markAsUnprocessed();
  89948. }
  89949. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89950. // Get correct effect
  89951. if (defines.isDirty) {
  89952. defines.markAsProcessed();
  89953. scene.resetCachedMaterial();
  89954. // Attributes
  89955. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89956. // Defines
  89957. var join = defines.toString();
  89958. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89959. }
  89960. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89961. return false;
  89962. }
  89963. this._renderId = scene.getRenderId();
  89964. this._wasPreviouslyReady = true;
  89965. return true;
  89966. };
  89967. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89968. var scene = this.getScene();
  89969. var defines = subMesh._materialDefines;
  89970. if (!defines) {
  89971. return;
  89972. }
  89973. var effect = subMesh.effect;
  89974. if (!effect) {
  89975. return;
  89976. }
  89977. this._activeEffect = effect;
  89978. // Matrices
  89979. this.bindOnlyWorldMatrix(world);
  89980. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89981. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89982. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89983. // Uniforms
  89984. if (this._mustRebind(scene, effect)) {
  89985. this._activeEffect.setColor3("mainColor", this.mainColor);
  89986. this._activeEffect.setColor3("lineColor", this.lineColor);
  89987. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89988. this._gridControl.x = this.gridRatio;
  89989. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89990. this._gridControl.z = this.minorUnitVisibility;
  89991. this._gridControl.w = this.opacity;
  89992. this._activeEffect.setVector4("gridControl", this._gridControl);
  89993. }
  89994. // Fog
  89995. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89996. this._afterBind(mesh, this._activeEffect);
  89997. };
  89998. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89999. _super.prototype.dispose.call(this, forceDisposeEffect);
  90000. };
  90001. GridMaterial.prototype.clone = function (name) {
  90002. var _this = this;
  90003. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  90004. };
  90005. GridMaterial.prototype.serialize = function () {
  90006. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90007. serializationObject.customType = "BABYLON.GridMaterial";
  90008. return serializationObject;
  90009. };
  90010. GridMaterial.prototype.getClassName = function () {
  90011. return "GridMaterial";
  90012. };
  90013. GridMaterial.Parse = function (source, scene, rootUrl) {
  90014. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  90015. };
  90016. __decorate([
  90017. BABYLON.serializeAsColor3()
  90018. ], GridMaterial.prototype, "mainColor", void 0);
  90019. __decorate([
  90020. BABYLON.serializeAsColor3()
  90021. ], GridMaterial.prototype, "lineColor", void 0);
  90022. __decorate([
  90023. BABYLON.serialize()
  90024. ], GridMaterial.prototype, "gridRatio", void 0);
  90025. __decorate([
  90026. BABYLON.serializeAsColor3()
  90027. ], GridMaterial.prototype, "gridOffset", void 0);
  90028. __decorate([
  90029. BABYLON.serialize()
  90030. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  90031. __decorate([
  90032. BABYLON.serialize()
  90033. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  90034. __decorate([
  90035. BABYLON.serialize()
  90036. ], GridMaterial.prototype, "opacity", void 0);
  90037. __decorate([
  90038. BABYLON.serialize()
  90039. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  90040. return GridMaterial;
  90041. }(BABYLON.PushMaterial));
  90042. BABYLON.GridMaterial = GridMaterial;
  90043. })(BABYLON || (BABYLON = {}));
  90044. //# sourceMappingURL=babylon.gridmaterial.js.map
  90045. 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}";
  90046. 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}";
  90047. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90048. var BABYLON;
  90049. (function (BABYLON) {
  90050. var GLTFLoaderCoordinateSystemMode;
  90051. (function (GLTFLoaderCoordinateSystemMode) {
  90052. /**
  90053. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  90054. */
  90055. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  90056. /**
  90057. * Sets the useRightHandedSystem flag on the scene.
  90058. */
  90059. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  90060. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  90061. var GLTFLoaderAnimationStartMode;
  90062. (function (GLTFLoaderAnimationStartMode) {
  90063. /**
  90064. * No animation will start.
  90065. */
  90066. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  90067. /**
  90068. * The first animation will start.
  90069. */
  90070. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  90071. /**
  90072. * All animations will start.
  90073. */
  90074. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  90075. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  90076. var GLTFLoaderState;
  90077. (function (GLTFLoaderState) {
  90078. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  90079. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  90080. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  90081. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  90082. var GLTFFileLoader = /** @class */ (function () {
  90083. function GLTFFileLoader() {
  90084. // #region Common options
  90085. /**
  90086. * Raised when the asset has been parsed.
  90087. * The data.json property stores the glTF JSON.
  90088. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  90089. */
  90090. this.onParsedObservable = new BABYLON.Observable();
  90091. // #endregion
  90092. // #region V2 options
  90093. /**
  90094. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  90095. */
  90096. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  90097. /**
  90098. * The animation start mode (NONE, FIRST, ALL).
  90099. */
  90100. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90101. /**
  90102. * Set to true to compile materials before raising the success callback.
  90103. */
  90104. this.compileMaterials = false;
  90105. /**
  90106. * Set to true to also compile materials with clip planes.
  90107. */
  90108. this.useClipPlane = false;
  90109. /**
  90110. * Set to true to compile shadow generators before raising the success callback.
  90111. */
  90112. this.compileShadowGenerators = false;
  90113. /**
  90114. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90115. */
  90116. this.onMeshLoadedObservable = new BABYLON.Observable();
  90117. /**
  90118. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90119. */
  90120. this.onTextureLoadedObservable = new BABYLON.Observable();
  90121. /**
  90122. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90123. */
  90124. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90125. /**
  90126. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90127. */
  90128. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90129. /**
  90130. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90131. * For assets with LODs, raised when all of the LODs are complete.
  90132. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90133. */
  90134. this.onCompleteObservable = new BABYLON.Observable();
  90135. /**
  90136. * Raised when the loader is disposed.
  90137. */
  90138. this.onDisposeObservable = new BABYLON.Observable();
  90139. /**
  90140. * Raised after a loader extension is created.
  90141. * Set additional options for a loader extension in this event.
  90142. */
  90143. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90144. // #endregion
  90145. this._loader = null;
  90146. this.name = "gltf";
  90147. this.extensions = {
  90148. ".gltf": { isBinary: false },
  90149. ".glb": { isBinary: true }
  90150. };
  90151. }
  90152. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90153. set: function (callback) {
  90154. if (this._onParsedObserver) {
  90155. this.onParsedObservable.remove(this._onParsedObserver);
  90156. }
  90157. this._onParsedObserver = this.onParsedObservable.add(callback);
  90158. },
  90159. enumerable: true,
  90160. configurable: true
  90161. });
  90162. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90163. set: function (callback) {
  90164. if (this._onMeshLoadedObserver) {
  90165. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90166. }
  90167. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90168. },
  90169. enumerable: true,
  90170. configurable: true
  90171. });
  90172. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90173. set: function (callback) {
  90174. if (this._onTextureLoadedObserver) {
  90175. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90176. }
  90177. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90178. },
  90179. enumerable: true,
  90180. configurable: true
  90181. });
  90182. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90183. set: function (callback) {
  90184. if (this._onMaterialLoadedObserver) {
  90185. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90186. }
  90187. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90188. },
  90189. enumerable: true,
  90190. configurable: true
  90191. });
  90192. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90193. set: function (callback) {
  90194. if (this._onAnimationGroupLoadedObserver) {
  90195. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90196. }
  90197. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90198. },
  90199. enumerable: true,
  90200. configurable: true
  90201. });
  90202. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90203. set: function (callback) {
  90204. if (this._onCompleteObserver) {
  90205. this.onCompleteObservable.remove(this._onCompleteObserver);
  90206. }
  90207. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90208. },
  90209. enumerable: true,
  90210. configurable: true
  90211. });
  90212. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90213. set: function (callback) {
  90214. if (this._onDisposeObserver) {
  90215. this.onDisposeObservable.remove(this._onDisposeObserver);
  90216. }
  90217. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90218. },
  90219. enumerable: true,
  90220. configurable: true
  90221. });
  90222. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90223. set: function (callback) {
  90224. if (this._onExtensionLoadedObserver) {
  90225. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90226. }
  90227. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90228. },
  90229. enumerable: true,
  90230. configurable: true
  90231. });
  90232. /**
  90233. * Gets a promise that resolves when the asset is completely loaded.
  90234. * @returns A promise that resolves when the asset is completely loaded.
  90235. */
  90236. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90237. var _this = this;
  90238. return new Promise(function (resolve) {
  90239. _this.onCompleteObservable.add(function () {
  90240. resolve();
  90241. }, undefined, undefined, undefined, true);
  90242. });
  90243. };
  90244. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90245. /**
  90246. * The loader state or null if not active.
  90247. */
  90248. get: function () {
  90249. return this._loader ? this._loader.state : null;
  90250. },
  90251. enumerable: true,
  90252. configurable: true
  90253. });
  90254. /**
  90255. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90256. */
  90257. GLTFFileLoader.prototype.dispose = function () {
  90258. if (this._loader) {
  90259. this._loader.dispose();
  90260. this._loader = null;
  90261. }
  90262. this.onMeshLoadedObservable.clear();
  90263. this.onTextureLoadedObservable.clear();
  90264. this.onMaterialLoadedObservable.clear();
  90265. this.onDisposeObservable.notifyObservers(this);
  90266. this.onDisposeObservable.clear();
  90267. };
  90268. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90269. var _this = this;
  90270. return Promise.resolve().then(function () {
  90271. var loaderData = _this._parse(data);
  90272. _this._loader = _this._getLoader(loaderData);
  90273. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90274. });
  90275. };
  90276. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90277. var _this = this;
  90278. return Promise.resolve().then(function () {
  90279. var loaderData = _this._parse(data);
  90280. _this._loader = _this._getLoader(loaderData);
  90281. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90282. });
  90283. };
  90284. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90285. var _this = this;
  90286. return Promise.resolve().then(function () {
  90287. var loaderData = _this._parse(data);
  90288. _this._loader = _this._getLoader(loaderData);
  90289. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90290. var container = new BABYLON.AssetContainer(scene);
  90291. Array.prototype.push.apply(container.meshes, result.meshes);
  90292. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90293. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90294. container.removeAllFromScene();
  90295. return container;
  90296. });
  90297. });
  90298. };
  90299. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90300. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90301. };
  90302. GLTFFileLoader.prototype.createPlugin = function () {
  90303. return new GLTFFileLoader();
  90304. };
  90305. GLTFFileLoader.prototype._parse = function (data) {
  90306. var parsedData;
  90307. if (data instanceof ArrayBuffer) {
  90308. parsedData = GLTFFileLoader._parseBinary(data);
  90309. }
  90310. else {
  90311. parsedData = {
  90312. json: JSON.parse(data),
  90313. bin: null
  90314. };
  90315. }
  90316. this.onParsedObservable.notifyObservers(parsedData);
  90317. this.onParsedObservable.clear();
  90318. return parsedData;
  90319. };
  90320. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90321. var _this = this;
  90322. var loaderVersion = { major: 2, minor: 0 };
  90323. var asset = loaderData.json.asset || {};
  90324. var version = GLTFFileLoader._parseVersion(asset.version);
  90325. if (!version) {
  90326. throw new Error("Invalid version: " + asset.version);
  90327. }
  90328. if (asset.minVersion !== undefined) {
  90329. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90330. if (!minVersion) {
  90331. throw new Error("Invalid minimum version: " + asset.minVersion);
  90332. }
  90333. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90334. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90335. }
  90336. }
  90337. var createLoaders = {
  90338. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90339. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90340. };
  90341. var createLoader = createLoaders[version.major];
  90342. if (!createLoader) {
  90343. throw new Error("Unsupported version: " + asset.version);
  90344. }
  90345. var loader = createLoader();
  90346. loader.coordinateSystemMode = this.coordinateSystemMode;
  90347. loader.animationStartMode = this.animationStartMode;
  90348. loader.compileMaterials = this.compileMaterials;
  90349. loader.useClipPlane = this.useClipPlane;
  90350. loader.compileShadowGenerators = this.compileShadowGenerators;
  90351. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90352. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90353. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90354. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90355. loader.onCompleteObservable.add(function () {
  90356. _this.onMeshLoadedObservable.clear();
  90357. _this.onTextureLoadedObservable.clear();
  90358. _this.onMaterialLoadedObservable.clear();
  90359. _this.onCompleteObservable.notifyObservers(_this);
  90360. _this.onCompleteObservable.clear();
  90361. });
  90362. return loader;
  90363. };
  90364. GLTFFileLoader._parseBinary = function (data) {
  90365. var Binary = {
  90366. Magic: 0x46546C67
  90367. };
  90368. var binaryReader = new BinaryReader(data);
  90369. var magic = binaryReader.readUint32();
  90370. if (magic !== Binary.Magic) {
  90371. throw new Error("Unexpected magic: " + magic);
  90372. }
  90373. var version = binaryReader.readUint32();
  90374. switch (version) {
  90375. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90376. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90377. }
  90378. throw new Error("Unsupported version: " + version);
  90379. };
  90380. GLTFFileLoader._parseV1 = function (binaryReader) {
  90381. var ContentFormat = {
  90382. JSON: 0
  90383. };
  90384. var length = binaryReader.readUint32();
  90385. if (length != binaryReader.getLength()) {
  90386. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90387. }
  90388. var contentLength = binaryReader.readUint32();
  90389. var contentFormat = binaryReader.readUint32();
  90390. var content;
  90391. switch (contentFormat) {
  90392. case ContentFormat.JSON: {
  90393. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90394. break;
  90395. }
  90396. default: {
  90397. throw new Error("Unexpected content format: " + contentFormat);
  90398. }
  90399. }
  90400. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90401. var body = binaryReader.readUint8Array(bytesRemaining);
  90402. return {
  90403. json: content,
  90404. bin: body
  90405. };
  90406. };
  90407. GLTFFileLoader._parseV2 = function (binaryReader) {
  90408. var ChunkFormat = {
  90409. JSON: 0x4E4F534A,
  90410. BIN: 0x004E4942
  90411. };
  90412. var length = binaryReader.readUint32();
  90413. if (length !== binaryReader.getLength()) {
  90414. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90415. }
  90416. // JSON chunk
  90417. var chunkLength = binaryReader.readUint32();
  90418. var chunkFormat = binaryReader.readUint32();
  90419. if (chunkFormat !== ChunkFormat.JSON) {
  90420. throw new Error("First chunk format is not JSON");
  90421. }
  90422. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90423. // Look for BIN chunk
  90424. var bin = null;
  90425. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90426. var chunkLength_1 = binaryReader.readUint32();
  90427. var chunkFormat_1 = binaryReader.readUint32();
  90428. switch (chunkFormat_1) {
  90429. case ChunkFormat.JSON: {
  90430. throw new Error("Unexpected JSON chunk");
  90431. }
  90432. case ChunkFormat.BIN: {
  90433. bin = binaryReader.readUint8Array(chunkLength_1);
  90434. break;
  90435. }
  90436. default: {
  90437. // ignore unrecognized chunkFormat
  90438. binaryReader.skipBytes(chunkLength_1);
  90439. break;
  90440. }
  90441. }
  90442. }
  90443. return {
  90444. json: json,
  90445. bin: bin
  90446. };
  90447. };
  90448. GLTFFileLoader._parseVersion = function (version) {
  90449. if (version === "1.0" || version === "1.0.1") {
  90450. return {
  90451. major: 1,
  90452. minor: 0
  90453. };
  90454. }
  90455. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90456. if (!match) {
  90457. return null;
  90458. }
  90459. return {
  90460. major: parseInt(match[1]),
  90461. minor: parseInt(match[2])
  90462. };
  90463. };
  90464. GLTFFileLoader._compareVersion = function (a, b) {
  90465. if (a.major > b.major)
  90466. return 1;
  90467. if (a.major < b.major)
  90468. return -1;
  90469. if (a.minor > b.minor)
  90470. return 1;
  90471. if (a.minor < b.minor)
  90472. return -1;
  90473. return 0;
  90474. };
  90475. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90476. var result = "";
  90477. var length = buffer.byteLength;
  90478. for (var i = 0; i < length; i++) {
  90479. result += String.fromCharCode(buffer[i]);
  90480. }
  90481. return result;
  90482. };
  90483. // #endregion
  90484. // #region V1 options
  90485. GLTFFileLoader.IncrementalLoading = true;
  90486. GLTFFileLoader.HomogeneousCoordinates = false;
  90487. return GLTFFileLoader;
  90488. }());
  90489. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90490. var BinaryReader = /** @class */ (function () {
  90491. function BinaryReader(arrayBuffer) {
  90492. this._arrayBuffer = arrayBuffer;
  90493. this._dataView = new DataView(arrayBuffer);
  90494. this._byteOffset = 0;
  90495. }
  90496. BinaryReader.prototype.getPosition = function () {
  90497. return this._byteOffset;
  90498. };
  90499. BinaryReader.prototype.getLength = function () {
  90500. return this._arrayBuffer.byteLength;
  90501. };
  90502. BinaryReader.prototype.readUint32 = function () {
  90503. var value = this._dataView.getUint32(this._byteOffset, true);
  90504. this._byteOffset += 4;
  90505. return value;
  90506. };
  90507. BinaryReader.prototype.readUint8Array = function (length) {
  90508. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90509. this._byteOffset += length;
  90510. return value;
  90511. };
  90512. BinaryReader.prototype.skipBytes = function (length) {
  90513. this._byteOffset += length;
  90514. };
  90515. return BinaryReader;
  90516. }());
  90517. if (BABYLON.SceneLoader) {
  90518. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90519. }
  90520. })(BABYLON || (BABYLON = {}));
  90521. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90522. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90523. var BABYLON;
  90524. (function (BABYLON) {
  90525. var GLTF1;
  90526. (function (GLTF1) {
  90527. /**
  90528. * Enums
  90529. */
  90530. var EComponentType;
  90531. (function (EComponentType) {
  90532. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90533. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90534. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90535. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90536. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90537. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90538. var EShaderType;
  90539. (function (EShaderType) {
  90540. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90541. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90542. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90543. var EParameterType;
  90544. (function (EParameterType) {
  90545. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90546. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90547. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90548. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90549. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90550. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90551. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90552. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90553. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90554. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90555. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90556. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90557. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90558. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90559. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90560. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90561. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90562. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90563. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90564. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90565. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90566. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90567. var ETextureWrapMode;
  90568. (function (ETextureWrapMode) {
  90569. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90570. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90571. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90572. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90573. var ETextureFilterType;
  90574. (function (ETextureFilterType) {
  90575. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90576. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90577. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90578. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90579. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90580. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90581. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90582. var ETextureFormat;
  90583. (function (ETextureFormat) {
  90584. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90585. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90586. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90587. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90588. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90589. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90590. var ECullingType;
  90591. (function (ECullingType) {
  90592. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90593. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90594. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90595. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90596. var EBlendingFunction;
  90597. (function (EBlendingFunction) {
  90598. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90599. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90600. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90601. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90602. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90603. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90604. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90605. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90606. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90607. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90608. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90609. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90610. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90611. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90612. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90613. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90614. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90615. })(BABYLON || (BABYLON = {}));
  90616. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90617. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90618. var BABYLON;
  90619. (function (BABYLON) {
  90620. var GLTF1;
  90621. (function (GLTF1) {
  90622. /**
  90623. * Tokenizer. Used for shaders compatibility
  90624. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90625. */
  90626. var ETokenType;
  90627. (function (ETokenType) {
  90628. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90629. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90630. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90631. })(ETokenType || (ETokenType = {}));
  90632. var Tokenizer = /** @class */ (function () {
  90633. function Tokenizer(toParse) {
  90634. this._pos = 0;
  90635. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90636. this._toParse = toParse;
  90637. this._maxPos = toParse.length;
  90638. }
  90639. Tokenizer.prototype.getNextToken = function () {
  90640. if (this.isEnd())
  90641. return ETokenType.END_OF_INPUT;
  90642. this.currentString = this.read();
  90643. this.currentToken = ETokenType.UNKNOWN;
  90644. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90645. this.currentToken = ETokenType.IDENTIFIER;
  90646. this.currentIdentifier = this.currentString;
  90647. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90648. this.currentIdentifier += this.currentString;
  90649. this.forward();
  90650. }
  90651. }
  90652. return this.currentToken;
  90653. };
  90654. Tokenizer.prototype.peek = function () {
  90655. return this._toParse[this._pos];
  90656. };
  90657. Tokenizer.prototype.read = function () {
  90658. return this._toParse[this._pos++];
  90659. };
  90660. Tokenizer.prototype.forward = function () {
  90661. this._pos++;
  90662. };
  90663. Tokenizer.prototype.isEnd = function () {
  90664. return this._pos >= this._maxPos;
  90665. };
  90666. return Tokenizer;
  90667. }());
  90668. /**
  90669. * Values
  90670. */
  90671. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90672. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90673. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90674. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90675. /**
  90676. * Parse
  90677. */
  90678. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90679. for (var buf in parsedBuffers) {
  90680. var parsedBuffer = parsedBuffers[buf];
  90681. gltfRuntime.buffers[buf] = parsedBuffer;
  90682. gltfRuntime.buffersCount++;
  90683. }
  90684. };
  90685. var parseShaders = function (parsedShaders, gltfRuntime) {
  90686. for (var sha in parsedShaders) {
  90687. var parsedShader = parsedShaders[sha];
  90688. gltfRuntime.shaders[sha] = parsedShader;
  90689. gltfRuntime.shaderscount++;
  90690. }
  90691. };
  90692. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90693. for (var object in parsedObjects) {
  90694. var parsedObject = parsedObjects[object];
  90695. gltfRuntime[runtimeProperty][object] = parsedObject;
  90696. }
  90697. };
  90698. /**
  90699. * Utils
  90700. */
  90701. var normalizeUVs = function (buffer) {
  90702. if (!buffer) {
  90703. return;
  90704. }
  90705. for (var i = 0; i < buffer.length / 2; i++) {
  90706. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90707. }
  90708. };
  90709. var getAttribute = function (attributeParameter) {
  90710. if (attributeParameter.semantic === "NORMAL") {
  90711. return "normal";
  90712. }
  90713. else if (attributeParameter.semantic === "POSITION") {
  90714. return "position";
  90715. }
  90716. else if (attributeParameter.semantic === "JOINT") {
  90717. return "matricesIndices";
  90718. }
  90719. else if (attributeParameter.semantic === "WEIGHT") {
  90720. return "matricesWeights";
  90721. }
  90722. else if (attributeParameter.semantic === "COLOR") {
  90723. return "color";
  90724. }
  90725. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90726. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90727. return "uv" + (channel === 0 ? "" : channel + 1);
  90728. }
  90729. return null;
  90730. };
  90731. /**
  90732. * Loads and creates animations
  90733. */
  90734. var loadAnimations = function (gltfRuntime) {
  90735. for (var anim in gltfRuntime.animations) {
  90736. var animation = gltfRuntime.animations[anim];
  90737. if (!animation.channels || !animation.samplers) {
  90738. continue;
  90739. }
  90740. var lastAnimation = null;
  90741. for (var i = 0; i < animation.channels.length; i++) {
  90742. // Get parameters and load buffers
  90743. var channel = animation.channels[i];
  90744. var sampler = animation.samplers[channel.sampler];
  90745. if (!sampler) {
  90746. continue;
  90747. }
  90748. var inputData = null;
  90749. var outputData = null;
  90750. if (animation.parameters) {
  90751. inputData = animation.parameters[sampler.input];
  90752. outputData = animation.parameters[sampler.output];
  90753. }
  90754. else {
  90755. inputData = sampler.input;
  90756. outputData = sampler.output;
  90757. }
  90758. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90759. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90760. var targetID = channel.target.id;
  90761. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90762. if (targetNode === null) {
  90763. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90764. }
  90765. if (targetNode === null) {
  90766. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90767. continue;
  90768. }
  90769. var isBone = targetNode instanceof BABYLON.Bone;
  90770. // Get target path (position, rotation or scaling)
  90771. var targetPath = channel.target.path;
  90772. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90773. if (targetPathIndex !== -1) {
  90774. targetPath = babylonAnimationPaths[targetPathIndex];
  90775. }
  90776. // Determine animation type
  90777. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90778. if (!isBone) {
  90779. if (targetPath === "rotationQuaternion") {
  90780. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90781. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90782. }
  90783. else {
  90784. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90785. }
  90786. }
  90787. // Create animation and key frames
  90788. var babylonAnimation = null;
  90789. var keys = [];
  90790. var arrayOffset = 0;
  90791. var modifyKey = false;
  90792. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90793. babylonAnimation = lastAnimation;
  90794. modifyKey = true;
  90795. }
  90796. if (!modifyKey) {
  90797. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90798. }
  90799. // For each frame
  90800. for (var j = 0; j < bufferInput.length; j++) {
  90801. var value = null;
  90802. if (targetPath === "rotationQuaternion") {
  90803. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90804. arrayOffset += 4;
  90805. }
  90806. else {
  90807. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90808. arrayOffset += 3;
  90809. }
  90810. if (isBone) {
  90811. var bone = targetNode;
  90812. var translation = BABYLON.Vector3.Zero();
  90813. var rotationQuaternion = new BABYLON.Quaternion();
  90814. var scaling = BABYLON.Vector3.Zero();
  90815. // Warning on decompose
  90816. var mat = bone.getBaseMatrix();
  90817. if (modifyKey && lastAnimation) {
  90818. mat = lastAnimation.getKeys()[j].value;
  90819. }
  90820. mat.decompose(scaling, rotationQuaternion, translation);
  90821. if (targetPath === "position") {
  90822. translation = value;
  90823. }
  90824. else if (targetPath === "rotationQuaternion") {
  90825. rotationQuaternion = value;
  90826. }
  90827. else {
  90828. scaling = value;
  90829. }
  90830. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90831. }
  90832. if (!modifyKey) {
  90833. keys.push({
  90834. frame: bufferInput[j],
  90835. value: value
  90836. });
  90837. }
  90838. else if (lastAnimation) {
  90839. lastAnimation.getKeys()[j].value = value;
  90840. }
  90841. }
  90842. // Finish
  90843. if (!modifyKey && babylonAnimation) {
  90844. babylonAnimation.setKeys(keys);
  90845. targetNode.animations.push(babylonAnimation);
  90846. }
  90847. lastAnimation = babylonAnimation;
  90848. gltfRuntime.scene.stopAnimation(targetNode);
  90849. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90850. }
  90851. }
  90852. };
  90853. /**
  90854. * Returns the bones transformation matrix
  90855. */
  90856. var configureBoneTransformation = function (node) {
  90857. var mat = null;
  90858. if (node.translation || node.rotation || node.scale) {
  90859. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90860. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90861. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90862. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90863. }
  90864. else {
  90865. mat = BABYLON.Matrix.FromArray(node.matrix);
  90866. }
  90867. return mat;
  90868. };
  90869. /**
  90870. * Returns the parent bone
  90871. */
  90872. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90873. // Try to find
  90874. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90875. if (newSkeleton.bones[i].name === jointName) {
  90876. return newSkeleton.bones[i];
  90877. }
  90878. }
  90879. // Not found, search in gltf nodes
  90880. var nodes = gltfRuntime.nodes;
  90881. for (var nde in nodes) {
  90882. var node = nodes[nde];
  90883. if (!node.jointName) {
  90884. continue;
  90885. }
  90886. var children = node.children;
  90887. for (var i = 0; i < children.length; i++) {
  90888. var child = gltfRuntime.nodes[children[i]];
  90889. if (!child.jointName) {
  90890. continue;
  90891. }
  90892. if (child.jointName === jointName) {
  90893. var mat = configureBoneTransformation(node);
  90894. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90895. bone.id = nde;
  90896. return bone;
  90897. }
  90898. }
  90899. }
  90900. return null;
  90901. };
  90902. /**
  90903. * Returns the appropriate root node
  90904. */
  90905. var getNodeToRoot = function (nodesToRoot, id) {
  90906. for (var i = 0; i < nodesToRoot.length; i++) {
  90907. var nodeToRoot = nodesToRoot[i];
  90908. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90909. var child = nodeToRoot.node.children[j];
  90910. if (child === id) {
  90911. return nodeToRoot.bone;
  90912. }
  90913. }
  90914. }
  90915. return null;
  90916. };
  90917. /**
  90918. * Returns the node with the joint name
  90919. */
  90920. var getJointNode = function (gltfRuntime, jointName) {
  90921. var nodes = gltfRuntime.nodes;
  90922. var node = nodes[jointName];
  90923. if (node) {
  90924. return {
  90925. node: node,
  90926. id: jointName
  90927. };
  90928. }
  90929. for (var nde in nodes) {
  90930. node = nodes[nde];
  90931. if (node.jointName === jointName) {
  90932. return {
  90933. node: node,
  90934. id: nde
  90935. };
  90936. }
  90937. }
  90938. return null;
  90939. };
  90940. /**
  90941. * Checks if a nodes is in joints
  90942. */
  90943. var nodeIsInJoints = function (skins, id) {
  90944. for (var i = 0; i < skins.jointNames.length; i++) {
  90945. if (skins.jointNames[i] === id) {
  90946. return true;
  90947. }
  90948. }
  90949. return false;
  90950. };
  90951. /**
  90952. * Fills the nodes to root for bones and builds hierarchy
  90953. */
  90954. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90955. // Creates nodes for root
  90956. for (var nde in gltfRuntime.nodes) {
  90957. var node = gltfRuntime.nodes[nde];
  90958. var id = nde;
  90959. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90960. continue;
  90961. }
  90962. // Create node to root bone
  90963. var mat = configureBoneTransformation(node);
  90964. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90965. bone.id = id;
  90966. nodesToRoot.push({ bone: bone, node: node, id: id });
  90967. }
  90968. // Parenting
  90969. for (var i = 0; i < nodesToRoot.length; i++) {
  90970. var nodeToRoot = nodesToRoot[i];
  90971. var children = nodeToRoot.node.children;
  90972. for (var j = 0; j < children.length; j++) {
  90973. var child = null;
  90974. for (var k = 0; k < nodesToRoot.length; k++) {
  90975. if (nodesToRoot[k].id === children[j]) {
  90976. child = nodesToRoot[k];
  90977. break;
  90978. }
  90979. }
  90980. if (child) {
  90981. child.bone._parent = nodeToRoot.bone;
  90982. nodeToRoot.bone.children.push(child.bone);
  90983. }
  90984. }
  90985. }
  90986. };
  90987. /**
  90988. * Imports a skeleton
  90989. */
  90990. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90991. if (!newSkeleton) {
  90992. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90993. }
  90994. if (!skins.babylonSkeleton) {
  90995. return newSkeleton;
  90996. }
  90997. // Find the root bones
  90998. var nodesToRoot = [];
  90999. var nodesToRootToAdd = [];
  91000. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  91001. newSkeleton.bones = [];
  91002. // Joints
  91003. for (var i = 0; i < skins.jointNames.length; i++) {
  91004. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91005. if (!jointNode) {
  91006. continue;
  91007. }
  91008. var node = jointNode.node;
  91009. if (!node) {
  91010. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  91011. continue;
  91012. }
  91013. var id = jointNode.id;
  91014. // Optimize, if the bone already exists...
  91015. var existingBone = gltfRuntime.scene.getBoneByID(id);
  91016. if (existingBone) {
  91017. newSkeleton.bones.push(existingBone);
  91018. continue;
  91019. }
  91020. // Search for parent bone
  91021. var foundBone = false;
  91022. var parentBone = null;
  91023. for (var j = 0; j < i; j++) {
  91024. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  91025. if (!jointNode_1) {
  91026. continue;
  91027. }
  91028. var joint = jointNode_1.node;
  91029. if (!joint) {
  91030. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  91031. continue;
  91032. }
  91033. var children = joint.children;
  91034. if (!children) {
  91035. continue;
  91036. }
  91037. foundBone = false;
  91038. for (var k = 0; k < children.length; k++) {
  91039. if (children[k] === id) {
  91040. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  91041. foundBone = true;
  91042. break;
  91043. }
  91044. }
  91045. if (foundBone) {
  91046. break;
  91047. }
  91048. }
  91049. // Create bone
  91050. var mat = configureBoneTransformation(node);
  91051. if (!parentBone && nodesToRoot.length > 0) {
  91052. parentBone = getNodeToRoot(nodesToRoot, id);
  91053. if (parentBone) {
  91054. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  91055. nodesToRootToAdd.push(parentBone);
  91056. }
  91057. }
  91058. }
  91059. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  91060. bone.id = id;
  91061. }
  91062. // Polish
  91063. var bones = newSkeleton.bones;
  91064. newSkeleton.bones = [];
  91065. for (var i = 0; i < skins.jointNames.length; i++) {
  91066. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91067. if (!jointNode) {
  91068. continue;
  91069. }
  91070. for (var j = 0; j < bones.length; j++) {
  91071. if (bones[j].id === jointNode.id) {
  91072. newSkeleton.bones.push(bones[j]);
  91073. break;
  91074. }
  91075. }
  91076. }
  91077. newSkeleton.prepare();
  91078. // Finish
  91079. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  91080. newSkeleton.bones.push(nodesToRootToAdd[i]);
  91081. }
  91082. return newSkeleton;
  91083. };
  91084. /**
  91085. * Imports a mesh and its geometries
  91086. */
  91087. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  91088. if (!newMesh) {
  91089. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91090. newMesh.id = id;
  91091. }
  91092. if (!node.babylonNode) {
  91093. return newMesh;
  91094. }
  91095. var subMaterials = [];
  91096. var vertexData = null;
  91097. var verticesStarts = new Array();
  91098. var verticesCounts = new Array();
  91099. var indexStarts = new Array();
  91100. var indexCounts = new Array();
  91101. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91102. var meshID = meshes[meshIndex];
  91103. var mesh = gltfRuntime.meshes[meshID];
  91104. if (!mesh) {
  91105. continue;
  91106. }
  91107. // Positions, normals and UVs
  91108. for (var i = 0; i < mesh.primitives.length; i++) {
  91109. // Temporary vertex data
  91110. var tempVertexData = new BABYLON.VertexData();
  91111. var primitive = mesh.primitives[i];
  91112. if (primitive.mode !== 4) {
  91113. // continue;
  91114. }
  91115. var attributes = primitive.attributes;
  91116. var accessor = null;
  91117. var buffer = null;
  91118. // Set positions, normal and uvs
  91119. for (var semantic in attributes) {
  91120. // Link accessor and buffer view
  91121. accessor = gltfRuntime.accessors[attributes[semantic]];
  91122. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91123. if (semantic === "NORMAL") {
  91124. tempVertexData.normals = new Float32Array(buffer.length);
  91125. tempVertexData.normals.set(buffer);
  91126. }
  91127. else if (semantic === "POSITION") {
  91128. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91129. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91130. for (var j = 0; j < buffer.length; j += 4) {
  91131. tempVertexData.positions[j] = buffer[j];
  91132. tempVertexData.positions[j + 1] = buffer[j + 1];
  91133. tempVertexData.positions[j + 2] = buffer[j + 2];
  91134. }
  91135. }
  91136. else {
  91137. tempVertexData.positions = new Float32Array(buffer.length);
  91138. tempVertexData.positions.set(buffer);
  91139. }
  91140. verticesCounts.push(tempVertexData.positions.length);
  91141. }
  91142. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91143. var channel = Number(semantic.split("_")[1]);
  91144. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91145. var uvs = new Float32Array(buffer.length);
  91146. uvs.set(buffer);
  91147. normalizeUVs(uvs);
  91148. tempVertexData.set(uvs, uvKind);
  91149. }
  91150. else if (semantic === "JOINT") {
  91151. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91152. tempVertexData.matricesIndices.set(buffer);
  91153. }
  91154. else if (semantic === "WEIGHT") {
  91155. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91156. tempVertexData.matricesWeights.set(buffer);
  91157. }
  91158. else if (semantic === "COLOR") {
  91159. tempVertexData.colors = new Float32Array(buffer.length);
  91160. tempVertexData.colors.set(buffer);
  91161. }
  91162. }
  91163. // Indices
  91164. accessor = gltfRuntime.accessors[primitive.indices];
  91165. if (accessor) {
  91166. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91167. tempVertexData.indices = new Int32Array(buffer.length);
  91168. tempVertexData.indices.set(buffer);
  91169. indexCounts.push(tempVertexData.indices.length);
  91170. }
  91171. else {
  91172. // Set indices on the fly
  91173. var indices = [];
  91174. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91175. indices.push(j);
  91176. }
  91177. tempVertexData.indices = new Int32Array(indices);
  91178. indexCounts.push(tempVertexData.indices.length);
  91179. }
  91180. if (!vertexData) {
  91181. vertexData = tempVertexData;
  91182. }
  91183. else {
  91184. vertexData.merge(tempVertexData);
  91185. }
  91186. // Sub material
  91187. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91188. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91189. // Update vertices start and index start
  91190. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91191. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91192. }
  91193. }
  91194. var material;
  91195. if (subMaterials.length > 1) {
  91196. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91197. material.subMaterials = subMaterials;
  91198. }
  91199. else {
  91200. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91201. }
  91202. if (subMaterials.length === 1) {
  91203. material = subMaterials[0];
  91204. }
  91205. if (!newMesh.material) {
  91206. newMesh.material = material;
  91207. }
  91208. // Apply geometry
  91209. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91210. newMesh.computeWorldMatrix(true);
  91211. // Apply submeshes
  91212. newMesh.subMeshes = [];
  91213. var index = 0;
  91214. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91215. var meshID = meshes[meshIndex];
  91216. var mesh = gltfRuntime.meshes[meshID];
  91217. if (!mesh) {
  91218. continue;
  91219. }
  91220. for (var i = 0; i < mesh.primitives.length; i++) {
  91221. if (mesh.primitives[i].mode !== 4) {
  91222. //continue;
  91223. }
  91224. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91225. index++;
  91226. }
  91227. }
  91228. // Finish
  91229. return newMesh;
  91230. };
  91231. /**
  91232. * Configure node transformation from position, rotation and scaling
  91233. */
  91234. var configureNode = function (newNode, position, rotation, scaling) {
  91235. if (newNode.position) {
  91236. newNode.position = position;
  91237. }
  91238. if (newNode.rotationQuaternion || newNode.rotation) {
  91239. newNode.rotationQuaternion = rotation;
  91240. }
  91241. if (newNode.scaling) {
  91242. newNode.scaling = scaling;
  91243. }
  91244. };
  91245. /**
  91246. * Configures node from transformation matrix
  91247. */
  91248. var configureNodeFromMatrix = function (newNode, node, parent) {
  91249. if (node.matrix) {
  91250. var position = new BABYLON.Vector3(0, 0, 0);
  91251. var rotation = new BABYLON.Quaternion();
  91252. var scaling = new BABYLON.Vector3(0, 0, 0);
  91253. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91254. mat.decompose(scaling, rotation, position);
  91255. configureNode(newNode, position, rotation, scaling);
  91256. }
  91257. else if (node.translation && node.rotation && node.scale) {
  91258. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91259. }
  91260. newNode.computeWorldMatrix(true);
  91261. };
  91262. /**
  91263. * Imports a node
  91264. */
  91265. var importNode = function (gltfRuntime, node, id, parent) {
  91266. var lastNode = null;
  91267. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91268. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91269. return null;
  91270. }
  91271. }
  91272. // Meshes
  91273. if (node.skin) {
  91274. if (node.meshes) {
  91275. var skin = gltfRuntime.skins[node.skin];
  91276. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91277. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91278. if (newMesh.skeleton === null) {
  91279. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91280. if (!skin.babylonSkeleton) {
  91281. skin.babylonSkeleton = newMesh.skeleton;
  91282. }
  91283. }
  91284. lastNode = newMesh;
  91285. }
  91286. }
  91287. else if (node.meshes) {
  91288. /**
  91289. * Improve meshes property
  91290. */
  91291. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91292. lastNode = newMesh;
  91293. }
  91294. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91295. var light = gltfRuntime.lights[node.light];
  91296. if (light) {
  91297. if (light.type === "ambient") {
  91298. var ambienLight = light[light.type];
  91299. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91300. hemiLight.name = node.name || "";
  91301. if (ambienLight.color) {
  91302. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91303. }
  91304. lastNode = hemiLight;
  91305. }
  91306. else if (light.type === "directional") {
  91307. var directionalLight = light[light.type];
  91308. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91309. dirLight.name = node.name || "";
  91310. if (directionalLight.color) {
  91311. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91312. }
  91313. lastNode = dirLight;
  91314. }
  91315. else if (light.type === "point") {
  91316. var pointLight = light[light.type];
  91317. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91318. ptLight.name = node.name || "";
  91319. if (pointLight.color) {
  91320. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91321. }
  91322. lastNode = ptLight;
  91323. }
  91324. else if (light.type === "spot") {
  91325. var spotLight = light[light.type];
  91326. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91327. spLight.name = node.name || "";
  91328. if (spotLight.color) {
  91329. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91330. }
  91331. if (spotLight.fallOfAngle) {
  91332. spLight.angle = spotLight.fallOfAngle;
  91333. }
  91334. if (spotLight.fallOffExponent) {
  91335. spLight.exponent = spotLight.fallOffExponent;
  91336. }
  91337. lastNode = spLight;
  91338. }
  91339. }
  91340. }
  91341. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91342. var camera = gltfRuntime.cameras[node.camera];
  91343. if (camera) {
  91344. if (camera.type === "orthographic") {
  91345. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91346. orthoCamera.name = node.name || "";
  91347. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91348. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91349. lastNode = orthoCamera;
  91350. }
  91351. else if (camera.type === "perspective") {
  91352. var perspectiveCamera = camera[camera.type];
  91353. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91354. persCamera.name = node.name || "";
  91355. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91356. if (!perspectiveCamera.aspectRatio) {
  91357. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91358. }
  91359. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91360. persCamera.maxZ = perspectiveCamera.zfar;
  91361. persCamera.minZ = perspectiveCamera.znear;
  91362. }
  91363. lastNode = persCamera;
  91364. }
  91365. }
  91366. }
  91367. // Empty node
  91368. if (!node.jointName) {
  91369. if (node.babylonNode) {
  91370. return node.babylonNode;
  91371. }
  91372. else if (lastNode === null) {
  91373. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91374. node.babylonNode = dummy;
  91375. lastNode = dummy;
  91376. }
  91377. }
  91378. if (lastNode !== null) {
  91379. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91380. configureNodeFromMatrix(lastNode, node, parent);
  91381. }
  91382. else {
  91383. var translation = node.translation || [0, 0, 0];
  91384. var rotation = node.rotation || [0, 0, 0, 1];
  91385. var scale = node.scale || [1, 1, 1];
  91386. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91387. }
  91388. lastNode.updateCache(true);
  91389. node.babylonNode = lastNode;
  91390. }
  91391. return lastNode;
  91392. };
  91393. /**
  91394. * Traverses nodes and creates them
  91395. */
  91396. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91397. if (meshIncluded === void 0) { meshIncluded = false; }
  91398. var node = gltfRuntime.nodes[id];
  91399. var newNode = null;
  91400. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91401. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91402. meshIncluded = true;
  91403. }
  91404. else {
  91405. meshIncluded = false;
  91406. }
  91407. }
  91408. else {
  91409. meshIncluded = true;
  91410. }
  91411. if (!node.jointName && meshIncluded) {
  91412. newNode = importNode(gltfRuntime, node, id, parent);
  91413. if (newNode !== null) {
  91414. newNode.id = id;
  91415. newNode.parent = parent;
  91416. }
  91417. }
  91418. if (node.children) {
  91419. for (var i = 0; i < node.children.length; i++) {
  91420. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91421. }
  91422. }
  91423. };
  91424. /**
  91425. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91426. */
  91427. var postLoad = function (gltfRuntime) {
  91428. // Nodes
  91429. var currentScene = gltfRuntime.currentScene;
  91430. if (currentScene) {
  91431. for (var i = 0; i < currentScene.nodes.length; i++) {
  91432. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91433. }
  91434. }
  91435. else {
  91436. for (var thing in gltfRuntime.scenes) {
  91437. currentScene = gltfRuntime.scenes[thing];
  91438. for (var i = 0; i < currentScene.nodes.length; i++) {
  91439. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91440. }
  91441. }
  91442. }
  91443. // Set animations
  91444. loadAnimations(gltfRuntime);
  91445. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91446. var skeleton = gltfRuntime.scene.skeletons[i];
  91447. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91448. }
  91449. };
  91450. /**
  91451. * onBind shaderrs callback to set uniforms and matrices
  91452. */
  91453. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91454. var materialValues = material.values || technique.parameters;
  91455. for (var unif in unTreatedUniforms) {
  91456. var uniform = unTreatedUniforms[unif];
  91457. var type = uniform.type;
  91458. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91459. if (uniform.semantic && !uniform.source && !uniform.node) {
  91460. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91461. }
  91462. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91463. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91464. if (source === null) {
  91465. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91466. }
  91467. if (source === null) {
  91468. continue;
  91469. }
  91470. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91471. }
  91472. }
  91473. else {
  91474. var value = materialValues[technique.uniforms[unif]];
  91475. if (!value) {
  91476. continue;
  91477. }
  91478. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91479. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91480. if (texture === null || texture === undefined) {
  91481. continue;
  91482. }
  91483. shaderMaterial.getEffect().setTexture(unif, texture);
  91484. }
  91485. else {
  91486. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91487. }
  91488. }
  91489. }
  91490. onSuccess(shaderMaterial);
  91491. };
  91492. /**
  91493. * Prepare uniforms to send the only one time
  91494. * Loads the appropriate textures
  91495. */
  91496. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91497. var materialValues = material.values || technique.parameters;
  91498. var techniqueUniforms = technique.uniforms;
  91499. /**
  91500. * Prepare values here (not matrices)
  91501. */
  91502. for (var unif in unTreatedUniforms) {
  91503. var uniform = unTreatedUniforms[unif];
  91504. var type = uniform.type;
  91505. var value = materialValues[techniqueUniforms[unif]];
  91506. if (value === undefined) {
  91507. // In case the value is the same for all materials
  91508. value = uniform.value;
  91509. }
  91510. if (!value) {
  91511. continue;
  91512. }
  91513. var onLoadTexture = function (uniformName) {
  91514. return function (texture) {
  91515. if (uniform.value && uniformName) {
  91516. // Static uniform
  91517. shaderMaterial.setTexture(uniformName, texture);
  91518. delete unTreatedUniforms[uniformName];
  91519. }
  91520. };
  91521. };
  91522. // Texture (sampler2D)
  91523. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91524. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91525. }
  91526. else {
  91527. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91528. // Static uniform
  91529. delete unTreatedUniforms[unif];
  91530. }
  91531. }
  91532. }
  91533. };
  91534. /**
  91535. * Shader compilation failed
  91536. */
  91537. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91538. return function (effect, error) {
  91539. shaderMaterial.dispose(true);
  91540. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91541. };
  91542. };
  91543. /**
  91544. * Shader compilation success
  91545. */
  91546. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91547. return function (_) {
  91548. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91549. shaderMaterial.onBind = function (mesh) {
  91550. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91551. };
  91552. };
  91553. };
  91554. /**
  91555. * Returns the appropriate uniform if already handled by babylon
  91556. */
  91557. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91558. for (var unif in technique.uniforms) {
  91559. var uniform = technique.uniforms[unif];
  91560. var uniformParameter = technique.parameters[uniform];
  91561. if (tokenizer.currentIdentifier === unif) {
  91562. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91563. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91564. if (transformIndex !== -1) {
  91565. delete unTreatedUniforms[unif];
  91566. return babylonTransforms[transformIndex];
  91567. }
  91568. }
  91569. }
  91570. }
  91571. return tokenizer.currentIdentifier;
  91572. };
  91573. /**
  91574. * All shaders loaded. Create materials one by one
  91575. */
  91576. var importMaterials = function (gltfRuntime) {
  91577. // Create materials
  91578. for (var mat in gltfRuntime.materials) {
  91579. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91580. }
  91581. };
  91582. /**
  91583. * Implementation of the base glTF spec
  91584. */
  91585. var GLTFLoaderBase = /** @class */ (function () {
  91586. function GLTFLoaderBase() {
  91587. }
  91588. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91589. var gltfRuntime = {
  91590. extensions: {},
  91591. accessors: {},
  91592. buffers: {},
  91593. bufferViews: {},
  91594. meshes: {},
  91595. lights: {},
  91596. cameras: {},
  91597. nodes: {},
  91598. images: {},
  91599. textures: {},
  91600. shaders: {},
  91601. programs: {},
  91602. samplers: {},
  91603. techniques: {},
  91604. materials: {},
  91605. animations: {},
  91606. skins: {},
  91607. extensionsUsed: [],
  91608. scenes: {},
  91609. buffersCount: 0,
  91610. shaderscount: 0,
  91611. scene: scene,
  91612. rootUrl: rootUrl,
  91613. loadedBufferCount: 0,
  91614. loadedBufferViews: {},
  91615. loadedShaderCount: 0,
  91616. importOnlyMeshes: false,
  91617. dummyNodes: []
  91618. };
  91619. // Parse
  91620. if (parsedData.extensions) {
  91621. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91622. }
  91623. if (parsedData.extensionsUsed) {
  91624. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91625. }
  91626. if (parsedData.buffers) {
  91627. parseBuffers(parsedData.buffers, gltfRuntime);
  91628. }
  91629. if (parsedData.bufferViews) {
  91630. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91631. }
  91632. if (parsedData.accessors) {
  91633. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91634. }
  91635. if (parsedData.meshes) {
  91636. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91637. }
  91638. if (parsedData.lights) {
  91639. parseObject(parsedData.lights, "lights", gltfRuntime);
  91640. }
  91641. if (parsedData.cameras) {
  91642. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91643. }
  91644. if (parsedData.nodes) {
  91645. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91646. }
  91647. if (parsedData.images) {
  91648. parseObject(parsedData.images, "images", gltfRuntime);
  91649. }
  91650. if (parsedData.textures) {
  91651. parseObject(parsedData.textures, "textures", gltfRuntime);
  91652. }
  91653. if (parsedData.shaders) {
  91654. parseShaders(parsedData.shaders, gltfRuntime);
  91655. }
  91656. if (parsedData.programs) {
  91657. parseObject(parsedData.programs, "programs", gltfRuntime);
  91658. }
  91659. if (parsedData.samplers) {
  91660. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91661. }
  91662. if (parsedData.techniques) {
  91663. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91664. }
  91665. if (parsedData.materials) {
  91666. parseObject(parsedData.materials, "materials", gltfRuntime);
  91667. }
  91668. if (parsedData.animations) {
  91669. parseObject(parsedData.animations, "animations", gltfRuntime);
  91670. }
  91671. if (parsedData.skins) {
  91672. parseObject(parsedData.skins, "skins", gltfRuntime);
  91673. }
  91674. if (parsedData.scenes) {
  91675. gltfRuntime.scenes = parsedData.scenes;
  91676. }
  91677. if (parsedData.scene && parsedData.scenes) {
  91678. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91679. }
  91680. return gltfRuntime;
  91681. };
  91682. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91683. var buffer = gltfRuntime.buffers[id];
  91684. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91685. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91686. }
  91687. else {
  91688. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91689. if (request) {
  91690. onError(request.status + " " + request.statusText);
  91691. }
  91692. });
  91693. }
  91694. };
  91695. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91696. var texture = gltfRuntime.textures[id];
  91697. if (!texture || !texture.source) {
  91698. onError("");
  91699. return;
  91700. }
  91701. if (texture.babylonTexture) {
  91702. onSuccess(null);
  91703. return;
  91704. }
  91705. var source = gltfRuntime.images[texture.source];
  91706. if (BABYLON.Tools.IsBase64(source.uri)) {
  91707. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91708. }
  91709. else {
  91710. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91711. if (request) {
  91712. onError(request.status + " " + request.statusText);
  91713. }
  91714. });
  91715. }
  91716. };
  91717. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91718. var texture = gltfRuntime.textures[id];
  91719. if (texture.babylonTexture) {
  91720. onSuccess(texture.babylonTexture);
  91721. return;
  91722. }
  91723. var sampler = gltfRuntime.samplers[texture.sampler];
  91724. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91725. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91726. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91727. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91728. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91729. var blob = new Blob([buffer]);
  91730. var blobURL = URL.createObjectURL(blob);
  91731. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91732. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91733. if (sampler.wrapS !== undefined) {
  91734. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91735. }
  91736. if (sampler.wrapT !== undefined) {
  91737. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91738. }
  91739. newTexture.name = id;
  91740. texture.babylonTexture = newTexture;
  91741. onSuccess(newTexture);
  91742. };
  91743. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91744. var shader = gltfRuntime.shaders[id];
  91745. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91746. var shaderString = atob(shader.uri.split(",")[1]);
  91747. onSuccess(shaderString);
  91748. }
  91749. else {
  91750. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91751. if (request) {
  91752. onError(request.status + " " + request.statusText);
  91753. }
  91754. });
  91755. }
  91756. };
  91757. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91758. var material = gltfRuntime.materials[id];
  91759. if (!material.technique) {
  91760. if (onError) {
  91761. onError("No technique found.");
  91762. }
  91763. return;
  91764. }
  91765. var technique = gltfRuntime.techniques[material.technique];
  91766. if (!technique) {
  91767. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91768. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91769. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91770. onSuccess(defaultMaterial);
  91771. return;
  91772. }
  91773. var program = gltfRuntime.programs[technique.program];
  91774. var states = technique.states;
  91775. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91776. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91777. var newVertexShader = "";
  91778. var newPixelShader = "";
  91779. var vertexTokenizer = new Tokenizer(vertexShader);
  91780. var pixelTokenizer = new Tokenizer(pixelShader);
  91781. var unTreatedUniforms = {};
  91782. var uniforms = [];
  91783. var attributes = [];
  91784. var samplers = [];
  91785. // Fill uniform, sampler2D and attributes
  91786. for (var unif in technique.uniforms) {
  91787. var uniform = technique.uniforms[unif];
  91788. var uniformParameter = technique.parameters[uniform];
  91789. unTreatedUniforms[unif] = uniformParameter;
  91790. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91791. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91792. if (transformIndex !== -1) {
  91793. uniforms.push(babylonTransforms[transformIndex]);
  91794. delete unTreatedUniforms[unif];
  91795. }
  91796. else {
  91797. uniforms.push(unif);
  91798. }
  91799. }
  91800. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91801. samplers.push(unif);
  91802. }
  91803. else {
  91804. uniforms.push(unif);
  91805. }
  91806. }
  91807. for (var attr in technique.attributes) {
  91808. var attribute = technique.attributes[attr];
  91809. var attributeParameter = technique.parameters[attribute];
  91810. if (attributeParameter.semantic) {
  91811. attributes.push(getAttribute(attributeParameter));
  91812. }
  91813. }
  91814. // Configure vertex shader
  91815. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91816. var tokenType = vertexTokenizer.currentToken;
  91817. if (tokenType !== ETokenType.IDENTIFIER) {
  91818. newVertexShader += vertexTokenizer.currentString;
  91819. continue;
  91820. }
  91821. var foundAttribute = false;
  91822. for (var attr in technique.attributes) {
  91823. var attribute = technique.attributes[attr];
  91824. var attributeParameter = technique.parameters[attribute];
  91825. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91826. newVertexShader += getAttribute(attributeParameter);
  91827. foundAttribute = true;
  91828. break;
  91829. }
  91830. }
  91831. if (foundAttribute) {
  91832. continue;
  91833. }
  91834. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91835. }
  91836. // Configure pixel shader
  91837. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91838. var tokenType = pixelTokenizer.currentToken;
  91839. if (tokenType !== ETokenType.IDENTIFIER) {
  91840. newPixelShader += pixelTokenizer.currentString;
  91841. continue;
  91842. }
  91843. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91844. }
  91845. // Create shader material
  91846. var shaderPath = {
  91847. vertex: program.vertexShader + id,
  91848. fragment: program.fragmentShader + id
  91849. };
  91850. var options = {
  91851. attributes: attributes,
  91852. uniforms: uniforms,
  91853. samplers: samplers,
  91854. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91855. };
  91856. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91857. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91858. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91859. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91860. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91861. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91862. if (states && states.functions) {
  91863. var functions = states.functions;
  91864. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91865. shaderMaterial.backFaceCulling = false;
  91866. }
  91867. var blendFunc = functions.blendFuncSeparate;
  91868. if (blendFunc) {
  91869. 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) {
  91870. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91871. }
  91872. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91873. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91874. }
  91875. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91876. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91877. }
  91878. 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) {
  91879. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91880. }
  91881. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91882. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91883. }
  91884. 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) {
  91885. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91886. }
  91887. }
  91888. }
  91889. };
  91890. return GLTFLoaderBase;
  91891. }());
  91892. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91893. /**
  91894. * glTF V1 Loader
  91895. */
  91896. var GLTFLoader = /** @class */ (function () {
  91897. function GLTFLoader() {
  91898. // #region Stubs for IGLTFLoader interface
  91899. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91900. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91901. this.compileMaterials = false;
  91902. this.useClipPlane = false;
  91903. this.compileShadowGenerators = false;
  91904. this.onDisposeObservable = new BABYLON.Observable();
  91905. this.onMeshLoadedObservable = new BABYLON.Observable();
  91906. this.onTextureLoadedObservable = new BABYLON.Observable();
  91907. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91908. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91909. this.onCompleteObservable = new BABYLON.Observable();
  91910. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91911. this.state = null;
  91912. }
  91913. GLTFLoader.RegisterExtension = function (extension) {
  91914. if (GLTFLoader.Extensions[extension.name]) {
  91915. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91916. return;
  91917. }
  91918. GLTFLoader.Extensions[extension.name] = extension;
  91919. };
  91920. GLTFLoader.prototype.dispose = function () { };
  91921. // #endregion
  91922. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91923. var _this = this;
  91924. scene.useRightHandedSystem = true;
  91925. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91926. gltfRuntime.importOnlyMeshes = true;
  91927. if (meshesNames === "") {
  91928. gltfRuntime.importMeshesNames = [];
  91929. }
  91930. else if (typeof meshesNames === "string") {
  91931. gltfRuntime.importMeshesNames = [meshesNames];
  91932. }
  91933. else if (meshesNames && !(meshesNames instanceof Array)) {
  91934. gltfRuntime.importMeshesNames = [meshesNames];
  91935. }
  91936. else {
  91937. gltfRuntime.importMeshesNames = [];
  91938. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91939. }
  91940. // Create nodes
  91941. _this._createNodes(gltfRuntime);
  91942. var meshes = new Array();
  91943. var skeletons = new Array();
  91944. // Fill arrays of meshes and skeletons
  91945. for (var nde in gltfRuntime.nodes) {
  91946. var node = gltfRuntime.nodes[nde];
  91947. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91948. meshes.push(node.babylonNode);
  91949. }
  91950. }
  91951. for (var skl in gltfRuntime.skins) {
  91952. var skin = gltfRuntime.skins[skl];
  91953. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91954. skeletons.push(skin.babylonSkeleton);
  91955. }
  91956. }
  91957. // Load buffers, shaders, materials, etc.
  91958. _this._loadBuffersAsync(gltfRuntime, function () {
  91959. _this._loadShadersAsync(gltfRuntime, function () {
  91960. importMaterials(gltfRuntime);
  91961. postLoad(gltfRuntime);
  91962. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91963. onSuccess(meshes, [], skeletons);
  91964. }
  91965. });
  91966. }, onProgress);
  91967. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91968. onSuccess(meshes, [], skeletons);
  91969. }
  91970. }, onError);
  91971. return true;
  91972. };
  91973. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91974. var _this = this;
  91975. return new Promise(function (resolve, reject) {
  91976. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91977. resolve({
  91978. meshes: meshes,
  91979. particleSystems: particleSystems,
  91980. skeletons: skeletons
  91981. });
  91982. }, onProgress, function (message) {
  91983. reject(new Error(message));
  91984. });
  91985. });
  91986. };
  91987. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91988. var _this = this;
  91989. scene.useRightHandedSystem = true;
  91990. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91991. // Load runtime extensios
  91992. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91993. // Create nodes
  91994. _this._createNodes(gltfRuntime);
  91995. // Load buffers, shaders, materials, etc.
  91996. _this._loadBuffersAsync(gltfRuntime, function () {
  91997. _this._loadShadersAsync(gltfRuntime, function () {
  91998. importMaterials(gltfRuntime);
  91999. postLoad(gltfRuntime);
  92000. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  92001. onSuccess();
  92002. }
  92003. });
  92004. });
  92005. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  92006. onSuccess();
  92007. }
  92008. }, onError);
  92009. }, onError);
  92010. };
  92011. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92012. var _this = this;
  92013. return new Promise(function (resolve, reject) {
  92014. _this._loadAsync(scene, data, rootUrl, function () {
  92015. resolve();
  92016. }, onProgress, function (message) {
  92017. reject(new Error(message));
  92018. });
  92019. });
  92020. };
  92021. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  92022. var hasShaders = false;
  92023. var processShader = function (sha, shader) {
  92024. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  92025. gltfRuntime.loadedShaderCount++;
  92026. if (shaderString) {
  92027. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  92028. }
  92029. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  92030. onload();
  92031. }
  92032. }, function () {
  92033. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  92034. });
  92035. };
  92036. for (var sha in gltfRuntime.shaders) {
  92037. hasShaders = true;
  92038. var shader = gltfRuntime.shaders[sha];
  92039. if (shader) {
  92040. processShader.bind(this, sha, shader)();
  92041. }
  92042. else {
  92043. BABYLON.Tools.Error("No shader named: " + sha);
  92044. }
  92045. }
  92046. if (!hasShaders) {
  92047. onload();
  92048. }
  92049. };
  92050. ;
  92051. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  92052. var hasBuffers = false;
  92053. var processBuffer = function (buf, buffer) {
  92054. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  92055. gltfRuntime.loadedBufferCount++;
  92056. if (bufferView) {
  92057. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  92058. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  92059. }
  92060. gltfRuntime.loadedBufferViews[buf] = bufferView;
  92061. }
  92062. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  92063. onLoad();
  92064. }
  92065. }, function () {
  92066. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  92067. });
  92068. };
  92069. for (var buf in gltfRuntime.buffers) {
  92070. hasBuffers = true;
  92071. var buffer = gltfRuntime.buffers[buf];
  92072. if (buffer) {
  92073. processBuffer.bind(this, buf, buffer)();
  92074. }
  92075. else {
  92076. BABYLON.Tools.Error("No buffer named: " + buf);
  92077. }
  92078. }
  92079. if (!hasBuffers) {
  92080. onLoad();
  92081. }
  92082. };
  92083. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  92084. var currentScene = gltfRuntime.currentScene;
  92085. if (currentScene) {
  92086. // Only one scene even if multiple scenes are defined
  92087. for (var i = 0; i < currentScene.nodes.length; i++) {
  92088. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92089. }
  92090. }
  92091. else {
  92092. // Load all scenes
  92093. for (var thing in gltfRuntime.scenes) {
  92094. currentScene = gltfRuntime.scenes[thing];
  92095. for (var i = 0; i < currentScene.nodes.length; i++) {
  92096. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92097. }
  92098. }
  92099. }
  92100. };
  92101. GLTFLoader.Extensions = {};
  92102. return GLTFLoader;
  92103. }());
  92104. GLTF1.GLTFLoader = GLTFLoader;
  92105. ;
  92106. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92107. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92108. })(BABYLON || (BABYLON = {}));
  92109. //# sourceMappingURL=babylon.glTFLoader.js.map
  92110. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92111. var BABYLON;
  92112. (function (BABYLON) {
  92113. var GLTF1;
  92114. (function (GLTF1) {
  92115. /**
  92116. * Utils functions for GLTF
  92117. */
  92118. var GLTFUtils = /** @class */ (function () {
  92119. function GLTFUtils() {
  92120. }
  92121. /**
  92122. * Sets the given "parameter" matrix
  92123. * @param scene: the {BABYLON.Scene} object
  92124. * @param source: the source node where to pick the matrix
  92125. * @param parameter: the GLTF technique parameter
  92126. * @param uniformName: the name of the shader's uniform
  92127. * @param shaderMaterial: the shader material
  92128. */
  92129. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92130. var mat = null;
  92131. if (parameter.semantic === "MODEL") {
  92132. mat = source.getWorldMatrix();
  92133. }
  92134. else if (parameter.semantic === "PROJECTION") {
  92135. mat = scene.getProjectionMatrix();
  92136. }
  92137. else if (parameter.semantic === "VIEW") {
  92138. mat = scene.getViewMatrix();
  92139. }
  92140. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92141. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92142. }
  92143. else if (parameter.semantic === "MODELVIEW") {
  92144. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92145. }
  92146. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92147. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92148. }
  92149. else if (parameter.semantic === "MODELINVERSE") {
  92150. mat = source.getWorldMatrix().invert();
  92151. }
  92152. else if (parameter.semantic === "VIEWINVERSE") {
  92153. mat = scene.getViewMatrix().invert();
  92154. }
  92155. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92156. mat = scene.getProjectionMatrix().invert();
  92157. }
  92158. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92159. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92160. }
  92161. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92162. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92163. }
  92164. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92165. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92166. }
  92167. else {
  92168. debugger;
  92169. }
  92170. if (mat) {
  92171. switch (parameter.type) {
  92172. case GLTF1.EParameterType.FLOAT_MAT2:
  92173. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92174. break;
  92175. case GLTF1.EParameterType.FLOAT_MAT3:
  92176. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92177. break;
  92178. case GLTF1.EParameterType.FLOAT_MAT4:
  92179. shaderMaterial.setMatrix(uniformName, mat);
  92180. break;
  92181. default: break;
  92182. }
  92183. }
  92184. };
  92185. /**
  92186. * Sets the given "parameter" matrix
  92187. * @param shaderMaterial: the shader material
  92188. * @param uniform: the name of the shader's uniform
  92189. * @param value: the value of the uniform
  92190. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92191. */
  92192. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92193. switch (type) {
  92194. case GLTF1.EParameterType.FLOAT:
  92195. shaderMaterial.setFloat(uniform, value);
  92196. return true;
  92197. case GLTF1.EParameterType.FLOAT_VEC2:
  92198. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92199. return true;
  92200. case GLTF1.EParameterType.FLOAT_VEC3:
  92201. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92202. return true;
  92203. case GLTF1.EParameterType.FLOAT_VEC4:
  92204. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92205. return true;
  92206. default: return false;
  92207. }
  92208. };
  92209. /**
  92210. * Returns the wrap mode of the texture
  92211. * @param mode: the mode value
  92212. */
  92213. GLTFUtils.GetWrapMode = function (mode) {
  92214. switch (mode) {
  92215. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92216. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92217. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92218. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92219. }
  92220. };
  92221. /**
  92222. * Returns the byte stride giving an accessor
  92223. * @param accessor: the GLTF accessor objet
  92224. */
  92225. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92226. // Needs this function since "byteStride" isn't requiered in glTF format
  92227. var type = accessor.type;
  92228. switch (type) {
  92229. case "VEC2": return 2;
  92230. case "VEC3": return 3;
  92231. case "VEC4": return 4;
  92232. case "MAT2": return 4;
  92233. case "MAT3": return 9;
  92234. case "MAT4": return 16;
  92235. default: return 1;
  92236. }
  92237. };
  92238. /**
  92239. * Returns the texture filter mode giving a mode value
  92240. * @param mode: the filter mode value
  92241. */
  92242. GLTFUtils.GetTextureFilterMode = function (mode) {
  92243. switch (mode) {
  92244. case GLTF1.ETextureFilterType.LINEAR:
  92245. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92246. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92247. case GLTF1.ETextureFilterType.NEAREST:
  92248. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92249. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92250. }
  92251. };
  92252. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92253. var byteOffset = bufferView.byteOffset + byteOffset;
  92254. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92255. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92256. throw new Error("Buffer access is out of range");
  92257. }
  92258. var buffer = loadedBufferView.buffer;
  92259. byteOffset += loadedBufferView.byteOffset;
  92260. switch (componentType) {
  92261. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92262. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92263. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92264. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92265. default: return new Float32Array(buffer, byteOffset, byteLength);
  92266. }
  92267. };
  92268. /**
  92269. * Returns a buffer from its accessor
  92270. * @param gltfRuntime: the GLTF runtime
  92271. * @param accessor: the GLTF accessor
  92272. */
  92273. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92274. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92275. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92276. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92277. };
  92278. /**
  92279. * Decodes a buffer view into a string
  92280. * @param view: the buffer view
  92281. */
  92282. GLTFUtils.DecodeBufferToText = function (view) {
  92283. var result = "";
  92284. var length = view.byteLength;
  92285. for (var i = 0; i < length; ++i) {
  92286. result += String.fromCharCode(view[i]);
  92287. }
  92288. return result;
  92289. };
  92290. /**
  92291. * Returns the default material of gltf. Related to
  92292. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92293. * @param scene: the Babylon.js scene
  92294. */
  92295. GLTFUtils.GetDefaultMaterial = function (scene) {
  92296. if (!GLTFUtils._DefaultMaterial) {
  92297. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92298. "precision highp float;",
  92299. "",
  92300. "uniform mat4 worldView;",
  92301. "uniform mat4 projection;",
  92302. "",
  92303. "attribute vec3 position;",
  92304. "",
  92305. "void main(void)",
  92306. "{",
  92307. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92308. "}"
  92309. ].join("\n");
  92310. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92311. "precision highp float;",
  92312. "",
  92313. "uniform vec4 u_emission;",
  92314. "",
  92315. "void main(void)",
  92316. "{",
  92317. " gl_FragColor = u_emission;",
  92318. "}"
  92319. ].join("\n");
  92320. var shaderPath = {
  92321. vertex: "GLTFDefaultMaterial",
  92322. fragment: "GLTFDefaultMaterial"
  92323. };
  92324. var options = {
  92325. attributes: ["position"],
  92326. uniforms: ["worldView", "projection", "u_emission"],
  92327. samplers: new Array(),
  92328. needAlphaBlending: false
  92329. };
  92330. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92331. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92332. }
  92333. return GLTFUtils._DefaultMaterial;
  92334. };
  92335. // The GLTF default material
  92336. GLTFUtils._DefaultMaterial = null;
  92337. return GLTFUtils;
  92338. }());
  92339. GLTF1.GLTFUtils = GLTFUtils;
  92340. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92341. })(BABYLON || (BABYLON = {}));
  92342. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92343. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92344. var BABYLON;
  92345. (function (BABYLON) {
  92346. var GLTF1;
  92347. (function (GLTF1) {
  92348. var GLTFLoaderExtension = /** @class */ (function () {
  92349. function GLTFLoaderExtension(name) {
  92350. this._name = name;
  92351. }
  92352. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92353. get: function () {
  92354. return this._name;
  92355. },
  92356. enumerable: true,
  92357. configurable: true
  92358. });
  92359. /**
  92360. * Defines an override for loading the runtime
  92361. * Return true to stop further extensions from loading the runtime
  92362. */
  92363. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92364. return false;
  92365. };
  92366. /**
  92367. * Defines an onverride for creating gltf runtime
  92368. * Return true to stop further extensions from creating the runtime
  92369. */
  92370. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92371. return false;
  92372. };
  92373. /**
  92374. * Defines an override for loading buffers
  92375. * Return true to stop further extensions from loading this buffer
  92376. */
  92377. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92378. return false;
  92379. };
  92380. /**
  92381. * Defines an override for loading texture buffers
  92382. * Return true to stop further extensions from loading this texture data
  92383. */
  92384. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92385. return false;
  92386. };
  92387. /**
  92388. * Defines an override for creating textures
  92389. * Return true to stop further extensions from loading this texture
  92390. */
  92391. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92392. return false;
  92393. };
  92394. /**
  92395. * Defines an override for loading shader strings
  92396. * Return true to stop further extensions from loading this shader data
  92397. */
  92398. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92399. return false;
  92400. };
  92401. /**
  92402. * Defines an override for loading materials
  92403. * Return true to stop further extensions from loading this material
  92404. */
  92405. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92406. return false;
  92407. };
  92408. // ---------
  92409. // Utilities
  92410. // ---------
  92411. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92412. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92413. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92414. }, function () {
  92415. setTimeout(function () {
  92416. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92417. });
  92418. });
  92419. };
  92420. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92421. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92422. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92423. }, function () {
  92424. setTimeout(function () {
  92425. onSuccess();
  92426. });
  92427. });
  92428. };
  92429. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92430. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92431. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92432. }, function () {
  92433. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92434. });
  92435. };
  92436. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92437. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92438. };
  92439. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92440. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92441. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92442. }, function () {
  92443. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92444. });
  92445. };
  92446. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92447. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92448. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92449. }, function () {
  92450. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92451. });
  92452. };
  92453. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92454. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92455. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92456. }, function () {
  92457. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92458. });
  92459. };
  92460. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92461. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92462. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92463. }, function () {
  92464. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92465. });
  92466. };
  92467. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92468. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92469. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92470. if (func(loaderExtension)) {
  92471. return;
  92472. }
  92473. }
  92474. defaultFunc();
  92475. };
  92476. return GLTFLoaderExtension;
  92477. }());
  92478. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92479. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92480. })(BABYLON || (BABYLON = {}));
  92481. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92482. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92483. var BABYLON;
  92484. (function (BABYLON) {
  92485. var GLTF1;
  92486. (function (GLTF1) {
  92487. var BinaryExtensionBufferName = "binary_glTF";
  92488. ;
  92489. ;
  92490. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92491. __extends(GLTFBinaryExtension, _super);
  92492. function GLTFBinaryExtension() {
  92493. return _super.call(this, "KHR_binary_glTF") || this;
  92494. }
  92495. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92496. var extensionsUsed = data.json.extensionsUsed;
  92497. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92498. return false;
  92499. }
  92500. this._bin = data.bin;
  92501. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92502. return true;
  92503. };
  92504. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92505. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92506. return false;
  92507. }
  92508. if (id !== BinaryExtensionBufferName) {
  92509. return false;
  92510. }
  92511. onSuccess(this._bin);
  92512. return true;
  92513. };
  92514. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92515. var texture = gltfRuntime.textures[id];
  92516. var source = gltfRuntime.images[texture.source];
  92517. if (!source.extensions || !(this.name in source.extensions)) {
  92518. return false;
  92519. }
  92520. var sourceExt = source.extensions[this.name];
  92521. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92522. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92523. onSuccess(buffer);
  92524. return true;
  92525. };
  92526. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92527. var shader = gltfRuntime.shaders[id];
  92528. if (!shader.extensions || !(this.name in shader.extensions)) {
  92529. return false;
  92530. }
  92531. var binaryExtensionShader = shader.extensions[this.name];
  92532. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92533. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92534. setTimeout(function () {
  92535. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92536. onSuccess(shaderString);
  92537. });
  92538. return true;
  92539. };
  92540. return GLTFBinaryExtension;
  92541. }(GLTF1.GLTFLoaderExtension));
  92542. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92543. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92544. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92545. })(BABYLON || (BABYLON = {}));
  92546. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92547. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92548. var BABYLON;
  92549. (function (BABYLON) {
  92550. var GLTF1;
  92551. (function (GLTF1) {
  92552. ;
  92553. ;
  92554. ;
  92555. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92556. __extends(GLTFMaterialsCommonExtension, _super);
  92557. function GLTFMaterialsCommonExtension() {
  92558. return _super.call(this, "KHR_materials_common") || this;
  92559. }
  92560. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92561. if (!gltfRuntime.extensions)
  92562. return false;
  92563. var extension = gltfRuntime.extensions[this.name];
  92564. if (!extension)
  92565. return false;
  92566. // Create lights
  92567. var lights = extension.lights;
  92568. if (lights) {
  92569. for (var thing in lights) {
  92570. var light = lights[thing];
  92571. switch (light.type) {
  92572. case "ambient":
  92573. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92574. var ambient = light.ambient;
  92575. if (ambient) {
  92576. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92577. }
  92578. break;
  92579. case "point":
  92580. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92581. var point = light.point;
  92582. if (point) {
  92583. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92584. }
  92585. break;
  92586. case "directional":
  92587. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92588. var directional = light.directional;
  92589. if (directional) {
  92590. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92591. }
  92592. break;
  92593. case "spot":
  92594. var spot = light.spot;
  92595. if (spot) {
  92596. 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);
  92597. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92598. }
  92599. break;
  92600. default:
  92601. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92602. break;
  92603. }
  92604. }
  92605. }
  92606. return false;
  92607. };
  92608. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92609. var material = gltfRuntime.materials[id];
  92610. if (!material || !material.extensions)
  92611. return false;
  92612. var extension = material.extensions[this.name];
  92613. if (!extension)
  92614. return false;
  92615. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92616. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92617. if (extension.technique === "CONSTANT") {
  92618. standardMaterial.disableLighting = true;
  92619. }
  92620. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92621. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92622. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92623. // Ambient
  92624. if (typeof extension.values.ambient === "string") {
  92625. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92626. }
  92627. else {
  92628. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92629. }
  92630. // Diffuse
  92631. if (typeof extension.values.diffuse === "string") {
  92632. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92633. }
  92634. else {
  92635. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92636. }
  92637. // Emission
  92638. if (typeof extension.values.emission === "string") {
  92639. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92640. }
  92641. else {
  92642. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92643. }
  92644. // Specular
  92645. if (typeof extension.values.specular === "string") {
  92646. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92647. }
  92648. else {
  92649. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92650. }
  92651. return true;
  92652. };
  92653. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92654. // Create buffer from texture url
  92655. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92656. // Create texture from buffer
  92657. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92658. }, onError);
  92659. };
  92660. return GLTFMaterialsCommonExtension;
  92661. }(GLTF1.GLTFLoaderExtension));
  92662. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92663. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92664. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92665. })(BABYLON || (BABYLON = {}));
  92666. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92667. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92668. var BABYLON;
  92669. (function (BABYLON) {
  92670. var GLTF2;
  92671. (function (GLTF2) {
  92672. var ArrayItem = /** @class */ (function () {
  92673. function ArrayItem() {
  92674. }
  92675. ArrayItem.Assign = function (values) {
  92676. if (values) {
  92677. for (var index = 0; index < values.length; index++) {
  92678. values[index]._index = index;
  92679. }
  92680. }
  92681. };
  92682. return ArrayItem;
  92683. }());
  92684. GLTF2.ArrayItem = ArrayItem;
  92685. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92686. })(BABYLON || (BABYLON = {}));
  92687. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92688. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92689. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92690. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92691. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92692. var BABYLON;
  92693. (function (BABYLON) {
  92694. var GLTF2;
  92695. (function (GLTF2) {
  92696. var GLTFLoader = /** @class */ (function () {
  92697. function GLTFLoader() {
  92698. this._completePromises = new Array();
  92699. this._disposed = false;
  92700. this._state = null;
  92701. this._extensions = {};
  92702. this._defaultSampler = {};
  92703. this._requests = new Array();
  92704. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92705. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92706. this.compileMaterials = false;
  92707. this.useClipPlane = false;
  92708. this.compileShadowGenerators = false;
  92709. this.onDisposeObservable = new BABYLON.Observable();
  92710. this.onMeshLoadedObservable = new BABYLON.Observable();
  92711. this.onTextureLoadedObservable = new BABYLON.Observable();
  92712. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92713. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92714. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92715. this.onCompleteObservable = new BABYLON.Observable();
  92716. }
  92717. GLTFLoader._Register = function (name, factory) {
  92718. if (GLTFLoader._Factories[name]) {
  92719. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92720. return;
  92721. }
  92722. GLTFLoader._Factories[name] = factory;
  92723. // Keep the order of registration so that extensions registered first are called first.
  92724. GLTFLoader._Names.push(name);
  92725. };
  92726. Object.defineProperty(GLTFLoader.prototype, "state", {
  92727. get: function () {
  92728. return this._state;
  92729. },
  92730. enumerable: true,
  92731. configurable: true
  92732. });
  92733. GLTFLoader.prototype.dispose = function () {
  92734. if (this._disposed) {
  92735. return;
  92736. }
  92737. this._disposed = true;
  92738. this.onDisposeObservable.notifyObservers(this);
  92739. this.onDisposeObservable.clear();
  92740. this._clear();
  92741. };
  92742. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92743. var _this = this;
  92744. return Promise.resolve().then(function () {
  92745. var nodes = null;
  92746. if (meshesNames) {
  92747. var nodeMap_1 = {};
  92748. if (_this._gltf.nodes) {
  92749. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92750. var node = _a[_i];
  92751. if (node.name) {
  92752. nodeMap_1[node.name] = node;
  92753. }
  92754. }
  92755. }
  92756. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92757. nodes = names.map(function (name) {
  92758. var node = nodeMap_1[name];
  92759. if (!node) {
  92760. throw new Error("Failed to find node '" + name + "'");
  92761. }
  92762. return node;
  92763. });
  92764. }
  92765. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92766. return {
  92767. meshes: _this._getMeshes(),
  92768. particleSystems: [],
  92769. skeletons: _this._getSkeletons(),
  92770. };
  92771. });
  92772. });
  92773. };
  92774. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92775. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92776. };
  92777. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92778. var _this = this;
  92779. return Promise.resolve().then(function () {
  92780. _this._loadExtensions();
  92781. _this._babylonScene = scene;
  92782. _this._rootUrl = rootUrl;
  92783. _this._progressCallback = onProgress;
  92784. _this._state = BABYLON.GLTFLoaderState.Loading;
  92785. _this._loadData(data);
  92786. _this._checkExtensions();
  92787. var promises = new Array();
  92788. if (nodes) {
  92789. promises.push(_this._loadNodesAsync(nodes));
  92790. }
  92791. else {
  92792. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92793. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92794. }
  92795. if (_this.compileMaterials) {
  92796. promises.push(_this._compileMaterialsAsync());
  92797. }
  92798. if (_this.compileShadowGenerators) {
  92799. promises.push(_this._compileShadowGeneratorsAsync());
  92800. }
  92801. var resultPromise = Promise.all(promises).then(function () {
  92802. _this._state = BABYLON.GLTFLoaderState.Ready;
  92803. _this._startAnimations();
  92804. });
  92805. resultPromise.then(function () {
  92806. _this._rootBabylonMesh.setEnabled(true);
  92807. BABYLON.Tools.SetImmediate(function () {
  92808. if (!_this._disposed) {
  92809. Promise.all(_this._completePromises).then(function () {
  92810. _this._state = BABYLON.GLTFLoaderState.Complete;
  92811. _this.onCompleteObservable.notifyObservers(_this);
  92812. _this.onCompleteObservable.clear();
  92813. _this._clear();
  92814. }).catch(function (error) {
  92815. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92816. _this._clear();
  92817. });
  92818. }
  92819. });
  92820. });
  92821. return resultPromise;
  92822. }).catch(function (error) {
  92823. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92824. _this._clear();
  92825. throw error;
  92826. });
  92827. };
  92828. GLTFLoader.prototype._loadExtensions = function () {
  92829. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92830. var name_1 = _a[_i];
  92831. var extension = GLTFLoader._Factories[name_1](this);
  92832. this._extensions[name_1] = extension;
  92833. this.onExtensionLoadedObservable.notifyObservers(extension);
  92834. }
  92835. this.onExtensionLoadedObservable.clear();
  92836. };
  92837. GLTFLoader.prototype._loadData = function (data) {
  92838. this._gltf = data.json;
  92839. this._setupData();
  92840. if (data.bin) {
  92841. var buffers = this._gltf.buffers;
  92842. if (buffers && buffers[0] && !buffers[0].uri) {
  92843. var binaryBuffer = buffers[0];
  92844. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92845. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92846. }
  92847. binaryBuffer._data = Promise.resolve(data.bin);
  92848. }
  92849. else {
  92850. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92851. }
  92852. }
  92853. };
  92854. GLTFLoader.prototype._setupData = function () {
  92855. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92856. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92857. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92858. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92859. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92860. GLTF2.ArrayItem.Assign(this._gltf.images);
  92861. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92862. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92863. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92864. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92865. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92866. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92867. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92868. if (this._gltf.nodes) {
  92869. var nodeParents = {};
  92870. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92871. var node = _a[_i];
  92872. if (node.children) {
  92873. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92874. var index = _c[_b];
  92875. nodeParents[index] = node._index;
  92876. }
  92877. }
  92878. }
  92879. var rootNode = this._createRootNode();
  92880. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92881. var node = _e[_d];
  92882. var parentIndex = nodeParents[node._index];
  92883. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92884. }
  92885. }
  92886. };
  92887. GLTFLoader.prototype._checkExtensions = function () {
  92888. if (this._gltf.extensionsRequired) {
  92889. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92890. var name_2 = _a[_i];
  92891. var extension = this._extensions[name_2];
  92892. if (!extension || !extension.enabled) {
  92893. throw new Error("Require extension " + name_2 + " is not available");
  92894. }
  92895. }
  92896. }
  92897. };
  92898. GLTFLoader.prototype._createRootNode = function () {
  92899. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92900. this._rootBabylonMesh.setEnabled(false);
  92901. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92902. switch (this.coordinateSystemMode) {
  92903. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92904. if (!this._babylonScene.useRightHandedSystem) {
  92905. rootNode.rotation = [0, 1, 0, 0];
  92906. rootNode.scale = [1, 1, -1];
  92907. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92908. }
  92909. break;
  92910. }
  92911. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92912. this._babylonScene.useRightHandedSystem = true;
  92913. break;
  92914. }
  92915. default: {
  92916. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  92917. }
  92918. }
  92919. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92920. return rootNode;
  92921. };
  92922. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92923. var promises = new Array();
  92924. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92925. var node = nodes_1[_i];
  92926. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92927. }
  92928. promises.push(this._loadAnimationsAsync());
  92929. return Promise.all(promises).then(function () { });
  92930. };
  92931. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92932. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92933. if (promise) {
  92934. return promise;
  92935. }
  92936. var promises = new Array();
  92937. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92938. var index = _a[_i];
  92939. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92940. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92941. }
  92942. promises.push(this._loadAnimationsAsync());
  92943. return Promise.all(promises).then(function () { });
  92944. };
  92945. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  92946. if (node._babylonMesh) {
  92947. callback(node._babylonMesh);
  92948. }
  92949. if (node._primitiveBabylonMeshes) {
  92950. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92951. var babylonMesh = _a[_i];
  92952. callback(babylonMesh);
  92953. }
  92954. }
  92955. };
  92956. GLTFLoader.prototype._getMeshes = function () {
  92957. var meshes = new Array();
  92958. // Root mesh is always first.
  92959. meshes.push(this._rootBabylonMesh);
  92960. var nodes = this._gltf.nodes;
  92961. if (nodes) {
  92962. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92963. var node = nodes_2[_i];
  92964. this._forEachNodeMesh(node, function (mesh) {
  92965. meshes.push(mesh);
  92966. });
  92967. }
  92968. }
  92969. return meshes;
  92970. };
  92971. GLTFLoader.prototype._getSkeletons = function () {
  92972. var skeletons = new Array();
  92973. var skins = this._gltf.skins;
  92974. if (skins) {
  92975. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92976. var skin = skins_1[_i];
  92977. if (skin._babylonSkeleton) {
  92978. skeletons.push(skin._babylonSkeleton);
  92979. }
  92980. }
  92981. }
  92982. return skeletons;
  92983. };
  92984. GLTFLoader.prototype._startAnimations = function () {
  92985. var animations = this._gltf.animations;
  92986. if (!animations) {
  92987. return;
  92988. }
  92989. switch (this.animationStartMode) {
  92990. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92991. // do nothing
  92992. break;
  92993. }
  92994. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92995. var animation = animations[0];
  92996. animation._babylonAnimationGroup.start(true);
  92997. break;
  92998. }
  92999. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  93000. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  93001. var animation = animations_1[_i];
  93002. animation._babylonAnimationGroup.start(true);
  93003. }
  93004. break;
  93005. }
  93006. default: {
  93007. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  93008. return;
  93009. }
  93010. }
  93011. };
  93012. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  93013. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  93014. if (promise) {
  93015. return promise;
  93016. }
  93017. if (node._babylonMesh) {
  93018. throw new Error(context + ": Invalid recursive node hierarchy");
  93019. }
  93020. var promises = new Array();
  93021. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  93022. node._babylonMesh = babylonMesh;
  93023. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93024. node._babylonAnimationTargets.push(babylonMesh);
  93025. GLTFLoader._LoadTransform(node, babylonMesh);
  93026. if (node.mesh != undefined) {
  93027. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  93028. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  93029. }
  93030. if (node.children) {
  93031. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  93032. var index = _a[_i];
  93033. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  93034. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  93035. }
  93036. }
  93037. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93038. return Promise.all(promises).then(function () { });
  93039. };
  93040. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  93041. // TODO: instancing
  93042. var _this = this;
  93043. var promises = new Array();
  93044. var primitives = mesh.primitives;
  93045. if (!primitives || primitives.length === 0) {
  93046. throw new Error(context + ": Primitives are missing");
  93047. }
  93048. GLTF2.ArrayItem.Assign(primitives);
  93049. if (primitives.length === 1) {
  93050. var primitive = primitives[0];
  93051. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  93052. }
  93053. else {
  93054. node._primitiveBabylonMeshes = [];
  93055. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  93056. var primitive = primitives_1[_i];
  93057. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  93058. node._primitiveBabylonMeshes.push(babylonMesh);
  93059. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  93060. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93061. }
  93062. }
  93063. if (node.skin != undefined) {
  93064. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  93065. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  93066. }
  93067. return Promise.all(promises).then(function () {
  93068. _this._forEachNodeMesh(node, function (babylonMesh) {
  93069. babylonMesh._refreshBoundingInfo(true);
  93070. });
  93071. });
  93072. };
  93073. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  93074. var _this = this;
  93075. var promises = new Array();
  93076. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  93077. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  93078. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  93079. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  93080. }));
  93081. if (primitive.material == undefined) {
  93082. babylonMesh.material = this._getDefaultMaterial();
  93083. }
  93084. else {
  93085. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  93086. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  93087. babylonMesh.material = babylonMaterial;
  93088. }));
  93089. }
  93090. return Promise.all(promises).then(function () { });
  93091. };
  93092. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93093. var _this = this;
  93094. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  93095. if (promise) {
  93096. return promise;
  93097. }
  93098. var attributes = primitive.attributes;
  93099. if (!attributes) {
  93100. throw new Error(context + ": Attributes are missing");
  93101. }
  93102. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93103. // TODO: handle other primitive modes
  93104. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93105. }
  93106. var promises = new Array();
  93107. var babylonVertexData = new BABYLON.VertexData();
  93108. if (primitive.indices == undefined) {
  93109. var positionAccessorIndex = attributes["POSITION"];
  93110. if (positionAccessorIndex != undefined) {
  93111. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93112. babylonVertexData.indices = new Uint32Array(accessor.count);
  93113. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93114. babylonVertexData.indices[i] = i;
  93115. }
  93116. }
  93117. }
  93118. else {
  93119. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93120. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93121. babylonVertexData.indices = data;
  93122. }));
  93123. }
  93124. var loadAttribute = function (attribute, kind) {
  93125. if (attributes[attribute] == undefined) {
  93126. return;
  93127. }
  93128. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93129. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93130. babylonMesh._delayInfo.push(kind);
  93131. }
  93132. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93133. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93134. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93135. if (attribute === "COLOR_0") {
  93136. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93137. babylonMesh.hasVertexAlpha = true;
  93138. if (accessor.type === "VEC3") {
  93139. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93140. }
  93141. }
  93142. babylonVertexData.set(attributeData, kind);
  93143. }));
  93144. };
  93145. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93146. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93147. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93148. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93149. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93150. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93151. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93152. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93153. return Promise.all(promises).then(function () {
  93154. return babylonVertexData;
  93155. });
  93156. };
  93157. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93158. if (!primitive.targets) {
  93159. return;
  93160. }
  93161. if (node._numMorphTargets == undefined) {
  93162. node._numMorphTargets = primitive.targets.length;
  93163. }
  93164. else if (primitive.targets.length !== node._numMorphTargets) {
  93165. throw new Error(context + ": Primitives do not have the same number of targets");
  93166. }
  93167. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93168. for (var index = 0; index < primitive.targets.length; index++) {
  93169. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93170. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93171. // TODO: tell the target whether it has positions, normals, tangents
  93172. }
  93173. };
  93174. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93175. if (!primitive.targets) {
  93176. return Promise.resolve();
  93177. }
  93178. var promises = new Array();
  93179. var morphTargetManager = babylonMesh.morphTargetManager;
  93180. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93181. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93182. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93183. }
  93184. return Promise.all(promises).then(function () { });
  93185. };
  93186. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93187. var _this = this;
  93188. var promises = new Array();
  93189. var loadAttribute = function (attribute, setData) {
  93190. if (attributes[attribute] == undefined) {
  93191. return;
  93192. }
  93193. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93194. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93195. setData(data);
  93196. }));
  93197. };
  93198. loadAttribute("POSITION", function (data) {
  93199. if (babylonVertexData.positions) {
  93200. for (var i = 0; i < data.length; i++) {
  93201. data[i] += babylonVertexData.positions[i];
  93202. }
  93203. babylonMorphTarget.setPositions(data);
  93204. }
  93205. });
  93206. loadAttribute("NORMAL", function (data) {
  93207. if (babylonVertexData.normals) {
  93208. for (var i = 0; i < data.length; i++) {
  93209. data[i] += babylonVertexData.normals[i];
  93210. }
  93211. babylonMorphTarget.setNormals(data);
  93212. }
  93213. });
  93214. loadAttribute("TANGENT", function (data) {
  93215. if (babylonVertexData.tangents) {
  93216. // Tangent data for morph targets is stored as xyz delta.
  93217. // The vertexData.tangent is stored as xyzw.
  93218. // So we need to skip every fourth vertexData.tangent.
  93219. for (var i = 0, j = 0; i < data.length; i++) {
  93220. data[i] += babylonVertexData.tangents[j++];
  93221. if ((i + 1) % 3 == 0) {
  93222. j++;
  93223. }
  93224. }
  93225. babylonMorphTarget.setTangents(data);
  93226. }
  93227. });
  93228. return Promise.all(promises).then(function () { });
  93229. };
  93230. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93231. if (accessor.componentType == 5126 /* FLOAT */) {
  93232. return data;
  93233. }
  93234. var factor = 1;
  93235. if (accessor.normalized) {
  93236. switch (accessor.componentType) {
  93237. case 5121 /* UNSIGNED_BYTE */: {
  93238. factor = 1 / 255;
  93239. break;
  93240. }
  93241. case 5123 /* UNSIGNED_SHORT */: {
  93242. factor = 1 / 65535;
  93243. break;
  93244. }
  93245. default: {
  93246. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93247. }
  93248. }
  93249. }
  93250. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93251. for (var i = 0; i < result.length; i++) {
  93252. result[i] = data[i] * factor;
  93253. }
  93254. return result;
  93255. };
  93256. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93257. var result = new Float32Array(data.length / 3 * 4);
  93258. var offset = 0;
  93259. for (var i = 0; i < result.length; i++) {
  93260. if ((i + 1) % 4 === 0) {
  93261. result[i] = 1;
  93262. }
  93263. else {
  93264. result[i] = data[offset++];
  93265. }
  93266. }
  93267. return result;
  93268. };
  93269. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93270. var position = BABYLON.Vector3.Zero();
  93271. var rotation = BABYLON.Quaternion.Identity();
  93272. var scaling = BABYLON.Vector3.One();
  93273. if (node.matrix) {
  93274. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93275. matrix.decompose(scaling, rotation, position);
  93276. }
  93277. else {
  93278. if (node.translation)
  93279. position = BABYLON.Vector3.FromArray(node.translation);
  93280. if (node.rotation)
  93281. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93282. if (node.scale)
  93283. scaling = BABYLON.Vector3.FromArray(node.scale);
  93284. }
  93285. babylonNode.position = position;
  93286. babylonNode.rotationQuaternion = rotation;
  93287. babylonNode.scaling = scaling;
  93288. };
  93289. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93290. var _this = this;
  93291. var assignSkeleton = function () {
  93292. _this._forEachNodeMesh(node, function (babylonMesh) {
  93293. babylonMesh.skeleton = skin._babylonSkeleton;
  93294. });
  93295. node._babylonMesh.parent = _this._rootBabylonMesh;
  93296. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93297. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93298. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93299. };
  93300. if (skin._loaded) {
  93301. return skin._loaded.then(function () {
  93302. assignSkeleton();
  93303. });
  93304. }
  93305. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93306. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93307. var skeletonId = "skeleton" + skin._index;
  93308. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93309. skin._babylonSkeleton = babylonSkeleton;
  93310. _this._loadBones(context, skin, inverseBindMatricesData);
  93311. assignSkeleton();
  93312. }));
  93313. };
  93314. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93315. if (skin.inverseBindMatrices == undefined) {
  93316. return Promise.resolve(null);
  93317. }
  93318. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93319. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93320. return data;
  93321. });
  93322. };
  93323. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93324. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93325. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93326. node._babylonAnimationTargets.push(babylonBone);
  93327. return babylonBone;
  93328. };
  93329. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93330. var babylonBones = {};
  93331. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93332. var index = _a[_i];
  93333. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93334. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93335. }
  93336. };
  93337. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93338. var babylonBone = babylonBones[node._index];
  93339. if (babylonBone) {
  93340. return babylonBone;
  93341. }
  93342. var boneIndex = skin.joints.indexOf(node._index);
  93343. var baseMatrix = BABYLON.Matrix.Identity();
  93344. if (inverseBindMatricesData && boneIndex !== -1) {
  93345. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93346. baseMatrix.invertToRef(baseMatrix);
  93347. }
  93348. var babylonParentBone = null;
  93349. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93350. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93351. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93352. }
  93353. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93354. babylonBones[node._index] = babylonBone;
  93355. return babylonBone;
  93356. };
  93357. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93358. return node.matrix ?
  93359. BABYLON.Matrix.FromArray(node.matrix) :
  93360. 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());
  93361. };
  93362. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93363. var animations = this._gltf.animations;
  93364. if (!animations) {
  93365. return Promise.resolve();
  93366. }
  93367. var promises = new Array();
  93368. for (var index = 0; index < animations.length; index++) {
  93369. var animation = animations[index];
  93370. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93371. }
  93372. return Promise.all(promises).then(function () { });
  93373. };
  93374. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93375. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93376. animation._babylonAnimationGroup = babylonAnimationGroup;
  93377. var promises = new Array();
  93378. GLTF2.ArrayItem.Assign(animation.channels);
  93379. GLTF2.ArrayItem.Assign(animation.samplers);
  93380. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93381. var channel = _a[_i];
  93382. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93383. }
  93384. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93385. return Promise.all(promises).then(function () {
  93386. babylonAnimationGroup.normalize();
  93387. });
  93388. };
  93389. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93390. var _this = this;
  93391. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93392. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93393. return Promise.resolve();
  93394. }
  93395. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93396. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93397. var targetPath;
  93398. var animationType;
  93399. switch (channel.target.path) {
  93400. case "translation" /* TRANSLATION */: {
  93401. targetPath = "position";
  93402. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93403. break;
  93404. }
  93405. case "rotation" /* ROTATION */: {
  93406. targetPath = "rotationQuaternion";
  93407. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93408. break;
  93409. }
  93410. case "scale" /* SCALE */: {
  93411. targetPath = "scaling";
  93412. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93413. break;
  93414. }
  93415. case "weights" /* WEIGHTS */: {
  93416. targetPath = "influence";
  93417. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93418. break;
  93419. }
  93420. default: {
  93421. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93422. }
  93423. }
  93424. var outputBufferOffset = 0;
  93425. var getNextOutputValue;
  93426. switch (targetPath) {
  93427. case "position": {
  93428. getNextOutputValue = function () {
  93429. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93430. outputBufferOffset += 3;
  93431. return value;
  93432. };
  93433. break;
  93434. }
  93435. case "rotationQuaternion": {
  93436. getNextOutputValue = function () {
  93437. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93438. outputBufferOffset += 4;
  93439. return value;
  93440. };
  93441. break;
  93442. }
  93443. case "scaling": {
  93444. getNextOutputValue = function () {
  93445. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93446. outputBufferOffset += 3;
  93447. return value;
  93448. };
  93449. break;
  93450. }
  93451. case "influence": {
  93452. getNextOutputValue = function () {
  93453. var value = new Array(targetNode._numMorphTargets);
  93454. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93455. value[i] = data.output[outputBufferOffset++];
  93456. }
  93457. return value;
  93458. };
  93459. break;
  93460. }
  93461. }
  93462. var getNextKey;
  93463. switch (data.interpolation) {
  93464. case "STEP" /* STEP */: {
  93465. getNextKey = function (frameIndex) { return ({
  93466. frame: data.input[frameIndex],
  93467. value: getNextOutputValue(),
  93468. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93469. }); };
  93470. break;
  93471. }
  93472. case "LINEAR" /* LINEAR */: {
  93473. getNextKey = function (frameIndex) { return ({
  93474. frame: data.input[frameIndex],
  93475. value: getNextOutputValue()
  93476. }); };
  93477. break;
  93478. }
  93479. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93480. getNextKey = function (frameIndex) { return ({
  93481. frame: data.input[frameIndex],
  93482. inTangent: getNextOutputValue(),
  93483. value: getNextOutputValue(),
  93484. outTangent: getNextOutputValue()
  93485. }); };
  93486. break;
  93487. }
  93488. }
  93489. var keys;
  93490. if (data.input.length === 1) {
  93491. var key = getNextKey(0);
  93492. keys = [
  93493. { frame: key.frame, value: key.value },
  93494. { frame: key.frame + 1, value: key.value }
  93495. ];
  93496. }
  93497. else {
  93498. keys = new Array(data.input.length);
  93499. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93500. keys[frameIndex] = getNextKey(frameIndex);
  93501. }
  93502. }
  93503. if (targetPath === "influence") {
  93504. var _loop_1 = function (targetIndex) {
  93505. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93506. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93507. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93508. frame: key.frame,
  93509. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93510. value: key.value[targetIndex],
  93511. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93512. }); }));
  93513. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93514. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93515. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93516. });
  93517. };
  93518. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93519. _loop_1(targetIndex);
  93520. }
  93521. }
  93522. else {
  93523. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93524. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93525. babylonAnimation.setKeys(keys);
  93526. if (targetNode._babylonAnimationTargets) {
  93527. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93528. var target = _a[_i];
  93529. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93530. }
  93531. }
  93532. }
  93533. });
  93534. };
  93535. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93536. if (sampler._data) {
  93537. return sampler._data;
  93538. }
  93539. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93540. switch (interpolation) {
  93541. case "STEP" /* STEP */:
  93542. case "LINEAR" /* LINEAR */:
  93543. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93544. break;
  93545. }
  93546. default: {
  93547. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93548. }
  93549. }
  93550. var inputData;
  93551. var outputData;
  93552. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93553. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93554. sampler._data = Promise.all([
  93555. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93556. inputData = data;
  93557. }),
  93558. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93559. outputData = data;
  93560. })
  93561. ]).then(function () {
  93562. return {
  93563. input: inputData,
  93564. interpolation: interpolation,
  93565. output: outputData,
  93566. };
  93567. });
  93568. return sampler._data;
  93569. };
  93570. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93571. if (buffer._data) {
  93572. return buffer._data;
  93573. }
  93574. if (!buffer.uri) {
  93575. throw new Error(context + ": Uri is missing");
  93576. }
  93577. buffer._data = this._loadUriAsync(context, buffer.uri);
  93578. return buffer._data;
  93579. };
  93580. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93581. if (bufferView._data) {
  93582. return bufferView._data;
  93583. }
  93584. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93585. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93586. try {
  93587. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93588. }
  93589. catch (e) {
  93590. throw new Error(context + ": " + e.message);
  93591. }
  93592. });
  93593. return bufferView._data;
  93594. };
  93595. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93596. var _this = this;
  93597. if (accessor.sparse) {
  93598. throw new Error(context + ": Sparse accessors are not currently supported");
  93599. }
  93600. if (accessor._data) {
  93601. return accessor._data;
  93602. }
  93603. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93604. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93605. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93606. var byteOffset = accessor.byteOffset || 0;
  93607. var byteStride = bufferView.byteStride;
  93608. if (byteStride === 0) {
  93609. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93610. }
  93611. try {
  93612. switch (accessor.componentType) {
  93613. case 5120 /* BYTE */: {
  93614. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93615. }
  93616. case 5121 /* UNSIGNED_BYTE */: {
  93617. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93618. }
  93619. case 5122 /* SHORT */: {
  93620. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93621. }
  93622. case 5123 /* UNSIGNED_SHORT */: {
  93623. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93624. }
  93625. case 5125 /* UNSIGNED_INT */: {
  93626. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93627. }
  93628. case 5126 /* FLOAT */: {
  93629. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93630. }
  93631. default: {
  93632. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93633. }
  93634. }
  93635. }
  93636. catch (e) {
  93637. throw new Error(context + ": " + e.messsage);
  93638. }
  93639. });
  93640. return accessor._data;
  93641. };
  93642. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93643. byteOffset += data.byteOffset;
  93644. var targetLength = count * numComponents;
  93645. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93646. return new typedArray(data.buffer, byteOffset, targetLength);
  93647. }
  93648. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93649. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93650. var targetBuffer = new typedArray(targetLength);
  93651. var sourceIndex = 0;
  93652. var targetIndex = 0;
  93653. while (targetIndex < targetLength) {
  93654. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93655. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93656. targetIndex++;
  93657. }
  93658. sourceIndex += elementStride;
  93659. }
  93660. return targetBuffer;
  93661. };
  93662. GLTFLoader.prototype._getDefaultMaterial = function () {
  93663. var id = "__gltf_default";
  93664. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93665. if (!babylonMaterial) {
  93666. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93667. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93668. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93669. babylonMaterial.metallic = 1;
  93670. babylonMaterial.roughness = 1;
  93671. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93672. }
  93673. return babylonMaterial;
  93674. };
  93675. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93676. var promises = new Array();
  93677. var babylonMaterial = material._babylonMaterial;
  93678. // Ensure metallic workflow
  93679. babylonMaterial.metallic = 1;
  93680. babylonMaterial.roughness = 1;
  93681. var properties = material.pbrMetallicRoughness;
  93682. if (properties) {
  93683. if (properties.baseColorFactor) {
  93684. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93685. babylonMaterial.alpha = properties.baseColorFactor[3];
  93686. }
  93687. else {
  93688. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93689. }
  93690. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93691. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93692. if (properties.baseColorTexture) {
  93693. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93694. babylonMaterial.albedoTexture = texture;
  93695. }));
  93696. }
  93697. if (properties.metallicRoughnessTexture) {
  93698. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93699. babylonMaterial.metallicTexture = texture;
  93700. }));
  93701. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93702. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93703. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93704. }
  93705. }
  93706. this._loadMaterialAlphaProperties(context, material);
  93707. return Promise.all(promises).then(function () { });
  93708. };
  93709. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93710. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93711. if (promise) {
  93712. return promise;
  93713. }
  93714. material._babylonMeshes = material._babylonMeshes || [];
  93715. material._babylonMeshes.push(babylonMesh);
  93716. if (!material._loaded) {
  93717. var promises = new Array();
  93718. var babylonMaterial = this._createMaterial(material);
  93719. material._babylonMaterial = babylonMaterial;
  93720. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93721. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93722. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93723. material._loaded = Promise.all(promises).then(function () { });
  93724. }
  93725. assign(material._babylonMaterial);
  93726. return material._loaded;
  93727. };
  93728. GLTFLoader.prototype._createMaterial = function (material) {
  93729. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93730. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93731. return babylonMaterial;
  93732. };
  93733. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93734. var promises = new Array();
  93735. var babylonMaterial = material._babylonMaterial;
  93736. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93737. if (material.doubleSided) {
  93738. babylonMaterial.backFaceCulling = false;
  93739. babylonMaterial.twoSidedLighting = true;
  93740. }
  93741. if (material.normalTexture) {
  93742. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93743. babylonMaterial.bumpTexture = texture;
  93744. }));
  93745. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93746. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93747. if (material.normalTexture.scale != undefined) {
  93748. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93749. }
  93750. }
  93751. if (material.occlusionTexture) {
  93752. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93753. babylonMaterial.ambientTexture = texture;
  93754. }));
  93755. babylonMaterial.useAmbientInGrayScale = true;
  93756. if (material.occlusionTexture.strength != undefined) {
  93757. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93758. }
  93759. }
  93760. if (material.emissiveTexture) {
  93761. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93762. babylonMaterial.emissiveTexture = texture;
  93763. }));
  93764. }
  93765. return Promise.all(promises).then(function () { });
  93766. };
  93767. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93768. var babylonMaterial = material._babylonMaterial;
  93769. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93770. switch (alphaMode) {
  93771. case "OPAQUE" /* OPAQUE */: {
  93772. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93773. break;
  93774. }
  93775. case "MASK" /* MASK */: {
  93776. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93777. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93778. if (babylonMaterial.alpha) {
  93779. if (babylonMaterial.alpha === 0) {
  93780. babylonMaterial.alphaCutOff = 1;
  93781. }
  93782. else {
  93783. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93784. }
  93785. babylonMaterial.alpha = 1;
  93786. }
  93787. if (babylonMaterial.albedoTexture) {
  93788. babylonMaterial.albedoTexture.hasAlpha = true;
  93789. }
  93790. break;
  93791. }
  93792. case "BLEND" /* BLEND */: {
  93793. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93794. if (babylonMaterial.albedoTexture) {
  93795. babylonMaterial.albedoTexture.hasAlpha = true;
  93796. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93797. }
  93798. break;
  93799. }
  93800. default: {
  93801. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  93802. }
  93803. }
  93804. };
  93805. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93806. var _this = this;
  93807. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93808. context = "#/textures/" + textureInfo.index;
  93809. var promises = new Array();
  93810. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93811. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93812. var deferred = new BABYLON.Deferred();
  93813. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93814. if (!_this._disposed) {
  93815. deferred.resolve();
  93816. }
  93817. }, function (message, exception) {
  93818. if (!_this._disposed) {
  93819. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  93820. }
  93821. });
  93822. promises.push(deferred.promise);
  93823. babylonTexture.name = texture.name || "texture" + texture._index;
  93824. babylonTexture.wrapU = samplerData.wrapU;
  93825. babylonTexture.wrapV = samplerData.wrapV;
  93826. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93827. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93828. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93829. babylonTexture.updateURL(objectURL);
  93830. }));
  93831. assign(babylonTexture);
  93832. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93833. return Promise.all(promises).then(function () { });
  93834. };
  93835. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93836. if (!sampler._data) {
  93837. sampler._data = {
  93838. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93839. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93840. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93841. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93842. };
  93843. }
  93844. ;
  93845. return sampler._data;
  93846. };
  93847. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93848. if (image._objectURL) {
  93849. return image._objectURL;
  93850. }
  93851. var promise;
  93852. if (image.uri) {
  93853. promise = this._loadUriAsync(context, image.uri);
  93854. }
  93855. else {
  93856. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93857. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93858. }
  93859. image._objectURL = promise.then(function (data) {
  93860. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93861. });
  93862. return image._objectURL;
  93863. };
  93864. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93865. var _this = this;
  93866. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93867. if (promise) {
  93868. return promise;
  93869. }
  93870. if (!GLTFLoader._ValidateUri(uri)) {
  93871. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93872. }
  93873. if (BABYLON.Tools.IsBase64(uri)) {
  93874. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93875. }
  93876. return new Promise(function (resolve, reject) {
  93877. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93878. if (!_this._disposed) {
  93879. resolve(new Uint8Array(data));
  93880. }
  93881. }, function (event) {
  93882. if (!_this._disposed) {
  93883. try {
  93884. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93885. request._lengthComputable = event.lengthComputable;
  93886. request._loaded = event.loaded;
  93887. request._total = event.total;
  93888. _this._onProgress();
  93889. }
  93890. }
  93891. catch (e) {
  93892. reject(e);
  93893. }
  93894. }
  93895. }, _this._babylonScene.database, true, function (request, exception) {
  93896. if (!_this._disposed) {
  93897. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93898. }
  93899. });
  93900. _this._requests.push(request);
  93901. });
  93902. };
  93903. GLTFLoader.prototype._onProgress = function () {
  93904. if (!this._progressCallback) {
  93905. return;
  93906. }
  93907. var lengthComputable = true;
  93908. var loaded = 0;
  93909. var total = 0;
  93910. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93911. var request = _a[_i];
  93912. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93913. return;
  93914. }
  93915. lengthComputable = lengthComputable && request._lengthComputable;
  93916. loaded += request._loaded;
  93917. total += request._total;
  93918. }
  93919. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93920. };
  93921. GLTFLoader._GetProperty = function (context, array, index) {
  93922. if (!array || index == undefined || !array[index]) {
  93923. throw new Error(context + ": Failed to find index (" + index + ")");
  93924. }
  93925. return array[index];
  93926. };
  93927. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93928. // Set defaults if undefined
  93929. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93930. switch (mode) {
  93931. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93932. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93933. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93934. default:
  93935. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  93936. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93937. }
  93938. };
  93939. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93940. // Set defaults if undefined
  93941. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93942. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93943. if (magFilter === 9729 /* LINEAR */) {
  93944. switch (minFilter) {
  93945. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93946. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93947. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93948. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93949. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93950. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93951. default:
  93952. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  93953. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93954. }
  93955. }
  93956. else {
  93957. if (magFilter !== 9728 /* NEAREST */) {
  93958. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  93959. }
  93960. switch (minFilter) {
  93961. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93962. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93963. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93964. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93965. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93966. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93967. default:
  93968. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  93969. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93970. }
  93971. }
  93972. };
  93973. GLTFLoader._GetNumComponents = function (context, type) {
  93974. switch (type) {
  93975. case "SCALAR": return 1;
  93976. case "VEC2": return 2;
  93977. case "VEC3": return 3;
  93978. case "VEC4": return 4;
  93979. case "MAT2": return 4;
  93980. case "MAT3": return 9;
  93981. case "MAT4": return 16;
  93982. }
  93983. throw new Error(context + ": Invalid type (" + type + ")");
  93984. };
  93985. GLTFLoader._ValidateUri = function (uri) {
  93986. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93987. };
  93988. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93989. var promises = new Array();
  93990. if (this._gltf.materials) {
  93991. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93992. var material = _a[_i];
  93993. var babylonMaterial = material._babylonMaterial;
  93994. var babylonMeshes = material._babylonMeshes;
  93995. if (babylonMaterial && babylonMeshes) {
  93996. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93997. var babylonMesh = babylonMeshes_1[_b];
  93998. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93999. if (this.useClipPlane) {
  94000. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  94001. }
  94002. }
  94003. }
  94004. }
  94005. }
  94006. return Promise.all(promises).then(function () { });
  94007. };
  94008. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  94009. var promises = new Array();
  94010. var lights = this._babylonScene.lights;
  94011. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  94012. var light = lights_1[_i];
  94013. var generator = light.getShadowGenerator();
  94014. if (generator) {
  94015. promises.push(generator.forceCompilationAsync());
  94016. }
  94017. }
  94018. return Promise.all(promises).then(function () { });
  94019. };
  94020. GLTFLoader.prototype._clear = function () {
  94021. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94022. var request = _a[_i];
  94023. request.abort();
  94024. }
  94025. this._requests.length = 0;
  94026. if (this._gltf && this._gltf.images) {
  94027. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  94028. var image = _c[_b];
  94029. if (image._objectURL) {
  94030. image._objectURL.then(function (value) {
  94031. URL.revokeObjectURL(value);
  94032. });
  94033. image._objectURL = undefined;
  94034. }
  94035. }
  94036. }
  94037. delete this._gltf;
  94038. delete this._babylonScene;
  94039. this._completePromises.length = 0;
  94040. for (var name_3 in this._extensions) {
  94041. this._extensions[name_3].dispose();
  94042. }
  94043. this._extensions = {};
  94044. delete this._rootBabylonMesh;
  94045. delete this._progressCallback;
  94046. this.onMeshLoadedObservable.clear();
  94047. this.onTextureLoadedObservable.clear();
  94048. this.onMaterialLoadedObservable.clear();
  94049. };
  94050. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  94051. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94052. var name_4 = _a[_i];
  94053. var extension = this._extensions[name_4];
  94054. if (extension.enabled) {
  94055. var promise = actionAsync(extension);
  94056. if (promise) {
  94057. return promise;
  94058. }
  94059. }
  94060. }
  94061. return null;
  94062. };
  94063. GLTFLoader._Names = new Array();
  94064. GLTFLoader._Factories = {};
  94065. return GLTFLoader;
  94066. }());
  94067. GLTF2.GLTFLoader = GLTFLoader;
  94068. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  94069. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94070. })(BABYLON || (BABYLON = {}));
  94071. //# sourceMappingURL=babylon.glTFLoader.js.map
  94072. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94073. var BABYLON;
  94074. (function (BABYLON) {
  94075. var GLTF2;
  94076. (function (GLTF2) {
  94077. var GLTFLoaderExtension = /** @class */ (function () {
  94078. function GLTFLoaderExtension(loader) {
  94079. this.enabled = true;
  94080. this._loader = loader;
  94081. }
  94082. GLTFLoaderExtension.prototype.dispose = function () {
  94083. delete this._loader;
  94084. };
  94085. // #region Overridable Methods
  94086. /** Override this method to modify the default behavior for loading scenes. */
  94087. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  94088. /** Override this method to modify the default behavior for loading nodes. */
  94089. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  94090. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  94091. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  94092. /** Override this method to modify the default behavior for loading materials. */
  94093. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  94094. /** Override this method to modify the default behavior for loading uris. */
  94095. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  94096. // #endregion
  94097. /** Helper method called by a loader extension to load an glTF extension. */
  94098. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94099. if (!property.extensions) {
  94100. return null;
  94101. }
  94102. var extensions = property.extensions;
  94103. var extension = extensions[this.name];
  94104. if (!extension) {
  94105. return null;
  94106. }
  94107. // Clear out the extension before executing the action to avoid recursing into the same property.
  94108. delete extensions[this.name];
  94109. try {
  94110. return actionAsync(context + "/extensions/" + this.name, extension);
  94111. }
  94112. finally {
  94113. // Restore the extension after executing the action.
  94114. extensions[this.name] = extension;
  94115. }
  94116. };
  94117. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94118. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94119. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94120. };
  94121. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94122. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94123. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94124. };
  94125. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94126. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94127. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94128. };
  94129. /** Helper method called by the loader to allow extensions to override loading materials. */
  94130. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94131. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94132. };
  94133. /** Helper method called by the loader to allow extensions to override loading uris. */
  94134. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94135. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94136. };
  94137. return GLTFLoaderExtension;
  94138. }());
  94139. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94140. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94141. })(BABYLON || (BABYLON = {}));
  94142. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94143. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94144. var BABYLON;
  94145. (function (BABYLON) {
  94146. var GLTF2;
  94147. (function (GLTF2) {
  94148. var Extensions;
  94149. (function (Extensions) {
  94150. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94151. var NAME = "MSFT_lod";
  94152. var MSFT_lod = /** @class */ (function (_super) {
  94153. __extends(MSFT_lod, _super);
  94154. function MSFT_lod() {
  94155. var _this = _super !== null && _super.apply(this, arguments) || this;
  94156. _this.name = NAME;
  94157. /**
  94158. * Maximum number of LODs to load, starting from the lowest LOD.
  94159. */
  94160. _this.maxLODsToLoad = Number.MAX_VALUE;
  94161. _this._loadingNodeLOD = null;
  94162. _this._loadNodeSignals = {};
  94163. _this._loadingMaterialLOD = null;
  94164. _this._loadMaterialSignals = {};
  94165. return _this;
  94166. }
  94167. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94168. var _this = this;
  94169. return this._loadExtensionAsync(context, node, function (context, extension) {
  94170. var firstPromise;
  94171. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94172. var _loop_1 = function (indexLOD) {
  94173. var nodeLOD = nodeLODs[indexLOD];
  94174. if (indexLOD !== 0) {
  94175. _this._loadingNodeLOD = nodeLOD;
  94176. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94177. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94178. }
  94179. }
  94180. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94181. if (indexLOD !== 0) {
  94182. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94183. if (previousNodeLOD._babylonMesh) {
  94184. previousNodeLOD._babylonMesh.dispose();
  94185. delete previousNodeLOD._babylonMesh;
  94186. }
  94187. }
  94188. if (indexLOD !== nodeLODs.length - 1) {
  94189. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94190. if (_this._loadNodeSignals[nodeIndex]) {
  94191. _this._loadNodeSignals[nodeIndex].resolve();
  94192. delete _this._loadNodeSignals[nodeIndex];
  94193. }
  94194. }
  94195. });
  94196. if (indexLOD === 0) {
  94197. firstPromise = promise;
  94198. }
  94199. else {
  94200. _this._loader._completePromises.push(promise);
  94201. _this._loadingNodeLOD = null;
  94202. }
  94203. };
  94204. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94205. _loop_1(indexLOD);
  94206. }
  94207. return firstPromise;
  94208. });
  94209. };
  94210. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94211. var _this = this;
  94212. // Don't load material LODs if already loading a node LOD.
  94213. if (this._loadingNodeLOD) {
  94214. return null;
  94215. }
  94216. return this._loadExtensionAsync(context, material, function (context, extension) {
  94217. var firstPromise;
  94218. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94219. var _loop_2 = function (indexLOD) {
  94220. var materialLOD = materialLODs[indexLOD];
  94221. if (indexLOD !== 0) {
  94222. _this._loadingMaterialLOD = materialLOD;
  94223. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94224. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94225. }
  94226. }
  94227. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94228. if (indexLOD !== 0) {
  94229. assign(materialLOD._babylonMaterial);
  94230. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94231. if (previousMaterialLOD._babylonMaterial) {
  94232. previousMaterialLOD._babylonMaterial.dispose();
  94233. delete previousMaterialLOD._babylonMaterial;
  94234. }
  94235. }
  94236. if (indexLOD !== materialLODs.length - 1) {
  94237. var materialIndex = materialLODs[indexLOD + 1]._index;
  94238. if (_this._loadMaterialSignals[materialIndex]) {
  94239. _this._loadMaterialSignals[materialIndex].resolve();
  94240. delete _this._loadMaterialSignals[materialIndex];
  94241. }
  94242. }
  94243. });
  94244. if (indexLOD === 0) {
  94245. firstPromise = promise;
  94246. }
  94247. else {
  94248. _this._loader._completePromises.push(promise);
  94249. _this._loadingMaterialLOD = null;
  94250. }
  94251. };
  94252. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94253. _loop_2(indexLOD);
  94254. }
  94255. return firstPromise;
  94256. });
  94257. };
  94258. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94259. var _this = this;
  94260. // Defer the loading of uris if loading a material or node LOD.
  94261. if (this._loadingMaterialLOD) {
  94262. var index = this._loadingMaterialLOD._index;
  94263. return this._loadMaterialSignals[index].promise.then(function () {
  94264. return _this._loader._loadUriAsync(context, uri);
  94265. });
  94266. }
  94267. else if (this._loadingNodeLOD) {
  94268. var index = this._loadingNodeLOD._index;
  94269. return this._loadNodeSignals[index].promise.then(function () {
  94270. return _this._loader._loadUriAsync(context, uri);
  94271. });
  94272. }
  94273. return null;
  94274. };
  94275. /**
  94276. * Gets an array of LOD properties from lowest to highest.
  94277. */
  94278. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94279. if (this.maxLODsToLoad <= 0) {
  94280. throw new Error("maxLODsToLoad must be greater than zero");
  94281. }
  94282. var properties = new Array();
  94283. for (var i = ids.length - 1; i >= 0; i--) {
  94284. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94285. if (properties.length === this.maxLODsToLoad) {
  94286. return properties;
  94287. }
  94288. }
  94289. properties.push(property);
  94290. return properties;
  94291. };
  94292. return MSFT_lod;
  94293. }(GLTF2.GLTFLoaderExtension));
  94294. Extensions.MSFT_lod = MSFT_lod;
  94295. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94296. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94297. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94298. })(BABYLON || (BABYLON = {}));
  94299. //# sourceMappingURL=MSFT_lod.js.map
  94300. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94301. var BABYLON;
  94302. (function (BABYLON) {
  94303. var GLTF2;
  94304. (function (GLTF2) {
  94305. var Extensions;
  94306. (function (Extensions) {
  94307. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94308. var NAME = "KHR_draco_mesh_compression";
  94309. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94310. __extends(KHR_draco_mesh_compression, _super);
  94311. function KHR_draco_mesh_compression(loader) {
  94312. var _this = _super.call(this, loader) || this;
  94313. _this.name = NAME;
  94314. _this._dracoCompression = null;
  94315. // Disable extension if decoder is not available.
  94316. if (!BABYLON.DracoCompression.DecoderUrl) {
  94317. _this.enabled = false;
  94318. }
  94319. return _this;
  94320. }
  94321. KHR_draco_mesh_compression.prototype.dispose = function () {
  94322. if (this._dracoCompression) {
  94323. this._dracoCompression.dispose();
  94324. }
  94325. _super.prototype.dispose.call(this);
  94326. };
  94327. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94328. var _this = this;
  94329. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94330. if (primitive.mode != undefined) {
  94331. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94332. primitive.mode !== 4 /* TRIANGLES */) {
  94333. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94334. }
  94335. // TODO: handle triangle strips
  94336. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94337. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94338. }
  94339. }
  94340. var attributes = {};
  94341. var loadAttribute = function (name, kind) {
  94342. var uniqueId = extension.attributes[name];
  94343. if (uniqueId == undefined) {
  94344. return;
  94345. }
  94346. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94347. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94348. babylonMesh._delayInfo.push(kind);
  94349. }
  94350. attributes[kind] = uniqueId;
  94351. };
  94352. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94353. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94354. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94355. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94356. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94357. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94358. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94359. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94360. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94361. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94362. try {
  94363. if (!_this._dracoCompression) {
  94364. _this._dracoCompression = new BABYLON.DracoCompression();
  94365. }
  94366. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94367. }
  94368. catch (e) {
  94369. throw new Error(context + ": " + e.message);
  94370. }
  94371. });
  94372. });
  94373. };
  94374. return KHR_draco_mesh_compression;
  94375. }(GLTF2.GLTFLoaderExtension));
  94376. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94377. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94378. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94379. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94380. })(BABYLON || (BABYLON = {}));
  94381. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94382. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94383. var BABYLON;
  94384. (function (BABYLON) {
  94385. var GLTF2;
  94386. (function (GLTF2) {
  94387. var Extensions;
  94388. (function (Extensions) {
  94389. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94390. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94391. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94392. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94393. function KHR_materials_pbrSpecularGlossiness() {
  94394. var _this = _super !== null && _super.apply(this, arguments) || this;
  94395. _this.name = NAME;
  94396. return _this;
  94397. }
  94398. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94399. var _this = this;
  94400. return this._loadExtensionAsync(context, material, function (context, extension) {
  94401. material._babylonMeshes = material._babylonMeshes || [];
  94402. material._babylonMeshes.push(babylonMesh);
  94403. if (!material._loaded) {
  94404. var promises = new Array();
  94405. var babylonMaterial = _this._loader._createMaterial(material);
  94406. material._babylonMaterial = babylonMaterial;
  94407. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94408. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94409. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94410. material._loaded = Promise.all(promises).then(function () { });
  94411. }
  94412. assign(material._babylonMaterial);
  94413. return material._loaded;
  94414. });
  94415. };
  94416. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94417. var promises = new Array();
  94418. var babylonMaterial = material._babylonMaterial;
  94419. if (properties.diffuseFactor) {
  94420. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94421. babylonMaterial.alpha = properties.diffuseFactor[3];
  94422. }
  94423. else {
  94424. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94425. }
  94426. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94427. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94428. if (properties.diffuseTexture) {
  94429. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94430. babylonMaterial.albedoTexture = texture;
  94431. }));
  94432. }
  94433. if (properties.specularGlossinessTexture) {
  94434. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94435. babylonMaterial.reflectivityTexture = texture;
  94436. }));
  94437. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94438. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94439. }
  94440. this._loader._loadMaterialAlphaProperties(context, material);
  94441. return Promise.all(promises).then(function () { });
  94442. };
  94443. return KHR_materials_pbrSpecularGlossiness;
  94444. }(GLTF2.GLTFLoaderExtension));
  94445. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94446. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94447. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94448. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94449. })(BABYLON || (BABYLON = {}));
  94450. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94451. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94452. var BABYLON;
  94453. (function (BABYLON) {
  94454. var GLTF2;
  94455. (function (GLTF2) {
  94456. var Extensions;
  94457. (function (Extensions) {
  94458. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94459. var NAME = "KHR_lights";
  94460. var LightType;
  94461. (function (LightType) {
  94462. LightType["AMBIENT"] = "ambient";
  94463. LightType["DIRECTIONAL"] = "directional";
  94464. LightType["POINT"] = "point";
  94465. LightType["SPOT"] = "spot";
  94466. })(LightType || (LightType = {}));
  94467. var KHR_lights = /** @class */ (function (_super) {
  94468. __extends(KHR_lights, _super);
  94469. function KHR_lights() {
  94470. var _this = _super !== null && _super.apply(this, arguments) || this;
  94471. _this.name = NAME;
  94472. return _this;
  94473. }
  94474. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94475. var _this = this;
  94476. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94477. var promise = _this._loader._loadSceneAsync(context, scene);
  94478. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94479. if (light.type !== LightType.AMBIENT) {
  94480. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94481. }
  94482. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94483. return promise;
  94484. });
  94485. };
  94486. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94487. var _this = this;
  94488. return this._loadExtensionAsync(context, node, function (context, extension) {
  94489. var promise = _this._loader._loadNodeAsync(context, node);
  94490. var babylonLight;
  94491. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94492. var name = node._babylonMesh.name;
  94493. switch (light.type) {
  94494. case LightType.AMBIENT: {
  94495. throw new Error(context + ": Ambient lights are not allowed on a node");
  94496. }
  94497. case LightType.DIRECTIONAL: {
  94498. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94499. break;
  94500. }
  94501. case LightType.POINT: {
  94502. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94503. break;
  94504. }
  94505. case LightType.SPOT: {
  94506. var spotLight = light;
  94507. // TODO: support inner and outer cone angles
  94508. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94509. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94510. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94511. break;
  94512. }
  94513. default: {
  94514. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94515. }
  94516. }
  94517. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94518. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94519. babylonLight.parent = node._babylonMesh;
  94520. return promise;
  94521. });
  94522. };
  94523. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94524. get: function () {
  94525. var extensions = this._loader._gltf.extensions;
  94526. if (!extensions || !extensions[this.name]) {
  94527. throw new Error("#/extensions: '" + this.name + "' not found");
  94528. }
  94529. var extension = extensions[this.name];
  94530. return extension.lights;
  94531. },
  94532. enumerable: true,
  94533. configurable: true
  94534. });
  94535. return KHR_lights;
  94536. }(GLTF2.GLTFLoaderExtension));
  94537. Extensions.KHR_lights = KHR_lights;
  94538. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94539. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94540. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94541. })(BABYLON || (BABYLON = {}));
  94542. //# sourceMappingURL=KHR_lights.js.map
  94543. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94544. globalObject["BABYLON"] = BABYLON
  94545. return BABYLON;
  94546. });